file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
list | attention_mask
list | labels
list |
---|---|---|---|---|---|---|
pragma solidity 0.6.2;
//based SWC
contract Refunder {
address payable[] private refundAddresses;
mapping (address => uint) public refunds;
constructor() public{
refundAddresses.push(0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359);
refundAddresses.push(0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed);
}
// bad
function refundAll() public {
for(uint256 x = 0; x < refundAddresses.length; x++) { // arbitrary length iteration based on how many addresses participated
//The call fails when the address with which it interacts does not exist or when a contract exception occurs.
require(refundAddresses[x].send(refunds[refundAddresses[x]])); // doubly bad, now a single failure on send will hold up all funds
}
}
//bad too
function refundAll_1() public {
for(uint256 x = 0; x < refundAddresses.length; x++) { // arbitrary length iteration based on how many addresses participated
refundAddresses[x].transfer(refunds[refundAddresses[x]]); // doubly bad, now a single failure on send will hold up all funds
}
}
} | arbitrary length iteration based on how many addresses participated
| for(uint256 x = 0; x < refundAddresses.length; x++) { | 2,562,261 | [
1,
297,
3682,
3345,
769,
6532,
2511,
603,
3661,
4906,
6138,
30891,
690,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
364,
12,
11890,
5034,
619,
273,
374,
31,
619,
411,
16255,
7148,
18,
2469,
31,
619,
27245,
288,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0xdac4f0d74592012eb4baeb608b1992ffe5cc537a
//Contract name: WorldCupBroker
//Balance: 1.88335987807420416 Ether
//Verification Date: 6/9/2018
//Transacion Count: 33
// CODE STARTS HERE
pragma solidity ^0.4.18;
// File: contracts/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: contracts/strings.sol
/*
* @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.
*/
pragma solidity ^0.4.14;
library strings {
struct slice {
uint _len;
uint _ptr;
}
function memcpy(uint dest, uint src, uint len) private pure {
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/*
* @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 pure 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 pure 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-terminated utf-8 string.
* @param self The bytes32 value to convert to a slice.
* @return A new slice containing the value of the input argument up to the
* first null.
*/
function toSliceB32(bytes32 self) internal pure returns (slice 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 pure 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 pure returns (string) {
string memory ret = new string(self._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
return ret;
}
/*
* @dev Returns the length in runes of the slice. Note that this operation
* takes time proportional to the length of the slice; avoid using it
* in loops, and call `slice.empty()` if you only need to know whether
* the slice is empty or not.
* @param self The slice to operate on.
* @return The length of the slice in runes.
*/
function len(slice self) internal pure returns (uint l) {
// Starting at ptr-31 means the LSB will be the byte we care about
uint ptr = self._ptr - 31;
uint end = ptr + self._len;
for (l = 0; ptr < end; l++) {
uint8 b;
assembly { b := and(mload(ptr), 0xFF) }
if (b < 0x80) {
ptr += 1;
} else if(b < 0xE0) {
ptr += 2;
} else if(b < 0xF0) {
ptr += 3;
} else if(b < 0xF8) {
ptr += 4;
} else if(b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
}
/*
* @dev Returns true if the slice is empty (has a length of 0).
* @param self The slice to operate on.
* @return True if the slice is empty, False otherwise.
*/
function empty(slice self) internal pure returns (bool) {
return self._len == 0;
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two slices are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first slice to compare.
* @param other The second slice to compare.
* @return The result of the comparison.
*/
function compare(slice self, slice other) internal pure returns (int) {
uint shortest = self._len;
if (other._len < self._len)
shortest = other._len;
uint selfptr = self._ptr;
uint otherptr = other._ptr;
for (uint idx = 0; idx < shortest; idx += 32) {
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint256 mask = uint256(-1); // 0xffff...
if(shortest < 32) {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint256 diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(self._len) - int(other._len);
}
/*
* @dev Returns true if the two slices contain the same text.
* @param self The first slice to compare.
* @param self The second slice to compare.
* @return True if the slices are equal, false otherwise.
*/
function equals(slice self, slice other) internal pure returns (bool) {
return compare(self, other) == 0;
}
/*
* @dev Extracts the first rune in the slice into `rune`, advancing the
* slice to point to the next rune and returning `self`.
* @param self The slice to operate on.
* @param rune The slice that will contain the first rune.
* @return `rune`.
*/
function nextRune(slice self, slice rune) internal pure returns (slice) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint l;
uint b;
// Load the first byte of the rune into the LSBs of b
assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }
if (b < 0x80) {
l = 1;
} else if(b < 0xE0) {
l = 2;
} else if(b < 0xF0) {
l = 3;
} else {
l = 4;
}
// Check for truncated codepoints
if (l > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += l;
self._len -= l;
rune._len = l;
return rune;
}
/*
* @dev Returns the first rune in the slice, advancing the slice to point
* to the next rune.
* @param self The slice to operate on.
* @return A slice containing only the first rune from `self`.
*/
function nextRune(slice self) internal pure 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 pure returns (uint ret) {
if (self._len == 0) {
return 0;
}
uint word;
uint length;
uint divisor = 2 ** 248;
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
uint b = word / divisor;
if (b < 0x80) {
ret = b;
length = 1;
} else if(b < 0xE0) {
ret = b & 0x1F;
length = 2;
} else if(b < 0xF0) {
ret = b & 0x0F;
length = 3;
} else {
ret = b & 0x07;
length = 4;
}
// Check for truncated codepoints
if (length > self._len) {
return 0;
}
for (uint i = 1; i < length; i++) {
divisor = divisor / 256;
b = (word / divisor) & 0xFF;
if (b & 0xC0 != 0x80) {
// Invalid UTF-8 sequence
return 0;
}
ret = (ret * 64) | (b & 0x3F);
}
return ret;
}
/*
* @dev Returns the keccak-256 hash of the slice.
* @param self The slice to hash.
* @return The hash of the slice.
*/
function keccak(slice self) internal pure returns (bytes32 ret) {
assembly {
ret := keccak256(mload(add(self, 32)), mload(self))
}
}
/*
* @dev Returns true if `self` starts with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function startsWith(slice self, slice needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` starts with `needle`, `needle` is removed from the
* beginning of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function beyond(slice self, slice needle) internal pure returns (slice) {
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(sha3(selfptr, length), sha3(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
self._ptr += needle._len;
}
return self;
}
/*
* @dev Returns true if the slice ends with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function endsWith(slice self, slice needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
uint selfptr = self._ptr + self._len - needle._len;
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` ends with `needle`, `needle` is removed from the
* end of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function until(slice self, slice needle) internal pure returns (slice) {
if (self._len < needle._len) {
return self;
}
uint selfptr = self._ptr + self._len - needle._len;
bool equal = true;
if (selfptr != needle._ptr) {
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
}
return self;
}
event log_bytemask(bytes32 mask);
// Returns the memory address of the first byte of the first occurrence of
// `needle` in `self`, or the first byte after `self` if not found.
function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr = selfptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
uint end = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr >= end)
return selfptr + selflen;
ptr++;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := sha3(needleptr, needlelen) }
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 pure returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
ptr = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr <= selfptr)
return selfptr;
ptr--;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr + needlelen;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := 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 pure 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 pure 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 pure 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 pure 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 pure 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 pure 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 pure returns (uint cnt) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
/*
* @dev Returns True if `self` contains `needle`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return True if `needle` is found in `self`, false otherwise.
*/
function contains(slice self, slice needle) internal pure returns (bool) {
return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;
}
/*
* @dev Returns a newly allocated string containing the concatenation of
* `self` and `other`.
* @param self The first slice to concatenate.
* @param other The second slice to concatenate.
* @return The concatenation of the two strings.
*/
function concat(slice self, slice other) internal pure returns (string) {
string memory ret = new string(self._len + other._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
memcpy(retptr + self._len, other._ptr, other._len);
return ret;
}
/*
* @dev Joins an array of slices, using `self` as a delimiter, returning a
* newly allocated string.
* @param self The delimiter to use.
* @param parts A list of slices to join.
* @return A newly allocated string containing all the slices in `parts`,
* joined with `self`.
*/
function join(slice self, slice[] parts) internal pure returns (string) {
if (parts.length == 0)
return "";
uint length = self._len * (parts.length - 1);
for(uint i = 0; i < parts.length; i++)
length += parts[i]._len;
string memory ret = new string(length);
uint retptr;
assembly { retptr := add(ret, 32) }
for(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;
}
}
// File: contracts/usingOraclize.sol
// <ORACLIZE_API>
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary
pragma solidity ^0.4.18;
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID; // silence the warning and remain backwards compatible
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
myid; result; proof; // Silence compiler warnings
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal pure returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr) internal pure returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
function ba2cbor(bytes[] arr) internal pure returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
// Convert from seconds to ledger timer ticks
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = byte(1); //role
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
require(prefix.length == n_random_bytes);
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
// Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
// verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
// Buffer too small
require(to.length >= minLength); // Should be a better way?
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
}
// </ORACLIZE_API>
// File: contracts/WorldCupBroker.sol
/*
* @title String & slice utility library for Solidity contracts.
* @author Daniel Bennett <[email protected]>
*
* @dev This is a solitidy contract that facilitates betting for the 2018
world cup. The contract on does not act as a counter party
to any bets placed and thus users bet on a decision pool for a match
(win, lose, draw), and based on the results of users will be credited winnings
proportional to their contributions to the winning pool.
*/
pragma solidity ^0.4.4;
contract WorldCupBroker is Ownable, usingOraclize {
using strings for *;
struct Bet {
bool cancelled;
bool claimed;
uint amount;
uint8 option; // 1 - teamA, 2 - teamB, 3 - Draw
address better;
}
struct Match {
bool locked; // match will be locked after payout or all bets returned
bool cancelled;
uint8 teamA;
uint8 teamB;
uint8 winner; // 0 - not set, 1 - teamA, 2 - teamB, 3- Draw, 4 - no winner
uint start;
uint closeBettingTime; // since this the close delay is constant
// this will always be the same, save gas for betters and just set the close time once
uint totalTeamABets;
uint totalTeamBBets;
uint totalDrawBets;
uint numBets;
string fixtureId;
string secondaryFixtureId;
bool inverted; // inverted if the secondary api has the home team and away teams inverted
string name;
mapping(uint => Bet) bets;
}
event MatchCreated(uint8);
event MatchUpdated(uint8);
event MatchFailedPayoutRelease(uint8);
event BetPlaced(
uint8 matchId,
uint8 outcome,
uint betId,
uint amount,
address better
);
event BetClaimed(
uint8 matchId,
uint betId
);
event BetCancelled(
uint8 matchId,
uint betId
);
string[32] public TEAMS = [
"Russia",
"Saudi Arabia",
"Egypt",
"Uruguay",
"Morocco",
"Iran",
"Portugal",
"Spain",
"France",
"Australia",
"Argentina",
"Iceland",
"Peru",
"Denmark",
"Croatia",
"Nigeria",
"Costa Rica",
"Serbia",
"Germany",
"Mexico",
"Brazil",
"Switzerland",
"Sweden",
"South Korea",
"Belgium",
"Panama",
"Tunisia",
"England",
"Poland",
"Senegal",
"Colombia",
"Japan"
];
uint public constant MAX_NUM_PAYOUT_ATTEMPTS = 3; // after 3 consecutive failed payout attempts, lock the match
uint public constant PAYOUT_ATTEMPT_INTERVAL = 10 minutes; // try every 10 minutes to release payout
uint public commission_rate = 7;
uint public minimum_bet = 0.01 ether;
uint private commissions = 0;
uint public primaryGasLimit = 225000;
uint public secondaryGasLimit = 250000;
Match[] matches;
mapping(bytes32 => uint8) oraclizeIds;
mapping(uint8 => uint8) payoutAttempts;
mapping(uint8 => bool) firstStepVerified;
mapping(uint8 => uint8) pendingWinner;
/*
* @dev Ensures a matchId points to a legitimate match
* @param _matchId the uint to check if it points to a valid match.
*/
modifier validMatch(uint8 _matchId) {
require(_matchId < uint8(matches.length));
_;
}
/*
* @dev the validBet modifier does as it's name implies and ensures that a bet
* is valid before proceeding with any methods called on the contract
* that would require access to such a bet
* @param _matchId the uint to check if it points to a valid match.
* @param _betId the uint to check if it points to a valid bet for a match.
*/
modifier validBet(uint8 _matchId, uint _betId) {
// short circuit to save gas
require(_matchId < uint8(matches.length) && _betId < matches[_matchId].numBets);
_;
}
/*
* @dev Adds a new match to the smart contract and schedules an oraclize query call
* to determine the winner of a match within 3 hours. Additionally emits an event
* signifying a match was created.
* @param _name the unique identifier of the match, should be of format Stage:Team A vs Team B
* @param _fixture the fixtureId for the football-data.org endpoint
* @param _secondary the fixtureId for the sportsmonk.com endpoint
* @param _inverted should be set to true if the teams are inverted on either of the API
* that is if the hometeam and localteam are swapped
* @param _teamA index of the homeTeam from the TEAMS array
* @param _teamB index of the awayTeam from the TEAMS array
* @param _start the unix timestamp for when the match is scheduled to begin
* @return `uint` the Id of the match in the matches array
*/
function addMatch(string _name, string _fixture, string _secondary, bool _invert, uint8 _teamA, uint8 _teamB, uint _start) public onlyOwner returns (uint8) {
// Check that there's at least 15 minutes until the match starts
require(_teamA < 32 && _teamB < 32 && _teamA != _teamB && (_start - 15 minutes) >= now);
Match memory newMatch = Match({
locked: false,
cancelled: false,
teamA: _teamA,
teamB: _teamB,
winner: 0,
fixtureId: _fixture, // The primary fixtureId that will be used to query the football-data API
secondaryFixtureId: _secondary, // The secondary fixtureID used to query sports monk
inverted: _invert,
start: _start,
closeBettingTime: _start - 3 minutes, // betting closes 3 minutes before a match starts
totalTeamABets: 0,
totalTeamBBets: 0,
totalDrawBets: 0,
numBets: 0,
name: _name
});
uint8 matchId = uint8(matches.push(newMatch)) - 1;
// concatinate oraclize query
string memory url = strConcat(
"[URL] json(https://soccer.sportmonks.com/api/v2.0/fixtures/",
newMatch.secondaryFixtureId,
"?api_token=${[decrypt] BNxYykO2hsQ7iA7yRuDLSu1km6jFZwN5X87TY1BSmU30llRn8uWkJjHgx+YGytA1tmbRjb20CW0gIzcFmvq3yLZnitsvW28SPjlf+s9MK7hU+uRXqwhoW6dmWqKsBrCigrggFwMBRk4kA16jugtIr+enXHjOnAKSxd1dO4YXTCYvZc3T1pFA9PVyFFnd}).data.scores[localteam_score,visitorteam_score]");
// store the oraclize query id for later use
// use hours to over estimate the amount of time it would take to safely get a correct result
// 90 minutes of regulation play time + potential 30 minutes of extra time + 15 minutes break
// + potential 10 minutes of stoppage time + potential 10 minutes of penalties
// + 25 minutes of time for any APIs to correct and ensure their information is correct
bytes32 oraclizeId = oraclize_query((_start + (3 hours)), "nested", url, primaryGasLimit);
oraclizeIds[oraclizeId] = matchId;
emit MatchCreated(matchId);
return matchId;
}
function cancelMatch(uint8 _matchId) public onlyOwner validMatch(_matchId) returns (bool) {
Match storage mtch = matches[_matchId];
require(!mtch.cancelled && now < mtch.closeBettingTime);
mtch.cancelled = true;
mtch.locked = true;
emit MatchUpdated(_matchId);
return true;
}
/*
* @dev returns the number of matches on the contract
*/
function getNumMatches() public view returns (uint) {
return matches.length;
}
/*
* @dev Returns some of the properties of a match. Functionality had to be seperated
* into 2 function calls to prevent stack too deep errors
* @param _matchId the index of that match in the matches array
* @return `string` the match name
* @return `string` the fixutre Id of the match for the football-data endpoint
* @return `string` the fixture Id fo the match for the sports monk endpoint
* @return `uint8` the index of the home team
* @return `uint8` the index of the away team
* @return `uint8` the winner of the match
* @return `uint` the unix timestamp for the match start time
* @return `bool` Match cancelled boolean
* @return `bool` Match locked boolean which is set to true if the match is payed out or bets are returned
*/
function getMatch(uint8 _matchId) public view validMatch(_matchId) returns (string, string, string, bool, uint8, uint8, uint8, uint, bool, bool) {
Match memory mtch = matches[_matchId];
return (
mtch.name,
mtch.fixtureId,
mtch.secondaryFixtureId,
mtch.inverted,
mtch.teamA,
mtch.teamB,
mtch.winner,
mtch.start,
mtch.cancelled,
mtch.locked
);
}
/*
* @dev Returns remaining of the properties of a match. Functionality had to be seperated
* into 2 function calls to prevent stack too deep errors
* @param _matchId the index of that match in the matches array
* @return `uint` timestamp for when betting for the match closes
* @return `uint` total size of the home team bet pool
* @return `uint` total size of the away team bet pool
* @return `uint` total size of the draw bet pool
* @return `uint` the total number of bets
* @return `uint8` the number of payout attempts for the match
*/
function getMatchBettingDetails(uint8 _matchId) public view validMatch(_matchId) returns (uint, uint, uint, uint, uint, uint8) {
Match memory mtch = matches[_matchId];
return (
mtch.closeBettingTime,
mtch.totalTeamABets,
mtch.totalTeamBBets,
mtch.totalDrawBets,
mtch.numBets,
payoutAttempts[_matchId]
);
}
/*
* @dev Adds a new bet to a match with the outcome passed where there are 3 possible outcomes
* homeTeam wins(1), awayTeam wins(2), draw(3). While it is possible for some matches
* to end in a draw, not all matches will have the possibility of ending in a draw
* this functionality will be added in front end code to prevent betting on invalid decisions.
* Emits a BetPlaced event.
* @param _matchId the index of the match in matches that the bet is for
* @param _outcome the possible outcome for the match that this bet is betting on
* @return `uint` the Id of the bet in a match's bet array
*/
function placeBet(uint8 _matchId, uint8 _outcome) public payable validMatch(_matchId) returns (uint) {
Match storage mtch = matches[_matchId];
// A bet must be a valid option, 1, 2, or 3, and cannot be less that the minimum bet amount
require(
!mtch.locked &&
!mtch.cancelled &&
now < mtch.closeBettingTime &&
_outcome > 0 &&
_outcome < 4 &&
msg.value >= minimum_bet
);
Bet memory bet = Bet(false, false, msg.value, _outcome, msg.sender);
uint betId = mtch.numBets;
mtch.bets[betId] = bet;
mtch.numBets++;
if (_outcome == 1) {
mtch.totalTeamABets += msg.value;
// a bit of safe math checking here
assert(mtch.totalTeamABets >= msg.value);
} else if (_outcome == 2) {
mtch.totalTeamBBets += msg.value;
assert(mtch.totalTeamBBets >= msg.value);
} else {
mtch.totalDrawBets += msg.value;
assert(mtch.totalDrawBets >= msg.value);
}
// emit bet placed event
emit BetPlaced(_matchId, _outcome, betId, msg.value, msg.sender);
return (betId);
}
/*
* @dev Returns the properties of a bet for a match
* @param _matchId the index of that match in the matches array
* @param _betId the index of that bet in the match bets array
* @return `address` the address that placed the bet and thus it's owner
* @return `uint` the amount that was bet
* @return `uint` the option that was bet on
* @return `bool` wether or not the bet had been cancelled
*/
function getBet(uint8 _matchId, uint _betId) public view validBet(_matchId, _betId) returns (address, uint, uint, bool, bool) {
Bet memory bet = matches[_matchId].bets[_betId];
// Don't return matchId and betId since you had to know them in the first place
return (bet.better, bet.amount, bet.option, bet.cancelled, bet.claimed);
}
/*
* @dev Cancel's a bet and returns the amount - commission fee. Emits a BetCancelled event
* @param _matchId the index of that match in the matches array
* @param _betId the index of that bet in the match bets array
*/
function cancelBet(uint8 _matchId, uint _betId) public validBet(_matchId, _betId) {
Match memory mtch = matches[_matchId];
require(!mtch.locked && now < mtch.closeBettingTime);
Bet storage bet = matches[_matchId].bets[_betId];
// only the person who made this bet can cancel it
require(!bet.cancelled && !bet.claimed && bet.better == msg.sender );
// stop re-entry just in case of malicious attack to withdraw all contract eth
bet.cancelled = true;
uint commission = bet.amount / 100 * commission_rate;
commissions += commission;
assert(commissions >= commission);
if (bet.option == 1) {
matches[_matchId].totalTeamABets -= bet.amount;
} else if (bet.option == 2) {
matches[_matchId].totalTeamBBets -= bet.amount;
} else if (bet.option == 3) {
matches[_matchId].totalDrawBets -= bet.amount;
}
bet.better.transfer(bet.amount - commission);
emit BetCancelled(_matchId, _betId);
}
/*
* @dev Betters can claim there winnings using this method or reclaim their bet
* if the match was cancelled
* @param _matchId the index of the match in the matches array
* @param _betId the bet being claimed
*/
function claimBet(uint8 _matchId, uint8 _betId) public validBet(_matchId, _betId) {
Match storage mtch = matches[_matchId];
Bet storage bet = mtch.bets[_betId];
// ensures the match has been locked (payout either done or bets returned)
// dead man's switch to prevent bets from ever getting locked in the contrat
// from insufficient funds during an oracalize query
// if the match isn't locked or cancelled, then you can claim your bet after
// the world cup is over (noon July 16)
require((mtch.locked || now >= 1531742400) &&
!bet.claimed &&
!bet.cancelled &&
msg.sender == bet.better
);
bet.claimed = true;
if (mtch.winner == 0) {
// If the match is locked with no winner set
// then either it was cancelled or a winner couldn't be determined
// transfer better back their bet amount
bet.better.transfer(bet.amount);
} else {
if (bet.option != mtch.winner) {
return;
}
uint totalPool;
uint winPool;
if (mtch.winner == 1) {
totalPool = mtch.totalTeamBBets + mtch.totalDrawBets;
// once again do some safe math
assert(totalPool >= mtch.totalTeamBBets);
winPool = mtch.totalTeamABets;
} else if (mtch.winner == 2) {
totalPool = mtch.totalTeamABets + mtch.totalDrawBets;
assert(totalPool >= mtch.totalTeamABets);
winPool = mtch.totalTeamBBets;
} else {
totalPool = mtch.totalTeamABets + mtch.totalTeamBBets;
assert(totalPool >= mtch.totalTeamABets);
winPool = mtch.totalDrawBets;
}
uint winnings = totalPool * bet.amount / winPool;
// calculate commissions percentage
uint commission = winnings / 100 * commission_rate;
commissions += commission;
assert(commissions >= commission);
// return original bet amount + winnings - commission
bet.better.transfer(winnings + bet.amount - commission);
}
emit BetClaimed(_matchId, _betId);
}
/*
* @dev Change the commission fee for the contract. The fee can never exceed 7%
* @param _newCommission the new fee rate to be charged in wei
*/
function changeFees(uint8 _newCommission) public onlyOwner {
// Max commission is 7%, but it can be FREE!!
require(_newCommission <= 7);
commission_rate = _newCommission;
}
/*
* @dev Withdraw a portion of the commission from the commission pool.
* @param _amount the amount of commission to be withdrawn
*/
function withdrawCommissions(uint _amount) public onlyOwner {
require(_amount <= commissions);
commissions -= _amount;
owner.transfer(_amount);
}
/*
* @dev Destroy the contract but only after the world cup is over for a month
*/
function withdrawBalance() public onlyOwner {
// World cup is over for a full month withdraw the full balance of the contract
// and destroy it to free space on the blockchain
require(now >= 1534291200); // This is 12am August 15, 2018
selfdestruct(owner);
}
/*
* @dev Change the minimum bet amount. Just in case the price of eth skyrockets or drops.
* @param _newMin the new minimum bet amount
*/
function changeMiniumBet(uint _newMin) public onlyOwner {
minimum_bet = _newMin;
}
/*
* @dev sets the gas price to be used for oraclize quries in the contract
* @param _price the price of each gas
*/
function setGasPrice(uint _price) public onlyOwner {
require(_price >= 20000000000 wei);
oraclize_setCustomGasPrice(_price);
}
/*
* @dev Oraclize query callback to determine the winner of the match.
* @param _myid the id for the oraclize query that is being returned
* @param _result the result of the query
*/
function __callback(bytes32 _myid, string _result) public {
// only oraclize can call this method
if (msg.sender != oraclize_cbAddress()) revert();
uint8 matchId = oraclizeIds[_myid];
Match storage mtch = matches[matchId];
require(!mtch.locked && !mtch.cancelled);
bool firstVerification = firstStepVerified[matchId];
// If there is no result or the result is null we want to do the following
if (bytes(_result).length == 0 || (keccak256(_result) == keccak256("[null, null]"))) {
// If max number of attempts has been reached then return all bets
if (++payoutAttempts[matchId] >= MAX_NUM_PAYOUT_ATTEMPTS) {
mtch.locked = true;
emit MatchFailedPayoutRelease(matchId);
} else {
emit MatchUpdated(matchId);
string memory url;
string memory querytype;
uint limit;
// if the contract has already verified the sportsmonks api
// use football-data.org as a secondary source of truth
if (firstVerification) {
url = strConcat(
"json(https://api.football-data.org/v1/fixtures/",
matches[matchId].fixtureId,
").fixture.result.[goalsHomeTeam,goalsAwayTeam]");
querytype = "URL";
limit = secondaryGasLimit;
} else {
url = strConcat(
"[URL] json(https://soccer.sportmonks.com/api/v2.0/fixtures/",
matches[matchId].secondaryFixtureId,
"?api_token=${[decrypt] BNxYykO2hsQ7iA7yRuDLSu1km6jFZwN5X87TY1BSmU30llRn8uWkJjHgx+YGytA1tmbRjb20CW0gIzcFmvq3yLZnitsvW28SPjlf+s9MK7hU+uRXqwhoW6dmWqKsBrCigrggFwMBRk4kA16jugtIr+enXHjOnAKSxd1dO4YXTCYvZc3T1pFA9PVyFFnd}).data.scores[localteam_score,visitorteam_score]");
querytype = "nested";
// use primary gas limit since that query won't payout winners on callback
limit = primaryGasLimit;
}
bytes32 oraclizeId = oraclize_query(PAYOUT_ATTEMPT_INTERVAL, querytype, url, limit);
oraclizeIds[oraclizeId] = matchId;
}
} else {
payoutAttempts[matchId] = 0;
// eg. result = "[2, 4]"
strings.slice memory s = _result.toSlice();
// remove the braces from the result
s = s.beyond("[".toSlice());
s = s.until("]".toSlice());
// split the string to get the two string encoded ints
strings.slice memory x = s.split(", ".toSlice());
// parse them to int to get the scores
uint homeScore = parseInt(s.toString());
uint awayScore = parseInt(x.toString());
uint8 matchResult;
// determine the winner
if (homeScore > awayScore) {
matchResult = 1;
} else if (homeScore < awayScore) {
matchResult = 2;
} else {
matchResult = 3;
}
// if this is the query to sportsmonks
if (!firstVerification) {
// set pending winner and call the second source of truth
pendingWinner[matchId] = matchResult;
firstStepVerified[matchId] = true;
url = strConcat(
"json(https://api.football-data.org/v1/fixtures/",
matches[matchId].fixtureId,
").fixture.result.[goalsHomeTeam,goalsAwayTeam]");
oraclizeId = oraclize_query("nested", url, secondaryGasLimit);
oraclizeIds[oraclizeId] = matchId;
} else {
mtch.locked = true;
// if one of the APIs has the teams inverted then flip the result
if (matches[matchId].inverted) {
if (matchResult == 1) {
matchResult = 2;
} else if (matchResult == 2) {
matchResult = 1;
}
}
// if the both APIs confirm the same winner then payout the winners
if (pendingWinner[matchId] == matchResult) {
mtch.winner = matchResult;
emit MatchUpdated(matchId);
} else {
// else don't set a winner because a source of truth couldn't be verified
// this way users can still reclaim their original bet amount
emit MatchFailedPayoutRelease(matchId);
}
}
}
}
function() public payable {}
}
| @dev Adds a new bet to a match with the outcome passed where there are 3 possible outcomes homeTeam wins(1), awayTeam wins(2), draw(3). While it is possible for some matches to end in a draw, not all matches will have the possibility of ending in a draw this functionality will be added in front end code to prevent betting on invalid decisions. Emits a BetPlaced event. @param _matchId the index of the match in matches that the bet is for @param _outcome the possible outcome for the match that this bet is betting on @return `uint` the Id of the bet in a match's bet array/ A bet must be a valid option, 1, 2, or 3, and cannot be less that the minimum bet amount a bit of safe math checking here | function placeBet(uint8 _matchId, uint8 _outcome) public payable validMatch(_matchId) returns (uint) {
Match storage mtch = matches[_matchId];
require(
!mtch.locked &&
!mtch.cancelled &&
now < mtch.closeBettingTime &&
_outcome > 0 &&
_outcome < 4 &&
msg.value >= minimum_bet
);
Bet memory bet = Bet(false, false, msg.value, _outcome, msg.sender);
uint betId = mtch.numBets;
mtch.bets[betId] = bet;
mtch.numBets++;
if (_outcome == 1) {
mtch.totalTeamABets += msg.value;
assert(mtch.totalTeamABets >= msg.value);
mtch.totalTeamBBets += msg.value;
assert(mtch.totalTeamBBets >= msg.value);
mtch.totalDrawBets += msg.value;
assert(mtch.totalDrawBets >= msg.value);
}
return (betId);
}
| 1,790,199 | [
1,
3655,
279,
394,
2701,
358,
279,
845,
598,
326,
12884,
2275,
1625,
1915,
854,
890,
3323,
29867,
1377,
6382,
8689,
31307,
12,
21,
3631,
10804,
8689,
31307,
12,
22,
3631,
3724,
12,
23,
2934,
21572,
518,
353,
3323,
364,
2690,
1885,
1377,
358,
679,
316,
279,
3724,
16,
486,
777,
1885,
903,
1240,
326,
25547,
434,
11463,
316,
279,
3724,
1377,
333,
14176,
903,
506,
3096,
316,
6641,
679,
981,
358,
5309,
2701,
1787,
603,
2057,
2109,
12682,
18,
1377,
7377,
1282,
279,
605,
278,
6029,
72,
871,
18,
225,
389,
1916,
548,
282,
326,
770,
434,
326,
845,
316,
1885,
716,
326,
2701,
353,
364,
225,
389,
21672,
282,
326,
3323,
12884,
364,
326,
845,
716,
333,
2701,
353,
2701,
1787,
603,
327,
1375,
11890,
68,
565,
326,
3124,
434,
326,
2701,
316,
279,
845,
1807,
2701,
526,
19,
432,
2701,
1297,
506,
279,
923,
1456,
16,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
565,
445,
3166,
38,
278,
12,
11890,
28,
389,
1916,
548,
16,
2254,
28,
389,
21672,
13,
1071,
8843,
429,
923,
2060,
24899,
1916,
548,
13,
1135,
261,
11890,
13,
288,
203,
3639,
4639,
2502,
5874,
343,
273,
1885,
63,
67,
1916,
548,
15533,
203,
3639,
2583,
12,
203,
5411,
401,
1010,
343,
18,
15091,
597,
203,
5411,
401,
1010,
343,
18,
10996,
1259,
597,
203,
5411,
2037,
411,
5874,
343,
18,
4412,
38,
278,
1787,
950,
597,
203,
5411,
389,
21672,
405,
374,
597,
7010,
5411,
389,
21672,
411,
1059,
597,
7010,
5411,
1234,
18,
1132,
1545,
5224,
67,
70,
278,
203,
3639,
11272,
203,
3639,
605,
278,
3778,
2701,
273,
605,
278,
12,
5743,
16,
629,
16,
1234,
18,
1132,
16,
389,
21672,
16,
1234,
18,
15330,
1769,
203,
3639,
2254,
2701,
548,
273,
5874,
343,
18,
2107,
38,
2413,
31,
203,
3639,
5874,
343,
18,
70,
2413,
63,
70,
278,
548,
65,
273,
2701,
31,
203,
3639,
5874,
343,
18,
2107,
38,
2413,
9904,
31,
203,
3639,
309,
261,
67,
21672,
422,
404,
13,
288,
203,
5411,
5874,
343,
18,
4963,
8689,
2090,
2413,
1011,
1234,
18,
1132,
31,
203,
5411,
1815,
12,
1010,
343,
18,
4963,
8689,
2090,
2413,
1545,
1234,
18,
1132,
1769,
203,
5411,
5874,
343,
18,
4963,
8689,
9676,
2413,
1011,
1234,
18,
1132,
31,
203,
5411,
1815,
12,
1010,
343,
18,
4963,
8689,
9676,
2413,
1545,
1234,
18,
1132,
1769,
203,
5411,
5874,
343,
18,
4963,
6493,
38,
2413,
1011,
1234,
18,
1132,
31,
203,
5411,
2
] |
// SPDX-License-Identifier: Apache-2.0-or-later
/*
Copyright 2021 Rigo Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// solhint-disable-next-line
pragma solidity 0.7.6;
pragma abicoder v2; // in 0.8 solc this is default behaviour
import "../../../utils/exchanges/uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol";
import "../../../utils/exchanges/uniswap/v3-periphery/contracts/interfaces/IPeripheryPaymentsWithFee.sol";
import "../../../utils/exchanges/uniswap/v3-periphery/contracts/interfaces/IPeripheryImmutableState.sol";
import "../../../utils/exchanges/uniswap/v3-periphery/contracts/libraries/Path.sol";
interface Token {
function approve(address _spender, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256);
function balanceOf(address _who) external view returns (uint256);
}
/// @title Interface for WETH9
interface IWETH9 {
/// @notice Deposit ether to get wrapped ether
function deposit() external payable;
/// @notice Withdraw wrapped ether to get ether
function withdraw(uint256) external;
}
contract AUniswapV3 {
using Path for bytes;
address payable immutable private UNISWAP_V3_SWAP_ROUTER_ADDRESS = payable(address(0xE592427A0AEce92De3Edee1F18E0157C05861564));
bytes4 immutable private APPROVE_SELECTOR = bytes4(keccak256(bytes("approve(address,uint256)")));
bytes4 immutable private EXACT_INPUT_SELECTOR = bytes4(keccak256("exactInput(ISwapRouter.ExactInputParams)"));
bytes4 immutable private EXACT_INPUT_SINGLE_SELECTOR = bytes4(keccak256("exactInputSingle(ISwapRouter.ExactInputSingleParams)"));
bytes4 immutable private EXACT_OUTPUT_SELECTOR = bytes4(keccak256("exactOutput(ISwapRouter.exactOutputParams)"));
bytes4 immutable private EXACT_OUTPUT_SINGLE_SELECTOR = bytes4(keccak256("exactOutputSingle(ISwapRouter.ExactOutputSingleParams)"));
bytes4 immutable private REFUND_ETH_SELECTOR = bytes4(keccak256("refundETH()"));
bytes4 immutable private SWEEP_TOKEN_SELECTOR = bytes4(keccak256("sweepToken(address,uint256,address)"));
bytes4 immutable private SWEEP_TOKEN_WITH_FEE_SELECTOR = bytes4(keccak256("sweepTokenWithFee(address,uint256,address,uint256,address)"));
bytes4 immutable private UNWRAP_WETH9_SELECTOR = bytes4(keccak256("unwrapWETH9(uint256,address)"));
bytes4 immutable private UNWRAP_WETH9_WITH_FEE_SELECTOR = bytes4(keccak256("unwrapWETH9WithFee(uint256,address,uint256,address)"));
bytes4 immutable private WRAP_ETH_SELECTOR = bytes4(keccak256("wrapETH(uint256)"));
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
/// @dev The `msg.value` should not be trusted for any method callable from multicall.
/// @param data The encoded function data for each of the calls to make to this contract
function multicall(bytes[] calldata data) external payable {
for (uint256 i = 0; i < data.length; i++) {
bytes memory messagePack = data[i];
bytes4 selector;
assembly {
selector := mload(add(messagePack, 32))
}
if (selector == EXACT_INPUT_SINGLE_SELECTOR) {
exactInputSingleInternal(abi.decode(data[i], (ISwapRouter.ExactInputSingleParams)));
} else if (selector == EXACT_INPUT_SELECTOR) {
exactInputInternal(abi.decode(data[i], (ISwapRouter.ExactInputParams)));
} else if (selector == EXACT_OUTPUT_SINGLE_SELECTOR) {
exactOutputSingleInternal(abi.decode(data[i], (ISwapRouter.ExactOutputSingleParams)));
} else if (selector == EXACT_OUTPUT_SELECTOR) {
exactOutputInternal(abi.decode(data[i], (ISwapRouter.ExactOutputParams)));
} else if (selector == WRAP_ETH_SELECTOR) {
wrapETHInternal(abi.decode(data[i], (uint256)));
} else if (selector == UNWRAP_WETH9_SELECTOR) {
(uint256 amountMinimum, address recipient) = abi.decode(data[i], (uint256, address));
unwrapWETH9Internal(amountMinimum, recipient);
} else if (selector == REFUND_ETH_SELECTOR) {
refundETHInternal();
} else if (selector == SWEEP_TOKEN_SELECTOR) {
(address token, uint256 amountMinimum, address recipient) = abi.decode(
data[i],
(address, uint256, address)
);
sweepTokenInternal(token, amountMinimum, recipient);
} else if (selector == UNWRAP_WETH9_WITH_FEE_SELECTOR) {
(uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient) = abi.decode(
data[i],
(uint256, address, uint256, address)
);
unwrapWETH9WithFeeInternal(amountMinimum, recipient, feeBips, feeRecipient);
} else if (selector == SWEEP_TOKEN_WITH_FEE_SELECTOR) {
(
address token,
uint256 amountMinimum,
address recipient,
uint256 feeBips,
address feeRecipient
) = abi.decode(
data[i],
(address, uint256, address, uint256, address)
);
sweepTokenWithFeeInternal(token, amountMinimum, recipient, feeBips, feeRecipient);
} else revert("UNKNOWN_SELECTOR");
}
}
/// @notice Wraps ETH when value input is non-null
/// @param value The ETH amount to be wrapped
function wrapETH(uint256 value) external payable {
wrapETHInternal(value);
}
function wrapETHInternal(uint256 value) internal {
if (value > uint256(0)) {
IWETH9(
IPeripheryImmutableState(UNISWAP_V3_SWAP_ROUTER_ADDRESS).WETH9()
).deposit{value: value}();
}
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in memory
/// @return amountOut The amount of the received token
function exactInputSingle(ISwapRouter.ExactInputSingleParams calldata params)
external
payable
returns (uint256 amountOut)
{
amountOut = exactInputSingleInternal(params);
}
function exactInputSingleInternal(ISwapRouter.ExactInputSingleParams memory params)
internal
returns (uint256 amountOut)
{
// we first set the allowance to the uniswap router
if (Token(params.tokenIn).allowance(address(this), UNISWAP_V3_SWAP_ROUTER_ADDRESS) < params.amountIn) {
safeApproveInternal(params.tokenIn, UNISWAP_V3_SWAP_ROUTER_ADDRESS, type(uint).max);
}
// finally, we swap the tokens
amountOut = ISwapRouter(UNISWAP_V3_SWAP_ROUTER_ADDRESS).exactInputSingle(
ISwapRouter.ExactInputSingleParams({
tokenIn: params.tokenIn,
tokenOut: params.tokenOut,
fee: params.fee,
recipient: address(this), // this drago is always the recipient
deadline: params.deadline,
amountIn: params.amountIn,
amountOutMinimum: params.amountOutMinimum,
sqrtPriceLimitX96: params.sqrtPriceLimitX96
})
);
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in memory
/// @return amountOut The amount of the received token
function exactInput(ISwapRouter.ExactInputParams calldata params)
external
payable
returns (uint256 amountOut)
{
amountOut = exactInputInternal(params);
}
function exactInputInternal(ISwapRouter.ExactInputParams memory params)
internal
returns (uint256 amountOut)
{
(address tokenIn, , ) = params.path.decodeFirstPool();
// we first set the allowance to the uniswap router
if (Token(tokenIn).allowance(address(this), UNISWAP_V3_SWAP_ROUTER_ADDRESS) < params.amountIn) {
safeApproveInternal(tokenIn, UNISWAP_V3_SWAP_ROUTER_ADDRESS, type(uint).max);
}
// finally, we swap the tokens
amountOut = ISwapRouter(UNISWAP_V3_SWAP_ROUTER_ADDRESS).exactInput(
ISwapRouter.ExactInputParams({
path: params.path,
recipient: address(this), // this drago is always the recipient
deadline: params.deadline,
amountIn: params.amountIn,
amountOutMinimum: params.amountOutMinimum
})
);
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in memory
/// @return amountIn The amount of the input token
function exactOutputSingle(ISwapRouter.ExactOutputSingleParams calldata params)
external
payable
returns (uint256 amountIn)
{
amountIn = exactOutputSingleInternal(params);
}
function exactOutputSingleInternal(ISwapRouter.ExactOutputSingleParams memory params)
internal
returns (uint256 amountIn)
{
// we first set the allowance to the uniswap router
if (Token(params.tokenIn).allowance(address(this), UNISWAP_V3_SWAP_ROUTER_ADDRESS) < params.amountInMaximum) {
safeApproveInternal(params.tokenIn, UNISWAP_V3_SWAP_ROUTER_ADDRESS, type(uint).max);
}
// finally, we swap the tokens
amountIn = ISwapRouter(UNISWAP_V3_SWAP_ROUTER_ADDRESS).exactOutputSingle(
ISwapRouter.ExactOutputSingleParams({
tokenIn: params.tokenIn,
tokenOut: params.tokenOut,
fee: params.fee,
recipient: address(this), // this drago is always the recipient
deadline: params.deadline,
amountOut: params.amountOut,
amountInMaximum: params.amountInMaximum,
sqrtPriceLimitX96: params.sqrtPriceLimitX96
})
);
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in memory
/// @return amountIn The amount of the input token
function exactOutput(ISwapRouter.ExactOutputParams calldata params)
external
payable
returns (uint256 amountIn)
{
amountIn = exactOutputInternal(params);
}
function exactOutputInternal(ISwapRouter.ExactOutputParams memory params)
internal
returns (uint256 amountIn)
{
(address tokenIn, , ) = params.path.decodeFirstPool();
// we first set the allowance to the uniswap router
if (Token(tokenIn).allowance(address(this), UNISWAP_V3_SWAP_ROUTER_ADDRESS) < params.amountInMaximum) {
safeApproveInternal(tokenIn, UNISWAP_V3_SWAP_ROUTER_ADDRESS, type(uint).max);
}
// finally, we swap the tokens
amountIn = ISwapRouter(UNISWAP_V3_SWAP_ROUTER_ADDRESS).exactOutput(
ISwapRouter.ExactOutputParams({
path: params.path,
recipient: address(this), // this drago is always the recipient
deadline: params.deadline,
amountOut: params.amountOut,
amountInMaximum: params.amountInMaximum
})
);
}
/// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
/// @param amountMinimum The minimum amount of WETH9 to unwrap
/// @param recipient The address receiving ETH
function unwrapWETH9(uint256 amountMinimum, address recipient)
external
payable
{
unwrapWETH9Internal(amountMinimum, recipient);
}
function unwrapWETH9Internal(uint256 amountMinimum, address recipient)
internal
{
IPeripheryPaymentsWithFee(UNISWAP_V3_SWAP_ROUTER_ADDRESS).unwrapWETH9(
amountMinimum,
recipient != address(this) ? address(this) : address(this) // this drago is always the recipient
);
}
/// @notice Refunds any ETH balance held by this contract to the `msg.sender`
/// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
/// that use ether for the input amount
function refundETH()
external
payable
{
refundETHInternal();
}
function refundETHInternal()
internal
{
IPeripheryPaymentsWithFee(UNISWAP_V3_SWAP_ROUTER_ADDRESS).refundETH();
}
/// @notice Transfers the full amount of a token held by this contract to recipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
/// @param token The contract address of the token which will be transferred to `recipient`
/// @param amountMinimum The minimum amount of token required for a transfer
/// @param recipient The destination address of the token
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
)
external
payable
{
sweepTokenInternal(token, amountMinimum, recipient);
}
function sweepTokenInternal(
address token,
uint256 amountMinimum,
address recipient
)
internal
{
IPeripheryPaymentsWithFee(UNISWAP_V3_SWAP_ROUTER_ADDRESS).sweepToken(
token,
amountMinimum,
recipient != address(this) ? address(this) : address(this) // this drago is always the recipient
);
}
/// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH, with a percentage between
/// 0 (exclusive), and 1 (inclusive) going to feeRecipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
function unwrapWETH9WithFee(
uint256 amountMinimum,
address recipient,
uint256 feeBips,
address feeRecipient
)
external
payable
{
unwrapWETH9WithFeeInternal(amountMinimum, recipient, feeBips, feeRecipient);
}
function unwrapWETH9WithFeeInternal(
uint256 amountMinimum,
address recipient,
uint256 feeBips,
address feeRecipient
)
internal
{
IPeripheryPaymentsWithFee(UNISWAP_V3_SWAP_ROUTER_ADDRESS).unwrapWETH9WithFee(
amountMinimum,
recipient != address(this) ? address(this) : address(this), // this drago is always the recipient
feeBips,
feeRecipient
);
}
/// @notice Transfers the full amount of a token held by this contract to recipient, with a percentage between
/// 0 (exclusive) and 1 (inclusive) going to feeRecipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
function sweepTokenWithFee(
address token,
uint256 amountMinimum,
address recipient,
uint256 feeBips,
address feeRecipient
)
external
payable
{
sweepTokenWithFeeInternal(token, amountMinimum, recipient, feeBips, feeRecipient);
}
function sweepTokenWithFeeInternal(
address token,
uint256 amountMinimum,
address recipient,
uint256 feeBips,
address feeRecipient
)
internal
{
IPeripheryPaymentsWithFee(UNISWAP_V3_SWAP_ROUTER_ADDRESS).sweepTokenWithFee(
token,
amountMinimum,
recipient != address(this) ? address(this) : address(this), // this drago is always the recipient
feeBips,
feeRecipient
);
}
function safeApproveInternal(
address token,
address spender,
uint256 value
)
internal
{
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(APPROVE_SELECTOR, spender, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"RIGOBLOCK_APPROVE_FAILED"
);
}
}
| @notice Swaps `amountIn` of one token for as much as possible of another along the specified path @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in memory @return amountOut The amount of the received token | function exactInput(ISwapRouter.ExactInputParams calldata params)
external
payable
returns (uint256 amountOut)
{
amountOut = exactInputInternal(params);
}
| 881,426 | [
1,
6050,
6679,
1375,
8949,
382,
68,
434,
1245,
1147,
364,
487,
9816,
487,
3323,
434,
4042,
7563,
326,
1269,
589,
225,
859,
1021,
1472,
4573,
364,
326,
3309,
17,
18444,
7720,
16,
3749,
487,
1375,
14332,
1210,
1370,
68,
316,
3778,
327,
3844,
1182,
1021,
3844,
434,
326,
5079,
1147,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
5565,
1210,
12,
5127,
91,
438,
8259,
18,
14332,
1210,
1370,
745,
892,
859,
13,
203,
3639,
3903,
203,
3639,
8843,
429,
203,
3639,
1135,
261,
11890,
5034,
3844,
1182,
13,
203,
565,
288,
203,
3639,
3844,
1182,
273,
5565,
1210,
3061,
12,
2010,
1769,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import "./lib/FixedPoint.sol";
contract BnbConjure is IERC20, ReentrancyGuard {
/// @notice using Openzeppelin contracts for SafeMath and Address
using SafeMath for uint256;
using Address for address;
using FixedPoint for FixedPoint.uq112x112;
using FixedPoint for FixedPoint.uq144x112;
/// @notice presenting the total supply
uint256 private _totalSupply;
/// @notice representing the name of the token
string private _name;
/// @notice representing the symbol of the token
string private _symbol;
/// @notice representing the decimals of the token
uint8 private immutable _decimals = 18;
/// @notice a record of balance of a specific account by address
mapping(address => uint256) private _balances;
/// @notice a record of allowances for a specific address by address to address mapping
mapping(address => mapping(address => uint256)) private _allowances;
/// @notice the owner and creator of the contract
address payable public _owner;
/// @notice the owner of the CONJURE factory
address payable public _factoryowner;
/// @notice the type of the arb asset (single asset, arb asset) (0... single, 1... arb)
uint8 public _assetType;
/// @notice the address of the collateral contract factory
address public _collateralFactory;
/// @notice the address of the collateral contract
address public _collateralContract;
/// @notice shows the init state of the contract
bool public _inited;
/// @notice struct for oracles
struct _oracleStruct {
address oracleaddress;
/// 0... chainlink 2... custom
uint oracleType;
string signature;
bytes calldatas;
uint256 weight;
uint256 decimals;
uint256 values;
}
/// @notice array for oracles
_oracleStruct[] public _oracleData;
/// @notice number of aracles
uint256 public _numoracles;
/// @notice the latest observed price
uint256 public _latestobservedprice;
/// @notice the latest observed price timestamp
uint256 public _latestobservedtime;
/// @notice maximum decimal size for the used prices
uint256 public _maximumDecimals = 18;
/* The number representing 1.0. */
uint public UNIT = 10**uint(_maximumDecimals);
constructor (
string memory name_,
string memory symbol_,
address payable owner_,
address payable factoryowner_,
address collateralfactory_
)
public {
_owner = owner_;
_factoryowner = factoryowner_;
_totalSupply = 0;
_name = name_;
_symbol = symbol_;
_collateralFactory = collateralfactory_;
_balances[_owner] = _totalSupply;
_inited = false;
emit Transfer(address(0), _owner, _totalSupply);
}
/**
* @dev Public init function to set up the contract with pricing sources
*
*/
function init(
uint256 mintingFee_,
uint8 assetType_,
address[] memory oracleAddresses_,
uint8[] memory oracleTypes_,
string[] memory signatures_,
bytes[] memory calldata_,
uint256[] memory values_,
uint256[] memory weights_,
uint256[] memory decimals_
) public
{
require(msg.sender == _owner);
require(_inited == false);
_collateralContract = IBnbCollateralFactory(_collateralFactory).BnbCollateralMint(payable(address(this)), _owner, _factoryowner, mintingFee_);
_assetType = assetType_;
_numoracles = oracleAddresses_.length;
// push the values into the oracle struct for further processing
for (uint i = 0; i < oracleAddresses_.length; i++) {
_oracleStruct memory temp_struct;
temp_struct.oracleaddress = oracleAddresses_[i];
temp_struct.oracleType = oracleTypes_[i];
temp_struct.signature = signatures_[i];
temp_struct.calldatas = calldata_[i];
temp_struct.weight = weights_[i];
temp_struct.values = values_[i];
temp_struct.decimals = decimals_[i];
_oracleData.push(temp_struct);
require(decimals_[i] <= 18);
}
getPrice();
_inited = true;
}
/**
* @dev Public burn function can only be called from the collateral contract
*
*/
function burn(address account, uint amount) public
{
require(msg.sender == _collateralContract);
_internalBurn(account, amount);
}
/**
* @dev Public mint function can only be called from the collateral contract
*
*/
function mint(address account, uint amount) public
{
require(msg.sender == _collateralContract);
_internalIssue(account, amount);
}
/**
* @dev internal mint function issues tokens to the given account
*
*/
function _internalIssue(address account, uint amount) internal {
_balances[account] = _balances[account].add(amount);
_totalSupply = _totalSupply.add(amount);
emit Transfer(address(0), account, amount);
emit Issued(account, amount);
}
/**
* @dev internal burn function burns tokens from the given account
*
*/
function _internalBurn(address account, uint amount) internal {
_balances[account] = _balances[account].sub(amount);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
emit Burned(account, amount);
}
/**
* @dev lets the owner change the owner
*/
function changeOwner(address payable _newOwner) public {
require(msg.sender == _owner);
address oldOwner = _owner;
_owner = _newOwner;
emit NewOwner(oldOwner, _owner);
}
/**
* @dev Lets the Factory Owner change the current owner
*/
function newFactoryOwner(address payable _newOwner) public {
require(msg.sender == _factoryowner);
_factoryowner = _newOwner;
}
/**
* @dev lets the owner collect the collected fees
*/
function collectFees() public {
require(msg.sender == _owner);
uint256 contractBalalance = address(this).balance;
_owner.transfer(contractBalalance);
}
/**
* Returns the latest price of an oracle asset
*/
function getLatestPrice(AggregatorV3Interface priceFeed) internal view returns (int) {
(
uint80 roundID,
int price,
uint startedAt,
uint timeStamp,
uint80 answeredInRound
) = priceFeed.latestRoundData();
return price;
}
/**
* Gets the BNB USD price from band oracle
*/
function getLatestBNBUSDPrice() public view returns (int) {
address contractaddress = 0xDA7a001b254CD22e46d3eAB04d937489c93174C3;
IBandOracle oracle = IBandOracle(contractaddress);
IBandOracle.ReferenceData memory ref = oracle.getReferenceData("BNB", "USD");
return int(ref.rate);
}
/**
* quicksort implementation
*/
function quickSort(uint[] memory arr, int left, int right) public pure {
int i = left;
int j = right;
if (i == j) return;
uint pivot = arr[uint(left + (right - left) / 2)];
while (i <= j) {
while (arr[uint(i)] < pivot) i++;
while (pivot < arr[uint(j)]) j--;
if (i <= j) {
(arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]);
i++;
j--;
}
}
if (left < j)
quickSort(arr, left, j);
if (i < right)
quickSort(arr, i, right);
}
/**
* Avg implementation
*/
function getAverage(uint[] memory arr) internal view returns (uint) {
uint sum = 0;
for (uint i = 0; i < arr.length; i++) {
sum += arr[i];
}
// if we dont have any weights
if (_assetType == 0)
{
return (sum / arr.length);
}
// divide by total weight
return (sum / 100);
}
/**
* Sort Function
*/
function sort(uint[] memory data) public pure returns (uint[] memory) {
quickSort(data, int(0), int(data.length - 1));
return data;
}
// sqrt function
function sqrt(uint256 y) internal view returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = (y + 1) / 2;
while (x < z) {
z = x;
x = (y.mul(UNIT).div(x) + x) / 2;
}
} else if (y != 0) {
z = 1;
}
// else z = 0
}
function getLatestPrice() public view returns (uint) {
return _latestobservedprice;
}
/**
* Returns the price for the arb asset (median price of the 5 assets)
*/
function getPrice() public returns (uint) {
// storing all in an array for further processing
uint[] memory prices = new uint[](_oracleData.length);
for (uint i = 0; i < _oracleData.length; i++) {
// chainlink oracle
if (_oracleData[i].oracleType == 0)
{
AggregatorV3Interface pricefeed = AggregatorV3Interface(_oracleData[i].oracleaddress);
uint price = uint(getLatestPrice(pricefeed));
prices[i] = price;
// norming price
if (_maximumDecimals != _oracleData[i].decimals)
{
prices[i] = prices[i] * 10 ** (_maximumDecimals - _oracleData[i].decimals);
}
if (_assetType == 1)
{
prices[i] = prices[i] * _oracleData[i].weight;
}
}
// custom oracle
if (_oracleData[i].oracleType == 2)
{
address contractaddress = _oracleData[i].oracleaddress;
string memory signature = _oracleData[i].signature;
bytes memory calldatas = _oracleData[i].calldatas;
uint256 callvalue = _oracleData[i].values;
bytes memory callData;
if (bytes(signature).length == 0) {
callData = calldatas;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), calldatas);
}
(bool success, bytes memory data) = contractaddress.call{value:callvalue}(callData);
require(success);
uint price = abi.decode(data, (uint));
prices[i] = price;
// norming price
if (_maximumDecimals != _oracleData[i].decimals)
{
prices[i] = prices[i] * 10 ** (_maximumDecimals - _oracleData[i].decimals);
}
if (_assetType == 1)
{
prices[i] = prices[i] * _oracleData[i].weight;
}
}
}
uint[] memory sorted = sort(prices);
/// for single assets return median
if (_assetType == 0)
{
uint modulo = sorted.length % 2;
// uneven so we can take the middle
if (modulo == 1)
{
uint sizer = (sorted.length + 1) / 2;
_latestobservedprice = sorted[sizer-1];
_latestobservedtime = block.timestamp;
return sorted[sizer-1];
}
// take average of the 2 most inner numbers
else
{
uint size1 = (sorted.length) / 2;
uint size2 = size1 + 1;
uint arrsize1 = sorted[size1-1];
uint arrsize2 = sorted[size2-1];
uint[] memory sortedmin = new uint[](2);
sortedmin[0] = arrsize1;
sortedmin[1] = arrsize2;
_latestobservedprice = getAverage(sortedmin);
_latestobservedtime = block.timestamp;
return getAverage(sortedmin);
}
}
/// else return avarage for arb assets
_latestobservedprice = getAverage(sorted);
_latestobservedtime = block.timestamp;
return getAverage(sorted);
}
///
/// ERC20 specific functions
///
/**
* fallback function for collection funds
*/
fallback() external payable {
}
receive() external payable {
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}. Uses burn abstraction for balance updates without gas and universally.
*/
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address dst, uint256 rawAmount) external override returns (bool) {
uint256 amount = rawAmount;
_transfer(msg.sender, dst, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
override
view
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(msg.sender, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero ress.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address src, address dst, uint256 rawAmount) external override returns (bool) {
address spender = msg.sender;
uint256 spenderAllowance = _allowances[src][spender];
uint256 amount = rawAmount;
if (spender != src && spenderAllowance != uint256(-1)) {
uint256 newAllowance = spenderAllowance.sub(amount, "CONJURE::transferFrom: transfer amount exceeds spender allowance");
_allowances[src][spender] = newAllowance;
}
_transfer(src, dst, amount);
return true;
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(
amount,
"BRC20: transfer amount exceeds balance"
);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
// ========== EVENTS ==========
event NewOwner(address oldOwner, address newOwner);
event FeeChanged(uint8 oldFee, uint8 newFee);
event Issued(address indexed account, uint value);
event Burned(address indexed account, uint value);
}
contract BnbConjureFactory {
event NewConjureContract(address deployed);
event FactoryOwnerChanged(address newowner);
address payable public factoryOwner;
constructor() public {
factoryOwner = msg.sender;
}
/**
* @dev lets anyone mint a new CONJURE contract
*/
function ConjureMint(
string memory name_,
string memory symbol_,
address payable owner_,
address collateralfactory_
) public returns(address) {
BnbConjure newContract = new BnbConjure(
name_,
symbol_,
owner_,
factoryOwner,
collateralfactory_
);
emit NewConjureContract(address(newContract));
return address(newContract);
}
/**
* @dev Lets the Factory Owner change the current owner
*/
function newFactoryOwner(address payable newOwner) public {
require(msg.sender == factoryOwner);
factoryOwner = newOwner;
emit FactoryOwnerChanged(factoryOwner);
}
}
interface IBnbCollateralFactory {
function BnbCollateralMint(address payable asset_, address owner_, address payable factoryowner_, uint256 mintingfeerate_) external returns (address);
}
interface IBandOracle {
struct ReferenceData {
uint256 rate; // base/quote exchange rate, multiplied by 1e18.
uint256 lastUpdatedBase; // UNIX epoch of the last time when base price gets updated.
uint256 lastUpdatedQuote; // UNIX epoch of the last time when quote price gets updated.
}
/// Returns the price data for the given base/quote pair. Revert if not available.
function getReferenceData(string calldata _base, string calldata _quote)
external
view
returns (ReferenceData memory);
}
| * Returns the latest price of an oracle asset/ | function getLatestPrice(AggregatorV3Interface priceFeed) internal view returns (int) {
(
uint80 roundID,
int price,
uint startedAt,
uint timeStamp,
uint80 answeredInRound
) = priceFeed.latestRoundData();
return price;
}
| 15,795,036 | [
1,
1356,
326,
4891,
6205,
434,
392,
20865,
3310,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
336,
18650,
5147,
12,
17711,
58,
23,
1358,
6205,
8141,
13,
2713,
1476,
1135,
261,
474,
13,
288,
203,
3639,
261,
203,
3639,
2254,
3672,
3643,
734,
16,
203,
3639,
509,
6205,
16,
203,
3639,
2254,
5746,
861,
16,
203,
3639,
2254,
18198,
16,
203,
3639,
2254,
3672,
5803,
329,
382,
11066,
203,
3639,
262,
273,
6205,
8141,
18,
13550,
11066,
751,
5621,
203,
3639,
327,
6205,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.16;
// Inheritance
import "./Owned.sol";
import "./MixinResolver.sol";
import "./MixinSystemSettings.sol";
import "./interfaces/IIssuer.sol";
// Libraries
import "./SafeDecimalMath.sol";
// Internal references
import "./interfaces/IPynth.sol";
import "./interfaces/IPeriFin.sol";
import "./interfaces/IFeePool.sol";
import "./interfaces/IPeriFinState.sol";
import "./interfaces/IExchanger.sol";
import "./interfaces/IDelegateApprovals.sol";
import "./interfaces/IExchangeRates.sol";
import "./interfaces/IEtherCollateral.sol";
import "./interfaces/IEtherCollateralpUSD.sol";
import "./interfaces/IHasBalance.sol";
import "./interfaces/IERC20.sol";
import "./interfaces/ILiquidations.sol";
import "./interfaces/ICollateralManager.sol";
import "./interfaces/IDebtCache.sol";
interface IRewardEscrowV2 {
// Views
function balanceOf(address account) external view returns (uint);
}
interface IIssuerInternalDebtCache {
function updateCachedPynthDebtWithRate(bytes32 currencyKey, uint currencyRate) external;
function updateCachedPynthDebtsWithRates(bytes32[] calldata currencyKeys, uint[] calldata currencyRates) external;
function updateDebtCacheValidity(bool currentlyInvalid) external;
function cacheInfo()
external
view
returns (
uint cachedDebt,
uint timestamp,
bool isInvalid,
bool isStale
);
}
// /contracts/source/contracts/issuer
contract Issuer is Owned, MixinSystemSettings, IIssuer {
using SafeMath for uint;
using SafeDecimalMath for uint;
// Available Pynths which can be used with the system
IPynth[] public availablePynths;
mapping(bytes32 => IPynth) public pynths;
mapping(address => bytes32) public pynthsByAddress;
/* ========== ENCODED NAMES ========== */
bytes32 internal constant pUSD = "pUSD";
bytes32 internal constant pETH = "pETH";
bytes32 internal constant PERI = "PERI";
// Flexible storage names
bytes32 public constant CONTRACT_NAME = "Issuer";
bytes32 internal constant LAST_ISSUE_EVENT = "lastIssueEvent";
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_PYNTHETIX = "PeriFin";
bytes32 private constant CONTRACT_EXCHANGER = "Exchanger";
bytes32 private constant CONTRACT_EXRATES = "ExchangeRates";
bytes32 private constant CONTRACT_PYNTHETIXSTATE = "PeriFinState";
bytes32 private constant CONTRACT_FEEPOOL = "FeePool";
bytes32 private constant CONTRACT_DELEGATEAPPROVALS = "DelegateApprovals";
bytes32 private constant CONTRACT_ETHERCOLLATERAL = "EtherCollateral";
bytes32 private constant CONTRACT_ETHERCOLLATERAL_SUSD = "EtherCollateralpUSD";
bytes32 private constant CONTRACT_COLLATERALMANAGER = "CollateralManager";
bytes32 private constant CONTRACT_REWARDESCROW_V2 = "RewardEscrowV2";
bytes32 private constant CONTRACT_PYNTHETIXESCROW = "PeriFinEscrow";
bytes32 private constant CONTRACT_LIQUIDATIONS = "Liquidations";
bytes32 private constant CONTRACT_DEBTCACHE = "DebtCache";
constructor(address _owner, address _resolver) public Owned(_owner) MixinSystemSettings(_resolver) {}
/* ========== VIEWS ========== */
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](13);
newAddresses[0] = CONTRACT_PYNTHETIX;
newAddresses[1] = CONTRACT_EXCHANGER;
newAddresses[2] = CONTRACT_EXRATES;
newAddresses[3] = CONTRACT_PYNTHETIXSTATE;
newAddresses[4] = CONTRACT_FEEPOOL;
newAddresses[5] = CONTRACT_DELEGATEAPPROVALS;
newAddresses[6] = CONTRACT_ETHERCOLLATERAL;
newAddresses[7] = CONTRACT_ETHERCOLLATERAL_SUSD;
newAddresses[8] = CONTRACT_REWARDESCROW_V2;
newAddresses[9] = CONTRACT_PYNTHETIXESCROW;
newAddresses[10] = CONTRACT_LIQUIDATIONS;
newAddresses[11] = CONTRACT_DEBTCACHE;
newAddresses[12] = CONTRACT_COLLATERALMANAGER;
return combineArrays(existingAddresses, newAddresses);
}
function perifin() internal view returns (IPeriFin) {
return IPeriFin(requireAndGetAddress(CONTRACT_PYNTHETIX));
}
function exchanger() internal view returns (IExchanger) {
return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER));
}
function exchangeRates() internal view returns (IExchangeRates) {
return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES));
}
function perifinState() internal view returns (IPeriFinState) {
return IPeriFinState(requireAndGetAddress(CONTRACT_PYNTHETIXSTATE));
}
function feePool() internal view returns (IFeePool) {
return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL));
}
function liquidations() internal view returns (ILiquidations) {
return ILiquidations(requireAndGetAddress(CONTRACT_LIQUIDATIONS));
}
function delegateApprovals() internal view returns (IDelegateApprovals) {
return IDelegateApprovals(requireAndGetAddress(CONTRACT_DELEGATEAPPROVALS));
}
function etherCollateral() internal view returns (IEtherCollateral) {
return IEtherCollateral(requireAndGetAddress(CONTRACT_ETHERCOLLATERAL));
}
function etherCollateralpUSD() internal view returns (IEtherCollateralpUSD) {
return IEtherCollateralpUSD(requireAndGetAddress(CONTRACT_ETHERCOLLATERAL_SUSD));
}
function collateralManager() internal view returns (ICollateralManager) {
return ICollateralManager(requireAndGetAddress(CONTRACT_COLLATERALMANAGER));
}
function rewardEscrowV2() internal view returns (IRewardEscrowV2) {
return IRewardEscrowV2(requireAndGetAddress(CONTRACT_REWARDESCROW_V2));
}
function perifinEscrow() internal view returns (IHasBalance) {
return IHasBalance(requireAndGetAddress(CONTRACT_PYNTHETIXESCROW));
}
function debtCache() internal view returns (IIssuerInternalDebtCache) {
return IIssuerInternalDebtCache(requireAndGetAddress(CONTRACT_DEBTCACHE));
}
function issuanceRatio() external view returns (uint) {
return getIssuanceRatio();
}
function _availableCurrencyKeysWithOptionalPERI(bool withPERI) internal view returns (bytes32[] memory) {
bytes32[] memory currencyKeys = new bytes32[](availablePynths.length + (withPERI ? 1 : 0));
for (uint i = 0; i < availablePynths.length; i++) {
currencyKeys[i] = pynthsByAddress[address(availablePynths[i])];
}
if (withPERI) {
currencyKeys[availablePynths.length] = PERI;
}
return currencyKeys;
}
function _totalIssuedPynths(bytes32 currencyKey, bool excludeCollateral)
internal
view
returns (uint totalIssued, bool anyRateIsInvalid)
{
(uint debt, , bool cacheIsInvalid, bool cacheIsStale) = debtCache().cacheInfo();
anyRateIsInvalid = cacheIsInvalid || cacheIsStale;
IExchangeRates exRates = exchangeRates();
// Add total issued pynths from non snx collateral back into the total if not excluded
if (!excludeCollateral) {
// Get the pUSD equivalent amount of all the MC issued pynths.
(uint nonSnxDebt, bool invalid) = collateralManager().totalLong();
debt = debt.add(nonSnxDebt);
anyRateIsInvalid = anyRateIsInvalid || invalid;
// Now add the ether collateral stuff as we are still supporting it.
debt = debt.add(etherCollateralpUSD().totalIssuedPynths());
// Add ether collateral pETH
(uint ethRate, bool ethRateInvalid) = exRates.rateAndInvalid(pETH);
uint ethIssuedDebt = etherCollateral().totalIssuedPynths().multiplyDecimalRound(ethRate);
debt = debt.add(ethIssuedDebt);
anyRateIsInvalid = anyRateIsInvalid || ethRateInvalid;
}
if (currencyKey == pUSD) {
return (debt, anyRateIsInvalid);
}
(uint currencyRate, bool currencyRateInvalid) = exRates.rateAndInvalid(currencyKey);
return (debt.divideDecimalRound(currencyRate), anyRateIsInvalid || currencyRateInvalid);
}
function _debtBalanceOfAndTotalDebt(address _issuer, bytes32 currencyKey)
internal
view
returns (
uint debtBalance,
uint totalSystemValue,
bool anyRateIsInvalid
)
{
IPeriFinState state = perifinState();
// What was their initial debt ownership?
(uint initialDebtOwnership, uint debtEntryIndex) = state.issuanceData(_issuer);
// What's the total value of the system excluding ETH backed pynths in their requested currency?
(totalSystemValue, anyRateIsInvalid) = _totalIssuedPynths(currencyKey, true);
// If it's zero, they haven't issued, and they have no debt.
// Note: it's more gas intensive to put this check here rather than before _totalIssuedPynths
// if they have 0 PERI, but it's a necessary trade-off
if (initialDebtOwnership == 0) return (0, totalSystemValue, anyRateIsInvalid);
// Figure out the global debt percentage delta from when they entered the system.
// This is a high precision integer of 27 (1e27) decimals.
uint currentDebtOwnership = state
.lastDebtLedgerEntry()
.divideDecimalRoundPrecise(state.debtLedger(debtEntryIndex))
.multiplyDecimalRoundPrecise(initialDebtOwnership);
// Their debt balance is their portion of the total system value.
uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal().multiplyDecimalRoundPrecise(
currentDebtOwnership
);
// Convert back into 18 decimals (1e18)
debtBalance = highPrecisionBalance.preciseDecimalToDecimal();
}
function _canBurnPynths(address account) internal view returns (bool) {
return now >= _lastIssueEvent(account).add(getMinimumStakeTime());
}
function _lastIssueEvent(address account) internal view returns (uint) {
// Get the timestamp of the last issue this account made
return flexibleStorage().getUIntValue(CONTRACT_NAME, keccak256(abi.encodePacked(LAST_ISSUE_EVENT, account)));
}
function _remainingIssuablePynths(address _issuer)
internal
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt,
bool anyRateIsInvalid
)
{
(alreadyIssued, totalSystemDebt, anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(_issuer, pUSD);
(uint issuable, bool isInvalid) = _maxIssuablePynths(_issuer);
maxIssuable = issuable;
anyRateIsInvalid = anyRateIsInvalid || isInvalid;
if (alreadyIssued >= maxIssuable) {
maxIssuable = 0;
} else {
maxIssuable = maxIssuable.sub(alreadyIssued);
}
}
function _snxToUSD(uint amount, uint snxRate) internal pure returns (uint) {
return amount.multiplyDecimalRound(snxRate);
}
function _usdToSnx(uint amount, uint snxRate) internal pure returns (uint) {
return amount.divideDecimalRound(snxRate);
}
function _maxIssuablePynths(address _issuer) internal view returns (uint, bool) {
// What is the value of their PERI balance in pUSD
(uint snxRate, bool isInvalid) = exchangeRates().rateAndInvalid(PERI);
uint destinationValue = _snxToUSD(_collateral(_issuer), snxRate);
// They're allowed to issue up to issuanceRatio of that value
return (destinationValue.multiplyDecimal(getIssuanceRatio()), isInvalid);
}
function _collateralisationRatio(address _issuer) internal view returns (uint, bool) {
uint totalOwnedPeriFin = _collateral(_issuer);
(uint debtBalance, , bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(_issuer, PERI);
// it's more gas intensive to put this check here if they have 0 PERI, but it complies with the interface
if (totalOwnedPeriFin == 0) return (0, anyRateIsInvalid);
return (debtBalance.divideDecimalRound(totalOwnedPeriFin), anyRateIsInvalid);
}
function _collateral(address account) internal view returns (uint) {
uint balance = IERC20(address(perifin())).balanceOf(account);
if (address(perifinEscrow()) != address(0)) {
balance = balance.add(perifinEscrow().balanceOf(account));
}
if (address(rewardEscrowV2()) != address(0)) {
balance = balance.add(rewardEscrowV2().balanceOf(account));
}
return balance;
}
function minimumStakeTime() external view returns (uint) {
return getMinimumStakeTime();
}
function canBurnPynths(address account) external view returns (bool) {
return _canBurnPynths(account);
}
function availableCurrencyKeys() external view returns (bytes32[] memory) {
return _availableCurrencyKeysWithOptionalPERI(false);
}
function availablePynthCount() external view returns (uint) {
return availablePynths.length;
}
function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid) {
(, anyRateInvalid) = exchangeRates().ratesAndInvalidForCurrencies(_availableCurrencyKeysWithOptionalPERI(true));
}
function totalIssuedPynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint totalIssued) {
(totalIssued, ) = _totalIssuedPynths(currencyKey, excludeEtherCollateral);
}
function lastIssueEvent(address account) external view returns (uint) {
return _lastIssueEvent(account);
}
function collateralisationRatio(address _issuer) external view returns (uint cratio) {
(cratio, ) = _collateralisationRatio(_issuer);
}
function collateralisationRatioAndAnyRatesInvalid(address _issuer)
external
view
returns (uint cratio, bool anyRateIsInvalid)
{
return _collateralisationRatio(_issuer);
}
function collateral(address account) external view returns (uint) {
return _collateral(account);
}
function debtBalanceOf(address _issuer, bytes32 currencyKey) external view returns (uint debtBalance) {
IPeriFinState state = perifinState();
// What was their initial debt ownership?
(uint initialDebtOwnership, ) = state.issuanceData(_issuer);
// If it's zero, they haven't issued, and they have no debt.
if (initialDebtOwnership == 0) return 0;
(debtBalance, , ) = _debtBalanceOfAndTotalDebt(_issuer, currencyKey);
}
function remainingIssuablePynths(address _issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
)
{
(maxIssuable, alreadyIssued, totalSystemDebt, ) = _remainingIssuablePynths(_issuer);
}
function maxIssuablePynths(address _issuer) external view returns (uint) {
(uint maxIssuable, ) = _maxIssuablePynths(_issuer);
return maxIssuable;
}
function transferablePeriFinAndAnyRateIsInvalid(address account, uint balance)
external
view
returns (uint transferable, bool anyRateIsInvalid)
{
// How many PERI do they have, excluding escrow?
// Note: We're excluding escrow here because we're interested in their transferable amount
// and escrowed PERI are not transferable.
// How many of those will be locked by the amount they've issued?
// Assuming issuance ratio is 20%, then issuing 20 PERI of value would require
// 100 PERI to be locked in their wallet to maintain their collateralisation ratio
// The locked perifin value can exceed their balance.
uint debtBalance;
(debtBalance, , anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(account, PERI);
uint lockedPeriFinValue = debtBalance.divideDecimalRound(getIssuanceRatio());
// If we exceed the balance, no PERI are transferable, otherwise the difference is.
if (lockedPeriFinValue >= balance) {
transferable = 0;
} else {
transferable = balance.sub(lockedPeriFinValue);
}
}
function getPynths(bytes32[] calldata currencyKeys) external view returns (IPynth[] memory) {
uint numKeys = currencyKeys.length;
IPynth[] memory addresses = new IPynth[](numKeys);
for (uint i = 0; i < numKeys; i++) {
addresses[i] = pynths[currencyKeys[i]];
}
return addresses;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function _addPynth(IPynth pynth) internal {
bytes32 currencyKey = pynth.currencyKey();
require(pynths[currencyKey] == IPynth(0), "Pynth exists");
require(pynthsByAddress[address(pynth)] == bytes32(0), "Pynth address already exists");
availablePynths.push(pynth);
pynths[currencyKey] = pynth;
pynthsByAddress[address(pynth)] = currencyKey;
emit PynthAdded(currencyKey, address(pynth));
}
function addPynth(IPynth pynth) external onlyOwner {
_addPynth(pynth);
// Invalidate the cache to force a snapshot to be recomputed. If a pynth were to be added
// back to the system and it still somehow had cached debt, this would force the value to be
// updated.
debtCache().updateDebtCacheValidity(true);
}
function addPynths(IPynth[] calldata pynthsToAdd) external onlyOwner {
uint numPynths = pynthsToAdd.length;
for (uint i = 0; i < numPynths; i++) {
_addPynth(pynthsToAdd[i]);
}
// Invalidate the cache to force a snapshot to be recomputed.
debtCache().updateDebtCacheValidity(true);
}
function _removePynth(bytes32 currencyKey) internal {
address pynthToRemove = address(pynths[currencyKey]);
require(pynthToRemove != address(0), "Pynth does not exist");
require(IERC20(pynthToRemove).totalSupply() == 0, "Pynth supply exists");
require(currencyKey != pUSD, "Cannot remove pynth");
// Remove the pynth from the availablePynths array.
for (uint i = 0; i < availablePynths.length; i++) {
if (address(availablePynths[i]) == pynthToRemove) {
delete availablePynths[i];
// Copy the last pynth into the place of the one we just deleted
// If there's only one pynth, this is pynths[0] = pynths[0].
// If we're deleting the last one, it's also a NOOP in the same way.
availablePynths[i] = availablePynths[availablePynths.length - 1];
// Decrease the size of the array by one.
availablePynths.length--;
break;
}
}
// And remove it from the pynths mapping
delete pynthsByAddress[pynthToRemove];
delete pynths[currencyKey];
emit PynthRemoved(currencyKey, pynthToRemove);
}
function removePynth(bytes32 currencyKey) external onlyOwner {
// Remove its contribution from the debt pool snapshot, and
// invalidate the cache to force a new snapshot.
IIssuerInternalDebtCache cache = debtCache();
cache.updateCachedPynthDebtWithRate(currencyKey, 0);
cache.updateDebtCacheValidity(true);
_removePynth(currencyKey);
}
function removePynths(bytes32[] calldata currencyKeys) external onlyOwner {
uint numKeys = currencyKeys.length;
// Remove their contributions from the debt pool snapshot, and
// invalidate the cache to force a new snapshot.
IIssuerInternalDebtCache cache = debtCache();
uint[] memory zeroRates = new uint[](numKeys);
cache.updateCachedPynthDebtsWithRates(currencyKeys, zeroRates);
cache.updateDebtCacheValidity(true);
for (uint i = 0; i < numKeys; i++) {
_removePynth(currencyKeys[i]);
}
}
function issuePynths(address from, uint amount) external onlyPeriFin {
_issuePynths(from, amount, false);
}
function issueMaxPynths(address from) external onlyPeriFin {
_issuePynths(from, 0, true);
}
function issuePynthsOnBehalf(
address issueForAddress,
address from,
uint amount
) external onlyPeriFin {
_requireCanIssueOnBehalf(issueForAddress, from);
_issuePynths(issueForAddress, amount, false);
}
function issueMaxPynthsOnBehalf(address issueForAddress, address from) external onlyPeriFin {
_requireCanIssueOnBehalf(issueForAddress, from);
_issuePynths(issueForAddress, 0, true);
}
function burnPynths(address from, uint amount) external onlyPeriFin {
_voluntaryBurnPynths(from, amount, false);
}
function burnPynthsOnBehalf(
address burnForAddress,
address from,
uint amount
) external onlyPeriFin {
_requireCanBurnOnBehalf(burnForAddress, from);
_voluntaryBurnPynths(burnForAddress, amount, false);
}
function burnPynthsToTarget(address from) external onlyPeriFin {
_voluntaryBurnPynths(from, 0, true);
}
function burnPynthsToTargetOnBehalf(address burnForAddress, address from) external onlyPeriFin {
_requireCanBurnOnBehalf(burnForAddress, from);
_voluntaryBurnPynths(burnForAddress, 0, true);
}
function liquidateDelinquentAccount(
address account,
uint susdAmount,
address liquidator
) external onlyPeriFin returns (uint totalRedeemed, uint amountToLiquidate) {
// Ensure waitingPeriod and pUSD balance is settled as burning impacts the size of debt pool
require(!exchanger().hasWaitingPeriodOrSettlementOwing(liquidator, pUSD), "pUSD needs to be settled");
// Check account is liquidation open
require(liquidations().isOpenForLiquidation(account), "Account not open for liquidation");
// require liquidator has enough pUSD
require(IERC20(address(pynths[pUSD])).balanceOf(liquidator) >= susdAmount, "Not enough pUSD");
uint liquidationPenalty = liquidations().liquidationPenalty();
// What is their debt in pUSD?
(uint debtBalance, uint totalDebtIssued, bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(account, pUSD);
(uint snxRate, bool snxRateInvalid) = exchangeRates().rateAndInvalid(PERI);
_requireRatesNotInvalid(anyRateIsInvalid || snxRateInvalid);
uint collateralForAccount = _collateral(account);
uint amountToFixRatio = liquidations().calculateAmountToFixCollateral(
debtBalance,
_snxToUSD(collateralForAccount, snxRate)
);
// Cap amount to liquidate to repair collateral ratio based on issuance ratio
amountToLiquidate = amountToFixRatio < susdAmount ? amountToFixRatio : susdAmount;
// what's the equivalent amount of snx for the amountToLiquidate?
uint snxRedeemed = _usdToSnx(amountToLiquidate, snxRate);
// Add penalty
totalRedeemed = snxRedeemed.multiplyDecimal(SafeDecimalMath.unit().add(liquidationPenalty));
// if total PERI to redeem is greater than account's collateral
// account is under collateralised, liquidate all collateral and reduce pUSD to burn
if (totalRedeemed > collateralForAccount) {
// set totalRedeemed to all transferable collateral
totalRedeemed = collateralForAccount;
// whats the equivalent pUSD to burn for all collateral less penalty
amountToLiquidate = _snxToUSD(
collateralForAccount.divideDecimal(SafeDecimalMath.unit().add(liquidationPenalty)),
snxRate
);
}
// burn pUSD from messageSender (liquidator) and reduce account's debt
_burnPynths(account, liquidator, amountToLiquidate, debtBalance, totalDebtIssued);
// Remove liquidation flag if amount liquidated fixes ratio
if (amountToLiquidate == amountToFixRatio) {
// Remove liquidation
liquidations().removeAccountInLiquidation(account);
}
}
/* ========== INTERNAL FUNCTIONS ========== */
function _requireRatesNotInvalid(bool anyRateIsInvalid) internal pure {
require(!anyRateIsInvalid, "A pynth or PERI rate is invalid");
}
function _requireCanIssueOnBehalf(address issueForAddress, address from) internal view {
require(delegateApprovals().canIssueFor(issueForAddress, from), "Not approved to act on behalf");
}
function _requireCanBurnOnBehalf(address burnForAddress, address from) internal view {
require(delegateApprovals().canBurnFor(burnForAddress, from), "Not approved to act on behalf");
}
function _issuePynths(
address from,
uint amount,
bool issueMax
) internal {
(uint maxIssuable, uint existingDebt, uint totalSystemDebt, bool anyRateIsInvalid) = _remainingIssuablePynths(from);
_requireRatesNotInvalid(anyRateIsInvalid);
if (!issueMax) {
require(amount <= maxIssuable, "Amount too large");
} else {
amount = maxIssuable;
}
// Keep track of the debt they're about to create
_addToDebtRegister(from, amount, existingDebt, totalSystemDebt);
// record issue timestamp
_setLastIssueEvent(from);
// Create their pynths
pynths[pUSD].issue(from, amount);
// Account for the issued debt in the cache
debtCache().updateCachedPynthDebtWithRate(pUSD, SafeDecimalMath.unit());
// Store their locked PERI amount to determine their fee % for the period
_appendAccountIssuanceRecord(from);
}
function _burnPynths(
address debtAccount,
address burnAccount,
uint amount,
uint existingDebt,
uint totalDebtIssued
) internal returns (uint amountBurnt) {
// liquidation requires pUSD to be already settled / not in waiting period
// If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just
// clear their debt and leave them be.
amountBurnt = existingDebt < amount ? existingDebt : amount;
// Remove liquidated debt from the ledger
_removeFromDebtRegister(debtAccount, amountBurnt, existingDebt, totalDebtIssued);
// pynth.burn does a safe subtraction on balance (so it will revert if there are not enough pynths).
pynths[pUSD].burn(burnAccount, amountBurnt);
// Account for the burnt debt in the cache.
debtCache().updateCachedPynthDebtWithRate(pUSD, SafeDecimalMath.unit());
// Store their debtRatio against a fee period to determine their fee/rewards % for the period
_appendAccountIssuanceRecord(debtAccount);
}
// If burning to target, `amount` is ignored, and the correct quantity of pUSD is burnt to reach the target
// c-ratio, allowing fees to be claimed. In this case, pending settlements will be skipped as the user
// will still have debt remaining after reaching their target.
function _voluntaryBurnPynths(
address from,
uint amount,
bool burnToTarget
) internal {
if (!burnToTarget) {
// If not burning to target, then burning requires that the minimum stake time has elapsed.
require(_canBurnPynths(from), "Minimum stake time not reached");
// First settle anything pending into pUSD as burning or issuing impacts the size of the debt pool
(, uint refunded, uint numEntriesSettled) = exchanger().settle(from, pUSD);
if (numEntriesSettled > 0) {
amount = exchanger().calculateAmountAfterSettlement(from, pUSD, amount, refunded);
}
}
(uint existingDebt, uint totalSystemValue, bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(from, pUSD);
(uint maxIssuablePynthsForAccount, bool snxRateInvalid) = _maxIssuablePynths(from);
_requireRatesNotInvalid(anyRateIsInvalid || snxRateInvalid);
require(existingDebt > 0, "No debt to forgive");
if (burnToTarget) {
amount = existingDebt.sub(maxIssuablePynthsForAccount);
}
uint amountBurnt = _burnPynths(from, from, amount, existingDebt, totalSystemValue);
// Check and remove liquidation if existingDebt after burning is <= maxIssuablePynths
// Issuance ratio is fixed so should remove any liquidations
if (existingDebt.sub(amountBurnt) <= maxIssuablePynthsForAccount) {
liquidations().removeAccountInLiquidation(from);
}
}
function _setLastIssueEvent(address account) internal {
// Set the timestamp of the last issuePynths
flexibleStorage().setUIntValue(
CONTRACT_NAME,
keccak256(abi.encodePacked(LAST_ISSUE_EVENT, account)),
block.timestamp
);
}
function _appendAccountIssuanceRecord(address from) internal {
uint initialDebtOwnership;
uint debtEntryIndex;
(initialDebtOwnership, debtEntryIndex) = perifinState().issuanceData(from);
feePool().appendAccountIssuanceRecord(from, initialDebtOwnership, debtEntryIndex);
}
function _addToDebtRegister(
address from,
uint amount,
uint existingDebt,
uint totalDebtIssued
) internal {
IPeriFinState state = perifinState();
// What will the new total be including the new value?
uint newTotalDebtIssued = amount.add(totalDebtIssued);
// What is their percentage (as a high precision int) of the total debt?
uint debtPercentage = amount.divideDecimalRoundPrecise(newTotalDebtIssued);
// And what effect does this percentage change have on the global debt holding of other issuers?
// The delta specifically needs to not take into account any existing debt as it's already
// accounted for in the delta from when they issued previously.
// The delta is a high precision integer.
uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage);
// And what does their debt ownership look like including this previous stake?
if (existingDebt > 0) {
debtPercentage = amount.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued);
} else {
// If they have no debt, they're a new issuer; record this.
state.incrementTotalIssuerCount();
}
// Save the debt entry parameters
state.setCurrentIssuanceData(from, debtPercentage);
// And if we're the first, push 1 as there was no effect to any other holders, otherwise push
// the change for the rest of the debt holders. The debt ledger holds high precision integers.
if (state.debtLedgerLength() > 0) {
state.appendDebtLedgerValue(state.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta));
} else {
state.appendDebtLedgerValue(SafeDecimalMath.preciseUnit());
}
}
function _removeFromDebtRegister(
address from,
uint debtToRemove,
uint existingDebt,
uint totalDebtIssued
) internal {
IPeriFinState state = perifinState();
// What will the new total after taking out the withdrawn amount
uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove);
uint delta = 0;
// What will the debt delta be if there is any debt left?
// Set delta to 0 if no more debt left in system after user
if (newTotalDebtIssued > 0) {
// What is the percentage of the withdrawn debt (as a high precision int) of the total debt after?
uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued);
// And what effect does this percentage change have on the global debt holding of other issuers?
// The delta specifically needs to not take into account any existing debt as it's already
// accounted for in the delta from when they issued previously.
delta = SafeDecimalMath.preciseUnit().add(debtPercentage);
}
// Are they exiting the system, or are they just decreasing their debt position?
if (debtToRemove == existingDebt) {
state.setCurrentIssuanceData(from, 0);
state.decrementTotalIssuerCount();
} else {
// What percentage of the debt will they be left with?
uint newDebt = existingDebt.sub(debtToRemove);
uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued);
// Store the debt percentage and debt ledger as high precision integers
state.setCurrentIssuanceData(from, newDebtPercentage);
}
// Update our cumulative ledger. This is also a high precision integer.
state.appendDebtLedgerValue(state.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta));
}
/* ========== MODIFIERS ========== */
function _onlyPeriFin() internal view {
require(msg.sender == address(perifin()), "Issuer: Only the perifin contract can perform this action");
}
modifier onlyPeriFin() {
_onlyPeriFin(); // Use an internal function to save code size.
_;
}
/* ========== EVENTS ========== */
event PynthAdded(bytes32 currencyKey, address pynth);
event PynthRemoved(bytes32 currencyKey, address pynth);
}
| What is the value of their PERI balance in pUSD They're allowed to issue up to issuanceRatio of that value | function _maxIssuablePynths(address _issuer) internal view returns (uint, bool) {
(uint snxRate, bool isInvalid) = exchangeRates().rateAndInvalid(PERI);
uint destinationValue = _snxToUSD(_collateral(_issuer), snxRate);
return (destinationValue.multiplyDecimal(getIssuanceRatio()), isInvalid);
}
| 1,089,729 | [
1,
23801,
353,
326,
460,
434,
3675,
10950,
45,
11013,
316,
293,
3378,
40,
16448,
4565,
2935,
358,
5672,
731,
358,
3385,
89,
1359,
8541,
434,
716,
460,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
1896,
7568,
89,
429,
52,
878,
451,
87,
12,
2867,
389,
17567,
13,
2713,
1476,
1135,
261,
11890,
16,
1426,
13,
288,
203,
3639,
261,
11890,
4556,
92,
4727,
16,
1426,
353,
1941,
13,
273,
7829,
20836,
7675,
5141,
1876,
1941,
12,
3194,
45,
1769,
203,
3639,
2254,
2929,
620,
273,
389,
8134,
92,
774,
3378,
40,
24899,
12910,
2045,
287,
24899,
17567,
3631,
4556,
92,
4727,
1769,
203,
203,
3639,
327,
261,
10590,
620,
18,
7027,
1283,
5749,
12,
588,
7568,
89,
1359,
8541,
1435,
3631,
353,
1941,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x2B9f2f30F722dD4917bd877D976adc4966A99333/sources/node_modules/@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBFundingCycleDataSource3_1_1.sol | @title Datasource @notice The datasource is called by JBPayoutRedemptionPaymentTerminals on pay and redemption, and provide an extra layer of logic to use a custom weight, a custom memo and/or a pay/redeem delegate | interface IJBFundingCycleDataSource3_1_1 is IERC165 {
function payParams(
JBPayParamsData calldata data
)
external
view
returns (
uint256 weight,
string memory memo,
JBPayDelegateAllocation3_1_1[] memory delegateAllocations
);
function redeemParams(
JBRedeemParamsData calldata data
)
external
view
returns (
uint256 reclaimAmount,
string memory memo,
JBRedemptionDelegateAllocation3_1_1[] memory delegateAllocations
);
pragma solidity ^0.8.0;
import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';
import {JBPayDelegateAllocation3_1_1} from './../structs/JBPayDelegateAllocation3_1_1.sol';
import {JBPayParamsData} from './../structs/JBPayParamsData.sol';
import {JBRedeemParamsData} from './../structs/JBRedeemParamsData.sol';
import {JBRedemptionDelegateAllocation3_1_1} from './../structs/JBRedemptionDelegateAllocation3_1_1.sol';
}
| 2,973,353 | [
1,
14305,
552,
225,
1021,
9181,
353,
2566,
635,
804,
30573,
2012,
426,
19117,
375,
6032,
27506,
1031,
603,
8843,
471,
283,
19117,
375,
16,
471,
5615,
392,
2870,
3018,
434,
4058,
358,
999,
279,
1679,
3119,
16,
279,
1679,
11063,
471,
19,
280,
279,
8843,
19,
266,
24903,
7152,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
8877,
42,
14351,
13279,
8597,
23,
67,
21,
67,
21,
353,
467,
654,
39,
28275,
288,
203,
225,
445,
8843,
1370,
12,
203,
565,
804,
38,
9148,
1370,
751,
745,
892,
501,
203,
225,
262,
203,
565,
3903,
203,
565,
1476,
203,
565,
1135,
261,
203,
1377,
2254,
5034,
3119,
16,
203,
1377,
533,
3778,
11063,
16,
203,
1377,
804,
38,
9148,
9586,
17353,
23,
67,
21,
67,
21,
8526,
3778,
7152,
8763,
1012,
203,
565,
11272,
203,
203,
225,
445,
283,
24903,
1370,
12,
203,
565,
804,
38,
426,
24903,
1370,
751,
745,
892,
501,
203,
225,
262,
203,
565,
3903,
203,
565,
1476,
203,
565,
1135,
261,
203,
1377,
2254,
5034,
283,
14784,
6275,
16,
203,
1377,
533,
3778,
11063,
16,
203,
1377,
804,
38,
426,
19117,
375,
9586,
17353,
23,
67,
21,
67,
21,
8526,
3778,
7152,
8763,
1012,
203,
565,
11272,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
5666,
288,
45,
654,
39,
28275,
97,
628,
4622,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
5471,
19,
474,
26362,
19,
45,
654,
39,
28275,
18,
18281,
13506,
203,
5666,
288,
8877,
9148,
9586,
17353,
23,
67,
21,
67,
21,
97,
628,
12871,
6216,
1697,
87,
19,
8877,
9148,
9586,
17353,
23,
67,
21,
67,
21,
18,
18281,
13506,
203,
5666,
288,
8877,
9148,
1370,
751,
97,
628,
12871,
6216,
1697,
87,
19,
8877,
9148,
1370,
751,
18,
18281,
13506,
203,
5666,
288,
8877,
426,
24903,
1370,
751,
97,
628,
12871,
2
] |
/**
*Submitted for verification at Etherscan.io on 2021-04-15
*/
// SPDX-License-Identifier: AGPL-3.0-or-later
/// ClipperMom.sol -- governance interface for the Clipper
// Copyright (C) 2021 Maker Ecosystem Growth Holdings, INC.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
pragma solidity >=0.6.12;
interface ClipLike {
function file(bytes32, uint256) external;
function ilk() external view returns (bytes32);
function stopped() external view returns (uint256);
}
interface AuthorityLike {
function canCall(address src, address dst, bytes4 sig) external view returns (bool);
}
interface OsmLike {
function peek() external view returns (uint256, bool);
function peep() external view returns (uint256, bool);
}
interface SpotterLike {
function ilks(bytes32) external view returns (OsmLike, uint256);
}
contract ClipperMom {
address public owner;
address public authority;
mapping (address => uint256) public locked; // timestamp when becomes unlocked (per clipper)
mapping (address => uint256) public tolerance; // clipper -> ray
SpotterLike public immutable spotter;
event SetOwner(address indexed oldOwner, address indexed newOwner);
event SetAuthority(address indexed oldAuthority, address indexed newAuthority);
event SetBreaker(address indexed clip, uint256 level);
modifier onlyOwner {
require(msg.sender == owner, "ClipperMom/only-owner");
_;
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig), "ClipperMom/not-authorized");
_;
}
constructor(address spotter_) public {
owner = msg.sender;
spotter = SpotterLike(spotter_);
emit SetOwner(address(0), msg.sender);
}
// --- Math ---
uint256 constant WAD = 10 ** 18;
uint256 constant RAY = 10 ** 27;
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x);
}
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = mul(x, y) / RAY;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == address(0)) {
return false;
} else {
return AuthorityLike(authority).canCall(src, address(this), sig);
}
}
function getPrices(address clip) internal view returns (uint256 cur, uint256 nxt) {
(OsmLike osm, ) = spotter.ilks(ClipLike(clip).ilk());
bool has;
(cur, has) = osm.peek();
require(has, "ClipperMom/invalid-cur-price");
(nxt, has) = osm.peep();
require(has, "ClipperMom/invalid-nxt-price");
}
// Governance actions with delay
function setOwner(address owner_) external onlyOwner {
emit SetOwner(owner, owner_);
owner = owner_;
}
function setAuthority(address authority_) external onlyOwner {
emit SetAuthority(authority, authority_);
authority = authority_;
}
// Set the price tolerance for a specific ilk.
// The price tolerance is the minimum acceptable value a new price can have relative to the previous price
// For instance, a tolerance of 0.6 means that a new price can't be lower than 60% of the previous price
// 0.6 * RAY = 600000000000000000000000000 => means acceptable drop from previous price is up to 40%
function setPriceTolerance(address clip, uint256 value) external onlyOwner {
require(value <= 1 * RAY, "ClipperMom/tolerance-out-of-bounds");
tolerance[clip] = value;
}
// Governance action without delay
function setBreaker(address clip, uint256 level, uint256 delay) external auth {
require(level <= 3, "ClipperMom/nonexistent-level");
ClipLike(clip).file("stopped", level);
// If governance changes the status of the breaker we want to lock for one hour
// the permissionless function so the osm can pull new nxt price to compare
locked[clip] = add(block.timestamp, delay);
emit SetBreaker(clip, level);
}
/**
The following implements a permissionless circuit breaker in case the price reported by an oracle
for a particular collateral type will drop below than a governance-defined % from 1 hour to the next.
The setPriceTolerance function sets that % (as a value between 0 and RAY) for a specific collateral type.
tripBreaker takes the address of some ilk's Clipper.
It then gets the current and next price and checks whether the next price is less than the minimum
acceptable next price based on the tolerance. If the next price is unacceptable (lower than rmul(current_price, tolerance)),
it stops creation of new auctions and resets of current auctions for the Clipper's ilk. Currently, governance
must reset the breaker manually.
*/
function tripBreaker(address clip) external {
require(ClipLike(clip).stopped() < 2, "ClipperMom/clipper-already-stopped");
require(block.timestamp > locked[clip], "ClipperMom/temporary-locked");
(uint256 cur, uint256 nxt) = getPrices(clip);
// tolerance[clip] == 0 will always make the following require to revert
require(nxt < rmul(cur, tolerance[clip]), "ClipperMom/price-within-bounds");
ClipLike(clip).file("stopped", 2);
emit SetBreaker(clip, 2);
}
} | timestamp when becomes unlocked (per clipper)
| mapping (address => uint256) public locked; | 6,700,771 | [
1,
5508,
1347,
12724,
25966,
261,
457,
6807,
457,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1071,
8586,
31,
377,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.19;
//pragma experimental ABIEncoderV2;
import "./ownable.sol";
import "./safemath.sol";
contract FactualNews is Ownable {
// Parameters
uint percentageAuditors = 10; // in %
uint percentageCompany = 5; // in %
string retMsg;
string _statusTemp;
// Request Status
string requestStatus = "Blank"; // This status can be "Blank", "Requested", "Approve Reviewer", "Reviewing" , "Auditing" , "Approved" or "Denied"
// Data structures associated to originators
mapping (address => uint) originatorToId; // links originator, person who created the request, address to id in the fundAmount array
uint[] fundAmount; // carries the actual ammount
address[] originatorsList;
uint totalFundAmount;
uint requestReviewId; // carries the request Id
// Data structures associated to reviewers
mapping (address => uint) reviewerToId; // links reviewer to id in reviewStatus array
bool[] reviewStatus; // status of revision - true is done and false is in progress
address[] reviewersList;
// Data structures associated to auditors
mapping (address => uint) auditorToId; // links auditor to id in auditorStatus array
string[] auditorStatus; // status of auditing - "Not initiated" , "Approved" or "Denied"
address[] auditorsList;
uint totalAuditors;
// Iniitate a review request
function createRequest(uint _requestReviewId) public {
if (keccak256(requestStatus) == keccak256("Blank")) {
requestStatus = "Requested";
requestReviewId = _requestReviewId;
totalFundAmount = 0;
totalAuditors = 0;
}
else {
revert();
}
}
// Get to total amount committed in this request
function getTotalRequestInfo() external view returns(string _requestStatus,
uint _requestReviewId,
uint _totalFundAmount,
uint[] _fundAmount,
address[] _originatorsList) {
_requestStatus = requestStatus;
_requestReviewId = requestReviewId;
_totalFundAmount = totalFundAmount;
_fundAmount = fundAmount;
_originatorsList = originatorsList;
}
modifier nonZeroValue() { if (!(msg.value > 0)) revert(); _; }
function findOriginator(address addr) internal returns (uint) {
uint i;
uint len;
len = originatorsList.length;
for (i=0;i<len;i++) {
if (addr == originatorsList[i]) {
return (i+1);
}
}
return 0;
}
// Add funds
function addReviewFunds() public payable {
if (keccak256(requestStatus) == keccak256("Requested")) {
uint _id = findOriginator(msg.sender);
if (_id == 0) {
_id = fundAmount.push(msg.value);
originatorsList.push(msg.sender);
originatorToId[msg.sender] = _id;
}
else {
fundAmount[_id-1] += msg.value;
originatorsList[_id-1] = msg.sender;
}
totalFundAmount += msg.value;
}
else {
revert();
}
}
// Withdrawal all money
function withdrawal(uint _amount, address _recipient) external onlyOwner {
uint transferAmount;
transferAmount = _amount;
if ( (_amount > totalFundAmount) || (_amount == 0) ) {
transferAmount = totalFundAmount;
}
totalFundAmount -= transferAmount;
_recipient.send(transferAmount);
}
//demo only allows ANYONE to withdraw
function withdrawAll() external {
totalFundAmount = 0;
require(msg.sender.send(this.balance));
}
function findReviewer(address addr) internal returns (uint) {
uint i;
uint len;
len = reviewersList.length;
for (i=0;i<len;i++) {
if (addr == reviewersList[i]) {
return (i+1);
}
}
return 0;
}
// Reviewers candidatate apply to review.
function applyForReview() public {
if (keccak256(requestStatus) == keccak256("Requested")) {
requestStatus = "Approve Reviewer";
uint _id = findReviewer(msg.sender);
if (_id == 0) {
_id = reviewStatus.push(false);
reviewersList.push(msg.sender);
reviewerToId[msg.sender] = _id;
}
else {
reviewStatus[_id-1] = false;
reviewersList[_id-1] = msg.sender;
}
}
else {
revert();
}
}
// Get review status
function getReviewStatusInfo() external view returns(bool[] _reviewStatus, address[] _reviewersList) {
_reviewStatus = reviewStatus;
_reviewersList = reviewersList;
}
function findAuditor(address addr) internal returns (uint) {
uint i;
uint len;
len = auditorsList.length;
for (i=0;i<len;i++) {
if (addr == auditorsList[i]) {
return (i+1);
}
}
return 0;
}
// Apply for Auditors
function applyForAuditing() external {
if ((keccak256(requestStatus) == keccak256("Requested")) ||
(keccak256(requestStatus) == keccak256("Approve Reviewer")) ) {
uint _id = findAuditor(msg.sender);
if (_id == 0) {
_id = auditorStatus.push("Not initiated");
auditorsList.push(msg.sender);
auditorToId[msg.sender] = _id;
totalAuditors++;
}
else {
auditorStatus[_id-1] = "Not initiated";
auditorsList[_id-1] = msg.sender;
}
}
else {
revert();
}
}
// Get auditor status
function getAuditorStatusInfo() external view returns(uint _totalAuditors, address[] _auditorsList) {
_totalAuditors = totalAuditors;
_auditorsList = auditorsList;
}
// Only the originator can approve Reviewers and Auditors
function approveReviewerAuditors() public onlyOwner {
if ((keccak256(requestStatus) == keccak256("Approve Reviewer")) &&
(totalAuditors > 0) ) {
requestStatus = "Reviewing";
}
else {
revert();
}
}
// Only first reviewer can trigger the auditing
function finishReview() public {
if ((keccak256(requestStatus) == keccak256("Reviewing")) &&
(reviewersList[0] == msg.sender) ) {
requestStatus = "Auditing";
}
else {
revert();
}
}
// Counts how many auditors have already approved
function _countStatus(string _status) private returns (uint) {
uint count = 0;
for (uint i=0; i < totalAuditors; i++) {
if (keccak256(auditorStatus[i]) == keccak256(_status)) {
count++;
}
}
return count;
}
//Check the outcome of auditing - Approved, Denied, Undefined
function _checkAuditingStatus() private returns (string) {
uint _countApproved;
uint _countDenied;
uint tempTotalAuditors;
_countApproved = _countStatus("Approved");
_countDenied = _countStatus("Denied");
// case which is tied
if ( ((totalAuditors % 2) == 0) &&
(totalAuditors == (_countApproved + _countDenied)) &&
(_countApproved == _countDenied) ) {
return "Denied";
}
if ((totalAuditors % 2) != 0) {
tempTotalAuditors = totalAuditors + 1;
}
else {
tempTotalAuditors = totalAuditors;
}
// Majority denied
if (_countDenied >= (tempTotalAuditors/2)) {
return "Denied";
}
// Majority Approved
if (_countApproved >= (tempTotalAuditors/2)) {
return "Approved";
}
return "Undefined";
}
// This function process all payments refering to the end o review process
function _finalizeRequestReview(string _status) private {
uint auditorsValue;
uint i;
uint remainder;
uint remainderOriginators;
uint totalOriginators;
uint originatorPart;
uint totalReviewers;
uint reviewerPart;
if (totalAuditors == 0) {
auditorsValue = 0;
}
else {
auditorsValue = (totalFundAmount * percentageAuditors / 100) / totalAuditors;
}
remainder = totalFundAmount;
for (i=0; i < totalAuditors; i++) {
auditorsList[i].transfer(auditorsValue);
remainder -= auditorsValue;
}
// Company should get paid here
remainder -= (totalFundAmount * percentageCompany / 100) / totalAuditors;
// Pay the reviewers in case that review was approved
if (keccak256(_status) == keccak256("Approved")) {
totalReviewers = reviewersList.length;
reviewerPart = remainder / totalReviewers;
for (i=0; i < totalReviewers; i++) {
reviewersList[i].transfer(reviewerPart);
remainder -= reviewerPart;
}
}
// Or return the funds to the originators
else {
totalOriginators = originatorsList.length;
remainderOriginators = remainder;
for (i=0; i < totalOriginators; i++) {
originatorPart = fundAmount[i]*remainderOriginators/totalFundAmount;
originatorsList[i].transfer(originatorPart);
remainder -= originatorPart;
}
}
totalFundAmount = remainder;
}
function toString(address x) internal returns (string) {
bytes memory b = new bytes(20);
for (uint i = 0; i < 20; i++)
b[i] = byte(uint8(uint(x) / (2**(8*(19 - i)))));
return string(b);
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint length;
while (j != 0){
length++;
j /= 10;
}
bytes memory bstr = new bytes(length);
uint k = length - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string){
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
// Auditors give their appreciation on the review
function auditReview(string decision) external payable returns (string) {
retMsg = "";
if ((keccak256(requestStatus) == keccak256("Auditing"))
&& (findAuditor(msg.sender) != 0)
) {
uint _id = findAuditor(msg.sender) - 1;
if (keccak256(decision) == keccak256("Approved")) {
auditorStatus[_id] = "Approved";
}
else {
auditorStatus[_id] = "Denied";
}
// Check auditing status
_statusTemp = string(_checkAuditingStatus());
if (keccak256(_statusTemp) != keccak256("Undefined")) {
_finalizeRequestReview(_statusTemp);
requestStatus = _statusTemp;
}
}
else {
retMsg = string(strConcat(toString(msg.sender), " - ", uint2str(findAuditor(msg.sender)), "",""));
}
return string(retMsg);
}
} | Company should get paid here | remainder -= (totalFundAmount * percentageCompany / 100) / totalAuditors;
| 12,807,927 | [
1,
12627,
1410,
336,
30591,
2674,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
10022,
3947,
261,
4963,
42,
1074,
6275,
380,
11622,
12627,
342,
2130,
13,
342,
2078,
10832,
1383,
31,
7010,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
/**
* @title RestrictedToken
* @dev An ERC20 token that can only be transferred to whitelisted accounts.
*/
contract RestrictedToken is Ownable, ERC20, ERC20Detailed {
// Approved recipients of the token
mapping (address => bool) _whitelist;
// events
event Whitelisted(address whitelisted);
event Removed(address removed);
/**
* @dev Initialize a restricted token. `msg.sender` gets all the tokens.
* @param name The token name
* @param symbol The token's symbol
* @param decimals The number of decimals
* @param initialSupply The supply of tokens
* @param initialWhitelist The initial set of accounts approved to receive token transfers.
*/
constructor(
string memory name,
string memory symbol,
uint8 decimals,
uint initialSupply,
address[] memory initialWhitelist
)
public
ERC20Detailed(name, symbol, decimals)
{
// Owner gets the initial supply
_mint(msg.sender, initialSupply);
// Whitelist the initial set of accounts. Duplicate addresses are a noop.
for (uint i = 0; i < initialWhitelist.length; i++) {
address account = initialWhitelist[i];
addToWhitelist(account);
}
}
// Whitelist functions
/**
* @dev Check if an account is whitelisted for transfers
* @param account The address to check
* @return true if the account is whitelisted
*/
function isWhitelisted(address account) public view returns (bool) {
return _whitelist[account];
}
/**
* @dev Add an account to the whitelist for transfers. Revert on zero address.
* @param account The address to add
*/
function addToWhitelist(address account) public onlyOwner {
require(account != address(0), "Invalid account address");
require(isWhitelisted(account) == false, "Account is already whitelisted");
_whitelist[account] = true;
emit Whitelisted(account);
}
/**
* @dev Remove an account from the whitelist for transfers. Revert on zero address.
* @param account The address to remove
*/
function removeFromWhitelist(address account) public onlyOwner {
require(account != address(0), "Invalid account address");
require(isWhitelisted(account) == true, "Cannot remove a non-whitelisted account");
_whitelist[account] = false;
emit Removed(account);
}
// Overrides
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return true if the transfer was successful
*/
function transfer(address to, uint256 value) public returns (bool) {
require(isWhitelisted(to), "Token cannot be be transferred to non-whitelisted address");
return super.transfer(to, value);
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
* @return true if the transfer was successful
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
require(isWhitelisted(to), "Token cannot be be transferred to non-whitelisted address");
return super.transferFrom(from, to, value);
}
}
| * @dev Add an account to the whitelist for transfers. Revert on zero address. @param account The address to add/ | function addToWhitelist(address account) public onlyOwner {
require(account != address(0), "Invalid account address");
require(isWhitelisted(account) == false, "Account is already whitelisted");
_whitelist[account] = true;
emit Whitelisted(account);
}
| 7,276,700 | [
1,
986,
392,
2236,
358,
326,
10734,
364,
29375,
18,
868,
1097,
603,
3634,
1758,
18,
225,
2236,
1021,
1758,
358,
527,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
9604,
18927,
12,
2867,
2236,
13,
1071,
1338,
5541,
288,
203,
3639,
2583,
12,
4631,
480,
1758,
12,
20,
3631,
315,
1941,
2236,
1758,
8863,
203,
3639,
2583,
12,
291,
18927,
329,
12,
4631,
13,
422,
629,
16,
315,
3032,
353,
1818,
26944,
8863,
203,
203,
3639,
389,
20409,
63,
4631,
65,
273,
638,
31,
203,
3639,
3626,
3497,
7523,
329,
12,
4631,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/42/0x231F7f060DdCB71284327d160ccF79DFf4cd38eF/sources/STBL.sol | Add Balancer Pool Token address
| BPT = TokenInterface(0x8D3C9B57EdD6f152532945e7e5F0ABF5f010AfE0); | 16,263,519 | [
1,
986,
605,
5191,
8828,
3155,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1377,
605,
1856,
273,
29938,
12,
20,
92,
28,
40,
23,
39,
29,
38,
10321,
2671,
40,
26,
74,
3600,
2947,
1578,
29,
7950,
73,
27,
73,
25,
42,
20,
2090,
42,
25,
74,
23254,
12664,
41,
20,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
/** title -Divies- v0.7.1
* ┌──────────────────────────────────────────────────────────────────────┐
* │ Divies!, is a contract that adds an external dividend system to H4D. │
* │ All eth sent to this contract, can be distributed to H4D holders. │
* │ Uses msg.sender as masternode for initial buy order. │
* └──────────────────────────────────────────────────────────────────────┘
* ┌────────────────────┐
* │ Setup Instructions │
* └────────────────────┘
* (Step 1) import this contracts interface into your contract
*
* import "./DiviesInterface.sol";
*
* (Step 2) set up the interface and point it to this contract
*
* DiviesInterface private Divies = DiviesInterface(0x63456554CC52038bE211FdC3DcF03F617BCfC80D);
* ┌────────────────────┐
* │ Usage Instructions │
* └────────────────────┘
* call as follows anywhere in your code:
*
* Divies.deposit.value(amount)();
* ex: Divies.deposit.value(232000000000000000000)();
*/
interface HourglassInterface {
function() payable external;
function buy(address _playerAddress) payable external returns(uint256);
function sell(uint256 _amountOfTokens) external;
function reinvest() external;
function withdraw() external;
function exit() external;
function dividendsOf(address _playerAddress) external view returns(uint256);
function balanceOf(address _playerAddress) external view returns(uint256);
function transfer(address _toAddress, uint256 _amountOfTokens) external returns(bool);
function stakingRequirement() external view returns(uint256);
}
contract Divies {
using SafeMath for uint256;
using UintCompressor for uint256;
HourglassInterface constant H4Dcontract_ = HourglassInterface(0x63456554CC52038bE211FdC3DcF03F617BCfC80D);
uint256 public pusherTracker_ = 100;
mapping (address => Pusher) public pushers_;
struct Pusher
{
uint256 tracker;
uint256 time;
}
uint256 public rateLimiter_;
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// MODIFIERS
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
modifier isHuman() {
require(tx.origin == msg.sender);
_;
}
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// BALANCE
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
function balances()
public
view
returns(uint256)
{
return (address(this).balance);
}
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// DEPOSIT
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
function deposit()
external
payable
{
}
// used so the distribute function can call hourglass's withdraw
function() external payable {}
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// EVENTS
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
event onDistribute(
address pusher,
uint256 startingBalance,
uint256 masternodePayout,
uint256 finalBalance,
uint256 compressedData
);
/* compression key
[0-14] - timestamp
[15-29] - caller pusher tracker
[30-44] - global pusher tracker
[45-46] - percent
[47] - greedy
*/
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// DISTRIBUTE
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
function distribute(uint256 _percent)
public
isHuman()
{
// make sure _percent is within boundaries
require(_percent > 0 && _percent < 100, "please pick a percent between 1 and 99");
// data setup
address _pusher = msg.sender;
uint256 _bal = address(this).balance;
uint256 _mnPayout;
uint256 _compressedData;
// limit pushers greed (use "if" instead of require for level 42 top kek)
if (
pushers_[_pusher].tracker <= pusherTracker_.sub(100) && // pusher is greedy: wait your turn
pushers_[_pusher].time.add(1 hours) < now // pusher is greedy: its not even been 1 hour
)
{
// update pushers wait que
pushers_[_pusher].tracker = pusherTracker_;
pusherTracker_++;
// setup mn payout for event
if (H4Dcontract_.balanceOf(_pusher) >= H4Dcontract_.stakingRequirement())
_mnPayout = (_bal / 10) / 3;
// setup _stop. this will be used to tell the loop to stop
uint256 _stop = (_bal.mul(100 - _percent)) / 100;
// buy & sell
H4Dcontract_.buy.value(_bal)(_pusher);
H4Dcontract_.sell(H4Dcontract_.balanceOf(address(this)));
// setup tracker. this will be used to tell the loop to stop
uint256 _tracker = H4Dcontract_.dividendsOf(address(this));
// reinvest/sell loop
while (_tracker >= _stop)
{
// lets burn some tokens to distribute dividends to H4D holders
H4Dcontract_.reinvest();
H4Dcontract_.sell(H4Dcontract_.balanceOf(address(this)));
// update our tracker with estimates (yea. not perfect, but cheaper on gas)
_tracker = (_tracker.mul(81)) / 100;
}
// withdraw
H4Dcontract_.withdraw();
} else {
_compressedData = _compressedData.insert(1, 47, 47);
}
// update pushers timestamp (do outside of "if" for super saiyan level top kek)
pushers_[_pusher].time = now;
// prep event compression data
_compressedData = _compressedData.insert(now, 0, 14);
_compressedData = _compressedData.insert(pushers_[_pusher].tracker, 15, 29);
_compressedData = _compressedData.insert(pusherTracker_, 30, 44);
_compressedData = _compressedData.insert(_percent, 45, 46);
// fire event
emit onDistribute(_pusher, _bal, _mnPayout, address(this).balance, _compressedData);
}
}
/**
* @title -UintCompressor- v0.1.9
*/
library UintCompressor {
using SafeMath for *;
function insert(uint256 _var, uint256 _include, uint256 _start, uint256 _end)
internal
pure
returns(uint256)
{
// check conditions
require(_end < 77 && _start < 77, "start/end must be less than 77");
require(_end >= _start, "end must be >= start");
// format our start/end points
_end = exponent(_end).mul(10);
_start = exponent(_start);
// check that the include data fits into its segment
require(_include < (_end / _start));
// build middle
if (_include > 0)
_include = _include.mul(_start);
return((_var.sub((_var / _start).mul(_start))).add(_include).add((_var / _end).mul(_end)));
}
function extract(uint256 _input, uint256 _start, uint256 _end)
internal
pure
returns(uint256)
{
// check conditions
require(_end < 77 && _start < 77, "start/end must be less than 77");
require(_end >= _start, "end must be >= start");
// format our start/end points
_end = exponent(_end).mul(10);
_start = exponent(_start);
// return requested section
return((((_input / _start).mul(_start)).sub((_input / _end).mul(_end))) / _start);
}
function exponent(uint256 _position)
private
pure
returns(uint256)
{
return((10).pwr(_position));
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ MODIFIERS^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | modifier isHuman() {
require(tx.origin == msg.sender);
_;
}
| 432,402 | [
1,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
66,
8663,
10591,
55,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
20254,
66,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
9606,
27803,
6925,
1435,
288,
203,
3639,
2583,
12,
978,
18,
10012,
422,
1234,
18,
15330,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.10;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol";
import "eth-token-recover/contracts/TokenRecover.sol";
import "dao-smartcontracts/contracts/dao/DAO.sol";
/**
* @title TokenFaucet
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev Implementation of a TokenFaucet
*/
contract TokenFaucet is TokenRecover {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event FaucetCreated(address indexed token);
// struct representing the enabled faucet
struct FaucetDetail {
bool exists;
bool enabled;
uint256 dailyRate;
uint256 referralRate;
uint256 totalDistributedTokens;
}
// struct representing the faucet status for an account
struct RecipientDetail {
bool exists;
mapping(address => uint256) tokens;
mapping(address => uint256) lastUpdate;
address referral;
}
// struct representing the referral status
struct ReferralDetail {
mapping(address => uint256) tokens;
address[] recipients;
}
// the time between two tokens claim
uint256 private _pauseTime = 1 days;
// the DAO smart contract
DAO private _dao;
// list of addresses who received tokens
address[] private _recipients;
// map of address and faucet details
mapping(address => FaucetDetail) private _faucetList;
// map of address and received token amount
mapping(address => RecipientDetail) private _recipientList;
// map of address and referred addresses
mapping(address => ReferralDetail) private _referralList;
/**
* @param dao DAO the decentralized organization address
*/
constructor(address payable dao) public {
require(dao != address(0), "TokenFaucet: dao is the zero address");
_dao = DAO(dao);
}
/**
* @return the DAO smart contract
*/
function dao() public view returns (DAO) {
return _dao;
}
/**
* @param token The token address to check
* @return if faucet is enabled or not
*/
function isEnabled(address token) public view returns (bool) {
return _faucetList[token].enabled;
}
/**
* @param token The token address to check
* @return the daily rate of tokens distributed
*/
function getDailyRate(address token) public view returns (uint256) {
return _faucetList[token].dailyRate;
}
/**
* @param token The token address to check
* @return the value earned by referral for each recipient
*/
function getReferralRate(address token) public view returns (uint256) {
return _faucetList[token].referralRate;
}
/**
* @param token The token address to check
* @return the sum of distributed tokens
*/
function totalDistributedTokens(address token) public view returns (uint256) {
return _faucetList[token].totalDistributedTokens;
}
/**
* @dev return the number of remaining tokens to distribute
* @param token The token address to check
* @return uint256
*/
function remainingTokens(address token) public view returns (uint256) {
return IERC20(token).balanceOf(address(this));
}
/**
* @return address of a recipient by list index
*/
function getRecipientAddress(uint256 index) public view returns (address) {
return _recipients[index];
}
/**
* @dev return the recipients length
* @return uint
*/
function getRecipientsLength() public view returns (uint) {
return _recipients.length;
}
/**
* @param account The address to check
* @param token The token address to check
* @return received token amount for the given address
*/
function receivedTokens(address account, address token) public view returns (uint256) {
return _recipientList[account].tokens[token];
}
/**
* @param account The address to check
* @param token The token address to check
* @return last tokens received timestamp
*/
function lastUpdate(address account, address token) public view returns (uint256) {
return _recipientList[account].lastUpdate[token];
}
/**
* @param account The address to check
* @return referral for given address
*/
function getReferral(address account) public view returns (address) {
return _recipientList[account].referral;
}
/**
* @param account The address to check
* @param token The token address to check
* @return earned tokens by referrals
*/
function earnedByReferral(address account, address token) public view returns (uint256) {
return _referralList[account].tokens[token];
}
/**
* @param account The address to check
* @return referred addresses for given address
*/
function getReferredAddresses(address account) public view returns (address[] memory) {
return _referralList[account].recipients;
}
/**
* @param account The address to check
* @return referred addresses for given address
*/
function getReferredAddressesLength(address account) public view returns (uint) {
return _referralList[account].recipients.length;
}
/**
* @param account The address to check
* @param token The token address to check
* @return time of next available claim or zero
*/
function nextClaimTime(address account, address token) public view returns (uint256) {
return lastUpdate(account, token) == 0 ? 0 : lastUpdate(account, token) + _pauseTime;
}
/**
* @param token Address of the token being distributed
* @param dailyRate Daily rate of tokens distributed
* @param referralRate The value earned by referral
*/
function createFaucet(address token, uint256 dailyRate, uint256 referralRate) public onlyOwner {
require(!_faucetList[token].exists, "TokenFaucet: token faucet already exists");
require(token != address(0), "TokenFaucet: token is the zero address");
require(dailyRate > 0, "TokenFaucet: dailyRate is 0");
require(referralRate > 0, "TokenFaucet: referralRate is 0");
_faucetList[token].exists = true;
_faucetList[token].enabled = true;
_faucetList[token].dailyRate = dailyRate;
_faucetList[token].referralRate = referralRate;
emit FaucetCreated(token);
}
/**
* @dev change daily referral rate
* @param token Address of tokens being updated
* @param newDailyRate Daily rate of tokens distributed
* @param newReferralRate The value earned by referral
*/
function setFaucetRates(address token, uint256 newDailyRate, uint256 newReferralRate) public onlyOwner {
require(_faucetList[token].exists, "TokenFaucet: token faucet does not exist");
require(newDailyRate > 0, "TokenFaucet: dailyRate is 0");
require(newReferralRate > 0, "TokenFaucet: referralRate is 0");
_faucetList[token].dailyRate = newDailyRate;
_faucetList[token].referralRate = newReferralRate;
}
/**
* @dev disable a faucet
* @param token Address of tokens being updated
*/
function disableFaucet(address token) public onlyOwner {
require(_faucetList[token].exists, "TokenFaucet: token faucet does not exist");
_faucetList[token].enabled = false;
}
/**
* @dev enable a faucet
* @param token Address of tokens being updated
*/
function enableFaucet(address token) public onlyOwner {
require(_faucetList[token].exists, "TokenFaucet: token faucet does not exist");
_faucetList[token].enabled = true;
}
/**
* @dev function to be called to receive tokens
* @param token The token address to distribute
*/
function getTokens(address token) public {
require(_faucetList[token].exists, "TokenFaucet: token faucet does not exist");
require(_dao.isMember(msg.sender), "TokenFaucet: message sender is not dao member");
// distribute tokens
_distributeTokens(token, msg.sender, address(0));
}
/**
* @dev function to be called to receive tokens
* @param token The token address to distribute
* @param referral Address to an account that is referring
*/
function getTokensWithReferral(address token, address referral) public {
require(_faucetList[token].exists, "TokenFaucet: token faucet does not exist");
require(_dao.isMember(msg.sender), "TokenFaucet: message sender is not dao member");
require(referral != msg.sender, "TokenFaucet: referral cannot be message sender");
// distribute tokens
_distributeTokens(token, msg.sender, referral);
}
/**
* @dev The way in which faucet tokens rate is calculated for recipient
* @param token Address of tokens being distributed
* @param account Address receiving the tokens
* @return Number of tokens that can be received
*/
function _getRecipientTokenAmount(address token, address account) internal view returns (uint256) {
uint256 tokenAmount = getDailyRate(token);
if (_dao.stakedTokensOf(account) > 0) {
tokenAmount = tokenAmount.mul(2);
}
if (_dao.usedTokensOf(account) > 0) {
tokenAmount = tokenAmount.mul(2);
}
return tokenAmount;
}
/**
* @dev The way in which faucet tokens rate is calculated for referral
* @param token Address of tokens being distributed
* @param account Address receiving the tokens
* @return Number of tokens that can be received
*/
function _getReferralTokenAmount(address token, address account) internal view returns (uint256) {
uint256 tokenAmount = 0;
if (_dao.isMember(account)) {
tokenAmount = getReferralRate(token);
if (_dao.stakedTokensOf(account) > 0) {
tokenAmount = tokenAmount.mul(2);
}
if (_dao.usedTokensOf(account) > 0) {
tokenAmount = tokenAmount.mul(2);
}
}
return tokenAmount;
}
/**
* @dev distribute tokens
* @param token The token being distributed
* @param account Address being distributing
* @param referral Address to an account that is referring
*/
function _distributeTokens(address token, address account, address referral) internal {
// solhint-disable-next-line not-rely-on-time
require(nextClaimTime(account, token) <= block.timestamp, "TokenFaucet: next claim date is not passed");
// check if recipient exists
if (!_recipientList[account].exists) {
_recipients.push(account);
_recipientList[account].exists = true;
// check if valid referral
if (referral != address(0)) {
_recipientList[account].referral = referral;
_referralList[referral].recipients.push(account);
}
}
uint256 recipientTokenAmount = _getRecipientTokenAmount(token, account);
// update recipient status
// solhint-disable-next-line not-rely-on-time
_recipientList[account].lastUpdate[token] = block.timestamp;
_recipientList[account].tokens[token] = _recipientList[account].tokens[token].add(recipientTokenAmount);
// update faucet status
_faucetList[token].totalDistributedTokens = _faucetList[token].totalDistributedTokens.add(recipientTokenAmount);
// transfer tokens to recipient
IERC20(token).safeTransfer(account, recipientTokenAmount);
// check referral
if (_recipientList[account].referral != address(0)) {
// referral is only the first one referring
address firstReferral = _recipientList[account].referral;
uint256 referralTokenAmount = _getReferralTokenAmount(token, firstReferral);
// referral can earn only if it is dao member
if (referralTokenAmount > 0) {
// update referral status
_referralList[firstReferral].tokens[token] = _referralList[firstReferral].tokens[token].add(referralTokenAmount);
// update faucet status
_faucetList[token].totalDistributedTokens = _faucetList[token].totalDistributedTokens.add(referralTokenAmount);
// transfer tokens to referral
IERC20(token).safeTransfer(firstReferral, referralTokenAmount);
}
}
}
}
| * @param token Address of the token being distributed @param dailyRate Daily rate of tokens distributed @param referralRate The value earned by referral/ | function createFaucet(address token, uint256 dailyRate, uint256 referralRate) public onlyOwner {
require(!_faucetList[token].exists, "TokenFaucet: token faucet already exists");
require(token != address(0), "TokenFaucet: token is the zero address");
require(dailyRate > 0, "TokenFaucet: dailyRate is 0");
require(referralRate > 0, "TokenFaucet: referralRate is 0");
_faucetList[token].exists = true;
_faucetList[token].enabled = true;
_faucetList[token].dailyRate = dailyRate;
_faucetList[token].referralRate = referralRate;
emit FaucetCreated(token);
}
| 12,668,720 | [
1,
2316,
5267,
434,
326,
1147,
3832,
16859,
225,
18872,
4727,
463,
12857,
4993,
434,
2430,
16859,
225,
1278,
29084,
4727,
1021,
460,
425,
1303,
329,
635,
1278,
29084,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
752,
29634,
5286,
278,
12,
2867,
1147,
16,
2254,
5034,
18872,
4727,
16,
2254,
5034,
1278,
29084,
4727,
13,
1071,
1338,
5541,
288,
203,
3639,
2583,
12,
5,
67,
507,
5286,
278,
682,
63,
2316,
8009,
1808,
16,
315,
1345,
29634,
5286,
278,
30,
1147,
11087,
5286,
278,
1818,
1704,
8863,
203,
3639,
2583,
12,
2316,
480,
1758,
12,
20,
3631,
315,
1345,
29634,
5286,
278,
30,
1147,
353,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
26790,
4727,
405,
374,
16,
315,
1345,
29634,
5286,
278,
30,
18872,
4727,
353,
374,
8863,
203,
3639,
2583,
12,
1734,
29084,
4727,
405,
374,
16,
315,
1345,
29634,
5286,
278,
30,
1278,
29084,
4727,
353,
374,
8863,
203,
203,
3639,
389,
507,
5286,
278,
682,
63,
2316,
8009,
1808,
273,
638,
31,
203,
3639,
389,
507,
5286,
278,
682,
63,
2316,
8009,
5745,
273,
638,
31,
203,
3639,
389,
507,
5286,
278,
682,
63,
2316,
8009,
26790,
4727,
273,
18872,
4727,
31,
203,
3639,
389,
507,
5286,
278,
682,
63,
2316,
8009,
1734,
29084,
4727,
273,
1278,
29084,
4727,
31,
203,
203,
3639,
3626,
478,
69,
5286,
278,
6119,
12,
2316,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.4.15;
/* MultiSigWallet that can receive NFT */
contract MultiSigWalletWithNFT721Support {
/*
* Events
*/
event Confirmation(address indexed sender, uint256 indexed transactionId);
event Revocation(address indexed sender, uint256 indexed transactionId);
event Submission(uint256 indexed transactionId);
event Execution(uint256 indexed transactionId);
event ExecutionFailure(uint256 indexed transactionId);
event Deposit(address indexed sender, uint256 value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint256 required);
/*
* Constants
*/
uint256 public constant MAX_OWNER_COUNT = 50;
/*
* Storage
*/
mapping(uint256 => Transaction) public transactions;
mapping(uint256 => mapping(address => bool)) public confirmations;
mapping(address => bool) public isOwner;
address[] public owners;
uint256 public required;
uint256 public transactionCount;
struct Transaction {
address destination;
uint256 value;
bytes data;
bool executed;
}
/*
* Modifiers
*/
modifier onlyWallet() {
require(msg.sender == address(this));
_;
}
modifier ownerDoesNotExist(address owner) {
require(!isOwner[owner]);
_;
}
modifier ownerExists(address owner) {
require(isOwner[owner]);
_;
}
modifier transactionExists(uint256 transactionId) {
require(transactions[transactionId].destination != 0);
_;
}
modifier confirmed(uint256 transactionId, address owner) {
require(confirmations[transactionId][owner]);
_;
}
modifier notConfirmed(uint256 transactionId, address owner) {
require(!confirmations[transactionId][owner]);
_;
}
modifier notExecuted(uint256 transactionId) {
require(!transactions[transactionId].executed);
_;
}
modifier notNull(address _address) {
require(_address != 0);
_;
}
modifier validRequirement(uint256 ownerCount, uint256 _required) {
require(ownerCount <= MAX_OWNER_COUNT && _required <= ownerCount && _required != 0 && ownerCount != 0);
_;
}
function onERC721Received(
address,
address,
uint256,
bytes memory
) public returns (bytes4) {
bytes4 b = hex"150b7a02";
return b;
}
/// @dev Fallback function allows to deposit ether.
function() payable {
if (msg.value > 0) Deposit(msg.sender, msg.value);
}
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
function MultiSigWalletWithNFT721Support(address[] _owners, uint256 _required) public validRequirement(_owners.length, _required) {
for (uint256 i = 0; i < _owners.length; i++) {
require(!isOwner[_owners[i]] && _owners[i] != 0);
isOwner[_owners[i]] = true;
}
owners = _owners;
required = _required;
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param owner Address of new owner.
function addOwner(address owner)
public
onlyWallet
ownerDoesNotExist(owner)
notNull(owner)
validRequirement(owners.length + 1, required)
{
isOwner[owner] = true;
owners.push(owner);
OwnerAddition(owner);
}
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param owner Address of owner.
function removeOwner(address owner) public onlyWallet ownerExists(owner) {
isOwner[owner] = false;
for (uint256 i = 0; i < owners.length - 1; i++)
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1];
break;
}
owners.length -= 1;
if (required > owners.length) changeRequirement(owners.length);
OwnerRemoval(owner);
}
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param owner Address of owner to be replaced.
/// @param newOwner Address of new owner.
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint256 i = 0; i < owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
isOwner[newOwner] = true;
OwnerRemoval(owner);
OwnerAddition(newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
function changeRequirement(uint256 _required) public onlyWallet validRequirement(owners.length, _required) {
required = _required;
RequirementChange(_required);
}
/// @dev Allows an owner to submit and confirm a transaction.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function submitTransaction(
address destination,
uint256 value,
bytes data
) public returns (uint256 transactionId) {
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint256 transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param transactionId Transaction ID.
function revokeConfirmation(uint256 transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
Revocation(msg.sender, transactionId);
}
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint256 transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txn = transactions[transactionId];
txn.executed = true;
if (external_call(txn.destination, txn.value, txn.data.length, txn.data)) Execution(transactionId);
else {
ExecutionFailure(transactionId);
txn.executed = false;
}
}
}
// call has been separated into its own function in order to take advantage
// of the Solidity's code generator to produce a loop that copies tx.data into memory.
function external_call(
address destination,
uint256 value,
uint256 dataLength,
bytes data
) internal returns (bool) {
bool result;
assembly {
let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
result := call(
sub(gas, 34710), // 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) +
// callNewAccountGas (25000, in case the destination address does not exist and needs creating)
destination,
value,
d,
dataLength, // Size of the input (in bytes) - this is what fixes the padding problem
x,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return Confirmation status.
function isConfirmed(uint256 transactionId) public constant returns (bool) {
uint256 count = 0;
for (uint256 i = 0; i < owners.length; i++) {
if (confirmations[transactionId][owners[i]]) count += 1;
if (count == required) return true;
}
}
/*
* Internal functions
*/
/// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function addTransaction(
address destination,
uint256 value,
bytes data
) internal notNull(destination) returns (uint256 transactionId) {
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false
});
transactionCount += 1;
Submission(transactionId);
}
/*
* Web3 call functions
*/
/// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return Number of confirmations.
function getConfirmationCount(uint256 transactionId) public constant returns (uint256 count) {
for (uint256 i = 0; i < owners.length; i++) if (confirmations[transactionId][owners[i]]) count += 1;
}
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed) public constant returns (uint256 count) {
for (uint256 i = 0; i < transactionCount; i++)
if ((pending && !transactions[i].executed) || (executed && transactions[i].executed)) count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners() public constant returns (address[]) {
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param transactionId Transaction ID.
/// @return Returns array of owner addresses.
function getConfirmations(uint256 transactionId) public constant returns (address[] _confirmations) {
address[] memory confirmationsTemp = new address[](owners.length);
uint256 count = 0;
uint256 i;
for (i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i = 0; i < count; i++) _confirmations[i] = confirmationsTemp[i];
}
/// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Returns array of transaction IDs.
function getTransactionIds(
uint256 from,
uint256 to,
bool pending,
bool executed
) public constant returns (uint256[] _transactionIds) {
uint256[] memory transactionIdsTemp = new uint256[](transactionCount);
uint256 count = 0;
uint256 i;
for (i = 0; i < transactionCount; i++)
if ((pending && !transactions[i].executed) || (executed && transactions[i].executed)) {
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint256[](to - from);
for (i = from; i < to; i++) _transactionIds[i - from] = transactionIdsTemp[i];
}
}
| @dev Fallback function allows to deposit ether. | function() payable {
if (msg.value > 0) Deposit(msg.sender, msg.value);
}
| 2,052,512 | [
1,
12355,
445,
5360,
358,
443,
1724,
225,
2437,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1435,
8843,
429,
288,
203,
3639,
309,
261,
3576,
18,
1132,
405,
374,
13,
4019,
538,
305,
12,
3576,
18,
15330,
16,
1234,
18,
1132,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0xAb7a8E2B7D00ebA2186DA8aA04Ce288DeB27A081/sources/project:/contracts/source/tokens/ERC721/CryptopiaEarlyAccessShip/CryptopiaEarlyAccessShipToken.sol | @dev Failsafe mechanism Allows the owner to retrieve tokens from the contract that might have been send there by accident @param tokenContract The address of ERC20 compatible token | function retrieveTokens(address tokenContract)
public virtual override
{
require(tokenContract != token, "Use withdraw");
super.retrieveTokens(tokenContract);
}
| 11,596,339 | [
1,
3754,
4626,
12860,
25619,
326,
3410,
358,
4614,
2430,
628,
326,
6835,
716,
4825,
1240,
2118,
1366,
1915,
635,
25961,
225,
1147,
8924,
1021,
1758,
434,
4232,
39,
3462,
7318,
1147,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4614,
5157,
12,
2867,
1147,
8924,
13,
7010,
3639,
1071,
5024,
3849,
21281,
565,
288,
203,
3639,
2583,
12,
2316,
8924,
480,
1147,
16,
315,
3727,
598,
9446,
8863,
203,
3639,
2240,
18,
17466,
5157,
12,
2316,
8924,
1769,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x378a23c0FA0c6E4F9680ae93caC368B5111BfC6F/sources/project_/contracts/managementContract.sol | * @title HManagementContract @dev Shared smart contract responsible for: - access control - whitelisting and superwhitelisting - freezing of accounts The contract uses {Initializable}, {AccessControlUpgradeable} and {PausableUpgradeable} by OpenZeppelin Account that is passed to the initialize function will be granted admin, minter, pauser and whitelister roles. Whitelisted accounts are addresses which have passed KYC and don't have transfer delays through pending deposits. SuperWhitelisted account is a special account that belongs to Himalaya Group and allows non whitelisted users to instantly transfer funds even if the have any tokens locked in pending deposits./ | contract HManagementContract is Initializable, AccessControlUpgradeable, PausableUpgradeable {
bytes32 private constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 private constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 private constant WHITELIST_ROLE = keccak256("WHITELIST_ROLE");
mapping(address => bool) private whitelisted;
mapping(address => bool) private superWhiteListed;
mapping(address => bool) private frozen;
uint256 public nonWhitelistedDelay;
uint256 public nonWhitelistedDepositLimit;
address[] private tokenList;
event Whitelist(address addr);
event UnWhitelist(address addr);
event Freeze(address addr);
event UnFreeze(address addr);
event SuperWhitelist(address addr);
event UnSuperWhitelist(address addr);
pragma solidity 0.6.12;
function initialize(address admin) public virtual initializer {
require(admin != address(0), "Adming address cannot be null");
__Pausable_init_unchained();
__AccessControl_init_unchained();
_setupRole(DEFAULT_ADMIN_ROLE, admin);
_setupRole(MINTER_ROLE, admin);
_setupRole(PAUSER_ROLE, admin);
_setupRole(WHITELIST_ROLE, admin);
nonWhitelistedDelay = 366 days;
whitelisted[admin] = true;
}
modifier onlyAdmin virtual {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "must have ADMIN ROLE");
_;
}
modifier onlyWhitelister virtual {
require(hasRole(WHITELIST_ROLE, _msgSender()), "must have WHITELIST ROLE");
_;
}
function setNonWhitelistedDelay(uint256 _nonWhitelistedDelay) external virtual onlyAdmin {
nonWhitelistedDelay = _nonWhitelistedDelay;
}
function setNonWhitelistedDepositLimit(uint256 _nonWhitelistedDepositLimit) external virtual onlyAdmin {
nonWhitelistedDepositLimit = _nonWhitelistedDepositLimit;
}
function whitelist(address addr) external virtual onlyWhitelister {
whitelisted[addr] = true;
for (uint256 i = 0; i < tokenList.length; i++) {
IDeposits(tokenList[i]).removeAllPendingDepositsExternal(addr);
}
emit Whitelist(addr);
}
function whitelist(address addr) external virtual onlyWhitelister {
whitelisted[addr] = true;
for (uint256 i = 0; i < tokenList.length; i++) {
IDeposits(tokenList[i]).removeAllPendingDepositsExternal(addr);
}
emit Whitelist(addr);
}
function unWhitelist(address addr) external virtual onlyWhitelister whenNotPaused() {
whitelisted[addr] = false;
for (uint256 i = 0; i < tokenList.length; i++) {
IDeposits(tokenList[i]).putTotalBalanceToLock(addr);
}
emit UnWhitelist(addr);
}
function unWhitelist(address addr) external virtual onlyWhitelister whenNotPaused() {
whitelisted[addr] = false;
for (uint256 i = 0; i < tokenList.length; i++) {
IDeposits(tokenList[i]).putTotalBalanceToLock(addr);
}
emit UnWhitelist(addr);
}
function isWhitelisted(address addr) external virtual view returns (bool) {
return whitelisted[addr];
}
function freeze(address addr) external virtual onlyWhitelister {
frozen[addr] = true;
emit Freeze(addr);
}
function unFreeze(address addr) external virtual onlyWhitelister whenNotPaused() {
frozen[addr] = false;
emit UnFreeze(addr);
}
function isFrozen(address addr) external virtual view returns (bool) {
return frozen[addr];
}
function addSuperWhitelisted(address addr) external virtual onlyAdmin {
superWhiteListed[addr] = true;
emit SuperWhitelist(addr);
}
function removeSuperWhitelisted(address addr) external virtual onlyAdmin {
superWhiteListed[addr] = false;
emit UnSuperWhitelist(addr);
}
function isSuperWhitelisted(address addr) external virtual view returns (bool) {
return superWhiteListed[addr];
}
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "Must have pauser role to do global pause");
_pause();
}
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "Must have pauser role to do the global unpause");
_unpause();
}
function pauseToken(address token) public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "Must have pauser role to pause individual contract");
IPausable(token).pause();
}
function unpauseToken(address token) public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "Must have pauser role to pause individual contract");
IPausable(token).unpause();
}
function addToken(address tokenAddress) external virtual onlyAdmin {
for (uint256 i = 0; i < tokenList.length; i++) {
if (tokenList[i] == tokenAddress) {
return;
}
}
tokenList.push(tokenAddress);
}
function addToken(address tokenAddress) external virtual onlyAdmin {
for (uint256 i = 0; i < tokenList.length; i++) {
if (tokenList[i] == tokenAddress) {
return;
}
}
tokenList.push(tokenAddress);
}
function addToken(address tokenAddress) external virtual onlyAdmin {
for (uint256 i = 0; i < tokenList.length; i++) {
if (tokenList[i] == tokenAddress) {
return;
}
}
tokenList.push(tokenAddress);
}
function removeToken(address tokenAddress) external virtual onlyAdmin {
for (uint256 i = 0; i < tokenList.length; i++) {
if (tokenList[i] == tokenAddress) {
tokenList[i] = tokenList[tokenList.length - 1];
tokenList.pop();
break;
}
}
}
function removeToken(address tokenAddress) external virtual onlyAdmin {
for (uint256 i = 0; i < tokenList.length; i++) {
if (tokenList[i] == tokenAddress) {
tokenList[i] = tokenList[tokenList.length - 1];
tokenList.pop();
break;
}
}
}
function removeToken(address tokenAddress) external virtual onlyAdmin {
for (uint256 i = 0; i < tokenList.length; i++) {
if (tokenList[i] == tokenAddress) {
tokenList[i] = tokenList[tokenList.length - 1];
tokenList.pop();
break;
}
}
}
function getTokenList() external virtual view returns (address[] memory) {
return tokenList;
}
}
| 1,960,313 | [
1,
44,
10998,
8924,
225,
10314,
13706,
6835,
14549,
364,
30,
300,
2006,
3325,
300,
10734,
310,
471,
2240,
20409,
310,
300,
4843,
94,
310,
434,
9484,
1021,
6835,
4692,
288,
4435,
6934,
5779,
288,
16541,
10784,
429,
97,
471,
288,
16507,
16665,
10784,
429,
97,
635,
3502,
62,
881,
84,
292,
267,
6590,
716,
353,
2275,
358,
326,
4046,
445,
903,
506,
17578,
3981,
16,
1131,
387,
16,
6790,
1355,
471,
600,
305,
292,
1249,
4900,
18,
3497,
7523,
329,
9484,
854,
6138,
1492,
1240,
2275,
1475,
61,
39,
471,
2727,
1404,
1240,
7412,
4624,
87,
3059,
4634,
443,
917,
1282,
18,
14845,
18927,
329,
2236,
353,
279,
4582,
2236,
716,
11081,
358,
670,
2840,
528,
69,
3756,
471,
5360,
1661,
26944,
3677,
358,
5934,
715,
7412,
284,
19156,
5456,
309,
326,
1240,
1281,
2430,
8586,
316,
4634,
443,
917,
1282,
18,
19,
2,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0
] | [
1,
16351,
670,
10998,
8924,
353,
10188,
6934,
16,
24349,
10784,
429,
16,
21800,
16665,
10784,
429,
288,
203,
565,
1731,
1578,
3238,
5381,
6989,
2560,
67,
16256,
273,
417,
24410,
581,
5034,
2932,
6236,
2560,
67,
16256,
8863,
203,
203,
565,
1731,
1578,
3238,
5381,
15662,
4714,
67,
16256,
273,
417,
24410,
581,
5034,
2932,
4066,
4714,
67,
16256,
8863,
203,
203,
565,
1731,
1578,
3238,
5381,
24353,
7085,
67,
16256,
273,
417,
24410,
581,
5034,
2932,
16861,
7085,
67,
16256,
8863,
203,
203,
565,
2874,
12,
2867,
516,
1426,
13,
3238,
26944,
31,
203,
203,
565,
2874,
12,
2867,
516,
1426,
13,
3238,
2240,
13407,
682,
329,
31,
203,
203,
565,
2874,
12,
2867,
516,
1426,
13,
3238,
12810,
31,
203,
203,
565,
2254,
5034,
1071,
1661,
18927,
329,
6763,
31,
203,
203,
565,
2254,
5034,
1071,
1661,
18927,
329,
758,
1724,
3039,
31,
203,
203,
565,
1758,
8526,
3238,
1147,
682,
31,
203,
203,
565,
871,
3497,
7523,
12,
2867,
3091,
1769,
203,
203,
565,
871,
1351,
18927,
12,
2867,
3091,
1769,
203,
203,
565,
871,
15217,
8489,
12,
2867,
3091,
1769,
203,
203,
565,
871,
1351,
9194,
8489,
12,
2867,
3091,
1769,
203,
203,
565,
871,
14845,
18927,
12,
2867,
3091,
1769,
203,
203,
565,
871,
1351,
8051,
18927,
12,
2867,
3091,
1769,
203,
203,
683,
9454,
18035,
560,
374,
18,
26,
18,
2138,
31,
203,
565,
445,
4046,
12,
2867,
3981,
13,
1071,
5024,
12562,
288,
203,
3639,
2583,
12,
3666,
480,
1758,
12,
20,
3631,
315,
1871,
11987,
1758,
2
] |
pragma solidity 0.4.15;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Controlled {
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController { require(msg.sender == controller); _; }
address public controller;
function Controlled() public { controller = msg.sender;}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) public onlyController {
controller = _newController;
}
}
/*
Copyright 2016, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title MiniMeToken Contract
/// @author Jordi Baylina
/// @dev This token contract's goal is to make it easy for anyone to clone this
/// token using the token distribution at a given block, this will allow DAO's
/// and DApps to upgrade their features in a decentralized manner without
/// affecting the original token
/// @dev It is ERC20 compliant, but still needs to under go further testing.
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public;
}
/// @dev The actual token contract, the default controller is the msg.sender
/// that deploys the contract, so usually this token will be deployed by a
/// token controller contract, which Giveth will call a "Campaign"
contract MiniMeToken is Controlled {
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = 'MMT_0.2'; //An arbitrary versioning scheme
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
MiniMeToken public parentToken;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
// The factory used to create new clone tokens
MiniMeTokenFactory public tokenFactory;
////////////////
// Constructor
////////////////
/// @notice Constructor to create a MiniMeToken
/// @param _tokenFactory The address of the MiniMeTokenFactory contract that
/// will create the Clone token contracts, the token factory needs to be
/// deployed first
/// @param _parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param _parentSnapShotBlock Block of the parent token that will
/// determine the initial distribution of the clone token, set to 0 if it
/// is a new token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
function MiniMeToken(
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public {
tokenFactory = MiniMeTokenFactory(_tokenFactory);
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
return doTransfer(msg.sender, _to, _amount);
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount
) public returns (bool success) {
// The controller of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// controller of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != controller) {
require(transfersEnabled);
// The standard ERC 20 transferFrom functionality
if (allowed[_from][msg.sender] < _amount) return false;
allowed[_from][msg.sender] -= _amount;
}
return doTransfer(_from, _to, _amount);
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount
) internal returns(bool) {
if (_amount == 0) {
return true;
}
require(parentSnapShotBlock < block.number);
// Do not allow transfer to 0x0 or the token contract itself
require((_to != 0) && (_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer returns false
var previousBalanceFrom = balanceOfAt(_from, block.number);
if (previousBalanceFrom < _amount) {
return false;
}
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
var previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
// An event to make the transfer easy to find on the blockchain
Transfer(_from, _to, _amount);
return true;
}
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender
) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(address _spender, uint256 _amount, bytes _extraData
) public returns (bool success) {
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() public constant returns (uint) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint _blockNumber) public constant
returns (uint) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0)
|| (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0)
|| (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Clone Token Method
////////////////
/// @notice Creates a new clone token with the initial distribution being
/// this token at `_snapshotBlock`
/// @param _cloneTokenName Name of the clone token
/// @param _cloneDecimalUnits Number of decimals of the smallest unit
/// @param _cloneTokenSymbol Symbol of the clone token
/// @param _snapshotBlock Block when the distribution of the parent token is
/// copied to set the initial distribution of the new clone token;
/// if the block is zero than the actual block, the current block is used
/// @param _transfersEnabled True if transfers are allowed in the clone
/// @return The address of the new MiniMeToken Contract
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) public returns(address) {
if (_snapshotBlock == 0) _snapshotBlock = block.number;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
_snapshotBlock,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
NewCloneToken(address(cloneToken), _snapshotBlock);
return address(cloneToken);
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount
) public onlyController returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
Transfer(0, _owner, _amount);
return true;
}
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint _amount
) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
Transfer(_owner, 0, _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) public onlyController {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint _block
) constant internal returns (uint) {
if (checkpoints.length == 0) return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
) internal {
if ((checkpoints.length == 0)
|| (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/// @dev Helper function to return a min betwen the two uints
/// PURE function
function min(uint a, uint b) internal constant returns (uint) {
return a < b ? a : b;
}
/// @notice The fallback function: If the contract's controller has not been
/// set to 0, then the `proxyPayment` method is called which relays the
/// ether and creates tokens as described in the token controller contract
function () public payable {
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public onlyController {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
////////////////
// MiniMeTokenFactory
////////////////
/// @dev This contract is used to generate clone contracts from a contract.
/// In solidity this is the way to create a contract from a contract of the
/// same class
contract MiniMeTokenFactory {
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the controller of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken) {
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
contract StakeTreeWithTokenization {
using SafeMath for uint256;
uint public version = 2;
struct Funder {
bool exists;
uint balance;
uint withdrawalEntry;
uint contribution;
uint contributionClaimed;
}
mapping(address => Funder) public funders;
bool public live = true; // For sunsetting contract
uint public totalCurrentFunders = 0; // Keeps track of total funders
uint public withdrawalCounter = 0; // Keeps track of how many withdrawals have taken place
uint public sunsetWithdrawDate;
MiniMeToken public tokenContract;
MiniMeTokenFactory public tokenFactory;
bool public tokenized = false;
bool public canClaimTokens = false;
address public beneficiary; // Address for beneficiary
uint public sunsetWithdrawalPeriod; // How long it takes for beneficiary to swipe contract when put into sunset mode
uint public withdrawalPeriod; // How long the beneficiary has to wait withdraw
uint public minimumFundingAmount; // Setting used for setting minimum amounts to fund contract with
uint public lastWithdrawal; // Last withdrawal time
uint public nextWithdrawal; // Next withdrawal time
uint public contractStartTime; // For accounting purposes
event Payment(address indexed funder, uint amount);
event Refund(address indexed funder, uint amount);
event Withdrawal(uint amount);
event TokensClaimed(address indexed funder, uint amount);
event Sunset(bool hasSunset);
function StakeTreeWithTokenization(
address beneficiaryAddress,
uint withdrawalPeriodInit,
uint withdrawalStart,
uint sunsetWithdrawPeriodInit,
uint minimumFundingAmountInit) {
beneficiary = beneficiaryAddress;
withdrawalPeriod = withdrawalPeriodInit;
sunsetWithdrawalPeriod = sunsetWithdrawPeriodInit;
lastWithdrawal = withdrawalStart;
nextWithdrawal = lastWithdrawal + withdrawalPeriod;
minimumFundingAmount = minimumFundingAmountInit;
contractStartTime = now;
}
// Modifiers
modifier onlyByBeneficiary() {
require(msg.sender == beneficiary);
_;
}
modifier onlyWhenTokenized() {
require(isTokenized());
_;
}
modifier onlyByFunder() {
require(isFunder(msg.sender));
_;
}
modifier onlyAfterNextWithdrawalDate() {
require(now >= nextWithdrawal);
_;
}
modifier onlyWhenLive() {
require(live);
_;
}
modifier onlyWhenSunset() {
require(!live);
_;
}
/*
* External accounts can pay directly to contract to fund it.
*/
function () payable {
fund();
}
/*
* Additional api for contracts to use as well
* Can only happen when live and over a minimum amount set by the beneficiary
*/
function fund() public payable onlyWhenLive {
require(msg.value >= minimumFundingAmount);
// Only increase total funders when we have a new funder
if(!isFunder(msg.sender)) {
totalCurrentFunders = totalCurrentFunders.add(1); // Increase total funder count
funders[msg.sender] = Funder({
exists: true,
balance: msg.value,
withdrawalEntry: withdrawalCounter, // Set the withdrawal counter. Ie at which withdrawal the funder "entered" the patronage contract
contribution: 0,
contributionClaimed: 0
});
}
else {
consolidateFunder(msg.sender, msg.value);
}
Payment(msg.sender, msg.value);
}
// Pure functions
/*
* This function calculates how much the beneficiary can withdraw.
* Due to no floating points in Solidity, we will lose some fidelity
* if there's wei on the last digit. The beneficiary loses a neglibible amount
* to withdraw but this benefits the beneficiary again on later withdrawals.
* We multiply by 10 (which corresponds to the 10%)
* then divide by 100 to get the actual part.
*/
function calculateWithdrawalAmount(uint startAmount) public returns (uint){
return startAmount.mul(10).div(100); // 10%
}
/*
* This function calculates the refund amount for the funder.
* Due to no floating points in Solidity, we will lose some fidelity.
* The funder loses a neglibible amount to refund.
* The left over wei gets pooled to the fund.
*/
function calculateRefundAmount(uint amount, uint withdrawalTimes) public returns (uint) {
for(uint i=0; i<withdrawalTimes; i++){
amount = amount.mul(9).div(10);
}
return amount;
}
// Getter functions
/*
* To calculate the refund amount we look at how many times the beneficiary
* has withdrawn since the funder added their funds.
* We use that deduct 10% for each withdrawal.
*/
function getRefundAmountForFunder(address addr) public constant returns (uint) {
// Only calculate on-the-fly if funder has not been updated
if(shouldUpdateFunder(addr)) {
uint amount = funders[addr].balance;
uint withdrawalTimes = getHowManyWithdrawalsForFunder(addr);
return calculateRefundAmount(amount, withdrawalTimes);
}
else {
return funders[addr].balance;
}
}
function getFunderContribution(address funder) public constant returns (uint) {
// Only calculate on-the-fly if funder has not been updated
if(shouldUpdateFunder(funder)) {
uint oldBalance = funders[funder].balance;
uint newBalance = getRefundAmountForFunder(funder);
uint contribution = oldBalance.sub(newBalance);
return funders[funder].contribution.add(contribution);
}
else {
return funders[funder].contribution;
}
}
function getBeneficiary() public constant returns (address) {
return beneficiary;
}
function getCurrentTotalFunders() public constant returns (uint) {
return totalCurrentFunders;
}
function getWithdrawalCounter() public constant returns (uint) {
return withdrawalCounter;
}
function getWithdrawalEntryForFunder(address addr) public constant returns (uint) {
return funders[addr].withdrawalEntry;
}
function getContractBalance() public constant returns (uint256 balance) {
balance = this.balance;
}
function getFunderBalance(address funder) public constant returns (uint256) {
return getRefundAmountForFunder(funder);
}
function getFunderContributionClaimed(address addr) public constant returns (uint) {
return funders[addr].contributionClaimed;
}
function isFunder(address addr) public constant returns (bool) {
return funders[addr].exists;
}
function isTokenized() public constant returns (bool) {
return tokenized;
}
function shouldUpdateFunder(address funder) public constant returns (bool) {
return getWithdrawalEntryForFunder(funder) < withdrawalCounter;
}
function getHowManyWithdrawalsForFunder(address addr) private constant returns (uint) {
return withdrawalCounter.sub(getWithdrawalEntryForFunder(addr));
}
// State changing functions
function setMinimumFundingAmount(uint amount) external onlyByBeneficiary {
require(amount > 0);
minimumFundingAmount = amount;
}
function withdraw() external onlyByBeneficiary onlyAfterNextWithdrawalDate onlyWhenLive {
// Check
uint amount = calculateWithdrawalAmount(this.balance);
// Effects
withdrawalCounter = withdrawalCounter.add(1);
lastWithdrawal = now; // For tracking purposes
nextWithdrawal = nextWithdrawal + withdrawalPeriod; // Fixed period increase
// Interaction
beneficiary.transfer(amount);
Withdrawal(amount);
}
// Refunding by funder
// Only funders can refund their own funding
// Can only be sent back to the same address it was funded with
// We also remove the funder if they succesfully exit with their funds
function refund() external onlyByFunder {
// Check
uint walletBalance = this.balance;
uint amount = getRefundAmountForFunder(msg.sender);
require(amount > 0);
// Effects
removeFunder();
// Interaction
msg.sender.transfer(amount);
Refund(msg.sender, amount);
// Make sure this worked as intended
assert(this.balance == walletBalance-amount);
}
// Used when the funder wants to remove themselves as a funder
// without refunding. Their eth stays in the pool
function removeFunder() public onlyByFunder {
delete funders[msg.sender];
totalCurrentFunders = totalCurrentFunders.sub(1);
}
/*
* This is a bookkeeping function which updates the state for the funder
* when top up their funds.
*/
function consolidateFunder(address funder, uint newPayment) private {
// Update contribution
funders[funder].contribution = getFunderContribution(funder);
// Update balance
funders[funder].balance = getRefundAmountForFunder(funder).add(newPayment);
// Update withdrawal entry
funders[funder].withdrawalEntry = withdrawalCounter;
}
function addTokenization(string tokenName, string tokenSymbol, uint8 tokenDecimals ) external onlyByBeneficiary {
require(!isTokenized());
tokenFactory = new MiniMeTokenFactory();
tokenContract = tokenFactory.createCloneToken(0x0, 0, tokenName, tokenDecimals, tokenSymbol, true);
tokenized = true;
canClaimTokens = true;
}
function claimTokens() external onlyByFunder onlyWhenTokenized {
require(canClaimTokens);
uint contributionAmount = getFunderContribution(msg.sender);
uint contributionClaimedAmount = getFunderContributionClaimed(msg.sender);
// Only claim tokens if they have some left to claim
uint claimAmount = contributionAmount.sub(contributionClaimedAmount);
require(claimAmount > 0);
// Claim tokens
funders[msg.sender].contributionClaimed = contributionAmount;
tokenContract.generateTokens(msg.sender, claimAmount);
TokensClaimed(msg.sender, claimAmount);
}
/*
* The beneficiary can stop/enable funders from claiming more tokens.
* This opens up opportunities for tokenizing only happening for a set periods.
*/
function enableTokenClaiming(bool _enabled) external onlyWhenTokenized onlyByBeneficiary {
canClaimTokens = _enabled;
}
/* --- Sunsetting --- */
/*
* The beneficiary can decide to stop using this contract.
* They use this sunset function to put it into sunset mode.
* The beneficiary can then swipe rest of the funds after a set time
* if funders have not withdrawn their funds.
*/
function sunset() external onlyByBeneficiary onlyWhenLive {
sunsetWithdrawDate = now.add(sunsetWithdrawalPeriod);
live = false;
Sunset(true);
}
function swipe(address recipient) external onlyWhenSunset onlyByBeneficiary {
require(now >= sunsetWithdrawDate);
recipient.transfer(this.balance);
}
/* --- Token Contract Forwarding Controller Functions --- */
/*
* Allows beneficiary to call two additional functions on the token contract:
* claimTokens
* enabledTransfers
*
*/
function tokenContractClaimTokens(address _token) onlyByBeneficiary onlyWhenTokenized {
tokenContract.claimTokens(_token);
}
function tokenContractEnableTransfers(bool _transfersEnabled) onlyByBeneficiary onlyWhenTokenized {
tokenContract.enableTransfers(_transfersEnabled);
}
} | Refunding by funder Only funders can refund their own funding Can only be sent back to the same address it was funded with We also remove the funder if they succesfully exit with their funds Check Effects Interaction Make sure this worked as intended | function refund() external onlyByFunder {
uint walletBalance = this.balance;
uint amount = getRefundAmountForFunder(msg.sender);
require(amount > 0);
removeFunder();
msg.sender.transfer(amount);
Refund(msg.sender, amount);
assert(this.balance == walletBalance-amount);
}
| 7,211,577 | [
1,
1957,
14351,
635,
284,
9341,
5098,
284,
26843,
848,
16255,
3675,
4953,
22058,
4480,
1338,
506,
3271,
1473,
358,
326,
1967,
1758,
518,
1703,
9831,
785,
598,
1660,
2546,
1206,
326,
284,
9341,
309,
2898,
8667,
764,
4095,
2427,
598,
3675,
284,
19156,
2073,
30755,
87,
5294,
1128,
4344,
3071,
333,
28613,
487,
12613,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
16255,
1435,
3903,
1338,
858,
42,
9341,
288,
203,
565,
2254,
9230,
13937,
273,
333,
18,
12296,
31,
203,
565,
2254,
3844,
273,
17404,
1074,
6275,
1290,
42,
9341,
12,
3576,
18,
15330,
1769,
203,
565,
2583,
12,
8949,
405,
374,
1769,
203,
203,
565,
1206,
42,
9341,
5621,
203,
203,
565,
1234,
18,
15330,
18,
13866,
12,
8949,
1769,
203,
203,
565,
3941,
1074,
12,
3576,
18,
15330,
16,
3844,
1769,
203,
203,
565,
1815,
12,
2211,
18,
12296,
422,
9230,
13937,
17,
8949,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x23a0e57620c875Cb3F1EdDcb7f8FAfBF2A466D83/sources/TWOBASED.sol | * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. This is internal function is equivalent to `approve`, and can be used to e.g. set automatic allowances for certain subsystems, etc. Emits an {Approval} event. Requirements: - `owner` cannot be the zero address. - `spender` cannot be the zero address./ | function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "zero address");
require(spender != address(0), "zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| 3,927,355 | [
1,
2785,
1375,
8949,
68,
487,
326,
1699,
1359,
434,
1375,
87,
1302,
264,
68,
1879,
326,
1375,
8443,
68,
87,
2430,
18,
1220,
353,
2713,
445,
353,
7680,
358,
1375,
12908,
537,
9191,
471,
848,
506,
1399,
358,
425,
18,
75,
18,
444,
5859,
1699,
6872,
364,
8626,
15359,
87,
16,
5527,
18,
7377,
1282,
392,
288,
23461,
97,
871,
18,
29076,
30,
300,
1375,
8443,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
87,
1302,
264,
68,
2780,
506,
326,
3634,
1758,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
12908,
537,
12,
2867,
3410,
16,
1758,
17571,
264,
16,
2254,
5034,
3844,
13,
2713,
5024,
288,
203,
3639,
2583,
12,
8443,
480,
1758,
12,
20,
3631,
315,
7124,
1758,
8863,
203,
3639,
2583,
12,
87,
1302,
264,
480,
1758,
12,
20,
3631,
315,
7124,
1758,
8863,
203,
203,
3639,
389,
5965,
6872,
63,
8443,
6362,
87,
1302,
264,
65,
273,
3844,
31,
203,
3639,
3626,
1716,
685,
1125,
12,
8443,
16,
17571,
264,
16,
3844,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/97/0xA13D1D1faD4d0Fa1dD2981E3632bcC7bDF17D160/sources/CORLToken.sol | * Returns balance of token/ | function balanceOf(address user) public view returns(uint256){
return _balanceOf[user];
}
An address can grant other addresses the right to spend a certain amount of tokens.
In relational database architecture, this relationship is called one-to-many: an owner can grant multiple
spenders to spend some tokens on his behalf.
| 11,407,577 | [
1,
1356,
11013,
434,
1147,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
11013,
951,
12,
2867,
729,
13,
1071,
1476,
1135,
12,
11890,
5034,
15329,
203,
3639,
327,
389,
12296,
951,
63,
1355,
15533,
203,
565,
289,
203,
203,
377,
1922,
1758,
848,
7936,
1308,
6138,
326,
2145,
358,
17571,
279,
8626,
3844,
434,
2430,
18,
203,
377,
657,
25302,
2063,
27418,
16,
333,
5232,
353,
2566,
1245,
17,
869,
17,
9353,
30,
392,
3410,
848,
7936,
3229,
7010,
377,
17571,
414,
358,
17571,
2690,
2430,
603,
18423,
12433,
6186,
18,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
ERC20BaseRewardModule
https://github.com/gysr-io/core
SPDX-License-Identifier: MIT
*/
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/IRewardModule.sol";
/**
* @title ERC20 base reward module
*
* @notice this abstract class implements common ERC20 funding and unlocking
* logic, which is inherited by other reward modules.
*/
abstract contract ERC20BaseRewardModule is IRewardModule {
using SafeERC20 for IERC20;
// single funding/reward schedule
struct Funding {
uint256 amount;
uint256 shares;
uint256 locked;
uint256 updated;
uint256 start;
uint256 duration;
}
// constants
uint256 public constant INITIAL_SHARES_PER_TOKEN = 10**6;
uint256 public constant MAX_ACTIVE_FUNDINGS = 16;
// funding/reward state fields
mapping(address => Funding[]) private _fundings;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _locked;
/**
* @notice getter for total token shares
*/
function totalShares(address token) public view returns (uint256) {
return _shares[token];
}
/**
* @notice getter for total locked token shares
*/
function lockedShares(address token) public view returns (uint256) {
return _locked[token];
}
/**
* @notice getter for funding schedule struct
*/
function fundings(address token, uint256 index)
public
view
returns (
uint256 amount,
uint256 shares,
uint256 locked,
uint256 updated,
uint256 start,
uint256 duration
)
{
Funding storage f = _fundings[token][index];
return (f.amount, f.shares, f.locked, f.updated, f.start, f.duration);
}
/**
* @param token contract address of reward token
* @return number of active funding schedules
*/
function fundingCount(address token) public view returns (uint256) {
return _fundings[token].length;
}
/**
* @notice compute number of unlockable shares for a specific funding schedule
* @param token contract address of reward token
* @param idx index of the funding
* @return the number of unlockable shares
*/
function unlockable(address token, uint256 idx)
public
view
returns (uint256)
{
Funding storage funding = _fundings[token][idx];
// funding schedule is in future
if (block.timestamp < funding.start) {
return 0;
}
// empty
if (funding.locked == 0) {
return 0;
}
// handle zero-duration period or leftover dust from integer division
if (block.timestamp >= funding.start + funding.duration) {
return funding.locked;
}
return
((block.timestamp - funding.updated) * funding.shares) /
funding.duration;
}
/**
* @notice fund pool by locking up reward tokens for future distribution
* @param token contract address of reward token
* @param amount number of reward tokens to lock up as funding
* @param duration period (seconds) over which funding will be unlocked
* @param start time (seconds) at which funding begins to unlock
*/
function _fund(
address token,
uint256 amount,
uint256 duration,
uint256 start
) internal {
requireController();
// validate
require(amount > 0, "rm1");
require(start >= block.timestamp, "rm2");
require(_fundings[token].length < MAX_ACTIVE_FUNDINGS, "rm3");
IERC20 rewardToken = IERC20(token);
// do transfer of funding
uint256 total = rewardToken.balanceOf(address(this));
rewardToken.safeTransferFrom(msg.sender, address(this), amount);
uint256 actual = rewardToken.balanceOf(address(this)) - total;
// mint shares at current rate
uint256 minted =
(total > 0)
? (_shares[token] * actual) / total
: actual * INITIAL_SHARES_PER_TOKEN;
_locked[token] += minted;
_shares[token] += minted;
// create new funding
_fundings[token].push(
Funding({
amount: amount,
shares: minted,
locked: minted,
updated: start,
start: start,
duration: duration
})
);
emit RewardsFunded(token, amount, minted, start);
}
/**
* @dev internal function to clean up stale funding schedules
* @param token contract address of reward token to clean up
*/
function _clean(address token) internal {
// check for stale funding schedules to expire
uint256 removed = 0;
uint256 originalSize = _fundings[token].length;
for (uint256 i = 0; i < originalSize; i++) {
Funding storage funding = _fundings[token][i - removed];
uint256 idx = i - removed;
if (
unlockable(token, idx) == 0 &&
block.timestamp >= funding.start + funding.duration
) {
emit RewardsExpired(
token,
funding.amount,
funding.shares,
funding.start
);
// remove at idx by copying last element here, then popping off last
// (we don't care about order)
_fundings[token][idx] = _fundings[token][
_fundings[token].length - 1
];
_fundings[token].pop();
removed++;
}
}
}
/**
* @dev unlocks reward tokens based on funding schedules
* @param token contract addres of reward token
* @return shares number of shares unlocked
*/
function _unlockTokens(address token) internal returns (uint256 shares) {
// get unlockable shares for each funding schedule
for (uint256 i = 0; i < _fundings[token].length; i++) {
uint256 s = unlockable(token, i);
Funding storage funding = _fundings[token][i];
if (s > 0) {
funding.locked -= s;
funding.updated = block.timestamp;
shares += s;
}
}
// do unlocking
if (shares > 0) {
_locked[token] -= shares;
emit RewardsUnlocked(token, shares);
}
}
/**
* @dev distribute reward tokens to user
* @param user address of user receiving rweard
* @param token contract address of reward token
* @param shares number of shares to be distributed
* @return amount number of reward tokens distributed
*/
function _distribute(
address user,
address token,
uint256 shares
) internal returns (uint256 amount) {
// compute reward amount in tokens
IERC20 rewardToken = IERC20(token);
amount =
(rewardToken.balanceOf(address(this)) * shares) /
_shares[token];
// update overall reward shares
_shares[token] -= shares;
// do reward
rewardToken.safeTransfer(user, amount);
emit RewardsDistributed(user, token, amount, shares);
}
}
/*
ERC20FriendlyRewardModule
https://github.com/gysr-io/core
SPDX-License-Identifier: MIT
*/
pragma solidity 0.8.4;
import "./interfaces/IRewardModule.sol";
import "./interfaces/IEvents.sol";
import "./ERC20BaseRewardModule.sol";
import "./GysrUtils.sol";
/**
* @title ERC20 friendly reward module
*
* @notice this reward module distributes a single ERC20 token as the staking reward.
* It is designed to offer simple and predictable reward mechanics.
*
* @dev rewards are immutable once earned, and can be claimed by the user at
* any time. The module can be configured with a linear vesting schedule to
* incentivize longer term staking. The user can spend GYSR at the time of
* staking to receive a multiplier on their earning rate.
*/
contract ERC20FriendlyRewardModule is ERC20BaseRewardModule {
using GysrUtils for uint256;
// constants
uint256 public constant FULL_VESTING = 10**DECIMALS;
// single stake by user
struct Stake {
uint256 shares;
uint256 gysr;
uint256 bonus;
uint256 rewardTally;
uint256 timestamp;
}
// mapping of user to all of their stakes
mapping(address => Stake[]) public stakes;
// total shares without GYSR multiplier applied
uint256 public totalRawStakingShares;
// total shares with GYSR multiplier applied
uint256 public totalStakingShares;
// counter representing the current rate of rewards per share
uint256 public rewardsPerStakedShare;
// value to keep track of earnings to be put back into the pool
uint256 public rewardDust;
// timestamp of last update
uint256 public lastUpdated;
// minimum ratio of earned rewards measured against FULL_VESTING (i.e. 2.5 * 10^17 would be 25%)
uint256 public immutable vestingStart;
// length of time in seconds until the user receives a FULL_VESTING (1x) multiplier on rewards
uint256 public immutable vestingPeriod;
IERC20 private immutable _token;
address private immutable _factory;
/**
* @param token_ the token that will be rewarded
* @param vestingStart_ minimum ratio earned
* @param vestingPeriod_ period (in seconds) over which investors vest to 100%
* @param factory_ address of module factory
*/
constructor(
address token_,
uint256 vestingStart_,
uint256 vestingPeriod_,
address factory_
) {
require(vestingStart_ <= FULL_VESTING, "frm1");
_token = IERC20(token_);
_factory = factory_;
vestingStart = vestingStart_;
vestingPeriod = vestingPeriod_;
lastUpdated = block.timestamp;
}
/**
* @inheritdoc IRewardModule
*/
function tokens()
external
view
override
returns (address[] memory tokens_)
{
tokens_ = new address[](1);
tokens_[0] = address(_token);
}
/**
* @inheritdoc IRewardModule
*/
function factory() external view override returns (address) {
return _factory;
}
/**
* @inheritdoc IRewardModule
*/
function balances()
external
view
override
returns (uint256[] memory balances_)
{
balances_ = new uint256[](1);
balances_[0] = totalLocked();
}
/**
* @inheritdoc IRewardModule
*/
function usage() external view override returns (uint256) {
return _usage();
}
/**
* @inheritdoc IRewardModule
*/
function stake(
address account,
address user,
uint256 shares,
bytes calldata data
) external override onlyOwner returns (uint256, uint256) {
_update();
return _stake(account, user, shares, data);
}
/**
* @notice internal implementation of stake method
* @param account address of staking account
* @param user address of user
* @param shares number of new shares minted
* @param data addtional data
* @return amount of gysr spent
* @return amount of gysr vested
*/
function _stake(
address account,
address user,
uint256 shares,
bytes calldata data
) internal returns (uint256, uint256) {
require(data.length == 0 || data.length == 32, "frm2");
uint256 gysr;
if (data.length == 32) {
assembly {
gysr := calldataload(164)
}
}
uint256 bonus =
gysr.gysrBonus(shares, totalRawStakingShares + shares, _usage());
if (gysr > 0) {
emit GysrSpent(user, gysr);
}
// update user staking info
stakes[account].push(
Stake(shares, gysr, bonus, rewardsPerStakedShare, block.timestamp)
);
// add new shares to global totals
totalRawStakingShares += shares;
totalStakingShares += (shares * bonus) / 10**DECIMALS;
return (gysr, 0);
}
/**
* @inheritdoc IRewardModule
*/
function unstake(
address account,
address user,
uint256 shares,
bytes calldata
) external override onlyOwner returns (uint256, uint256) {
_update();
return _unstake(account, user, shares);
}
/**
* @notice internal implementation of unstake
* @param account address of staking account
* @param user address of user
* @param shares number of shares burned
* @return amount of gysr spent
* @return amount of gysr vested
*/
function _unstake(
address account,
address user,
uint256 shares
) internal returns (uint256, uint256) {
// redeem first-in-last-out
uint256 sharesLeftToBurn = shares;
Stake[] storage userStakes = stakes[account];
uint256 rewardAmount;
uint256 gysrVested;
uint256 preVestingRewards;
uint256 timeVestingCoeff;
while (sharesLeftToBurn > 0) {
Stake storage lastStake = userStakes[userStakes.length - 1];
require(lastStake.timestamp < block.timestamp, "frm3");
if (lastStake.shares <= sharesLeftToBurn) {
// fully redeem a past stake
preVestingRewards = _rewardForStakedShares(
lastStake.shares,
lastStake.bonus,
lastStake.rewardTally
);
timeVestingCoeff = timeVestingCoefficient(lastStake.timestamp);
rewardAmount +=
(preVestingRewards * timeVestingCoeff) /
10**DECIMALS;
rewardDust +=
(preVestingRewards * (FULL_VESTING - timeVestingCoeff)) /
10**DECIMALS;
totalStakingShares -=
(lastStake.shares * lastStake.bonus) /
10**DECIMALS;
sharesLeftToBurn -= lastStake.shares;
gysrVested += lastStake.gysr;
userStakes.pop();
} else {
// partially redeem a past stake
preVestingRewards = _rewardForStakedShares(
sharesLeftToBurn,
lastStake.bonus,
lastStake.rewardTally
);
timeVestingCoeff = timeVestingCoefficient(lastStake.timestamp);
rewardAmount +=
(preVestingRewards * timeVestingCoeff) /
10**DECIMALS;
rewardDust +=
(preVestingRewards * (FULL_VESTING - timeVestingCoeff)) /
10**DECIMALS;
totalStakingShares -=
(sharesLeftToBurn * lastStake.bonus) /
10**DECIMALS;
uint256 partialVested =
(sharesLeftToBurn * lastStake.gysr) / lastStake.shares;
gysrVested += partialVested;
lastStake.shares -= sharesLeftToBurn;
lastStake.gysr -= partialVested;
sharesLeftToBurn = 0;
}
}
// update global totals
totalRawStakingShares -= shares;
if (rewardAmount > 0) {
_distribute(user, address(_token), rewardAmount);
}
if (gysrVested > 0) {
emit GysrVested(user, gysrVested);
}
return (0, gysrVested);
}
/**
* @inheritdoc IRewardModule
*/
function claim(
address account,
address user,
uint256 shares,
bytes calldata data
) external override onlyOwner returns (uint256 spent, uint256 vested) {
_update();
(, vested) = _unstake(account, user, shares);
(spent, ) = _stake(account, user, shares, data);
}
/**
* @dev compute rewards owed for a specific stake
* @param shares number of shares to calculate rewards for
* @param bonus associated bonus for this stake
* @param rewardTally associated rewardTally for this stake
* @return reward for these staked shares
*/
function _rewardForStakedShares(
uint256 shares,
uint256 bonus,
uint256 rewardTally
) internal view returns (uint256) {
return
((((rewardsPerStakedShare - rewardTally) * shares) / 10**DECIMALS) * // counteract rewardsPerStakedShare coefficient
bonus) / 10**DECIMALS; // counteract bonus coefficient
}
/**
* @notice compute vesting multiplier as function of staking time
* @param time epoch time at which the tokens were staked
* @return vesting multiplier rewards
*/
function timeVestingCoefficient(uint256 time)
public
view
returns (uint256)
{
if (vestingPeriod == 0) return FULL_VESTING;
uint256 stakeTime = block.timestamp - time;
if (stakeTime > vestingPeriod) return FULL_VESTING;
return
vestingStart +
(stakeTime * (FULL_VESTING - vestingStart)) /
vestingPeriod;
}
/**
* @inheritdoc IRewardModule
*/
function update(address) external override {
requireOwner();
_update();
}
/**
* @notice method called ad hoc to clean up and perform additional accounting
* @dev will only be called manually, and should not contain any essential logic
*/
function clean() external override {
requireOwner();
_update();
_clean(address(_token));
}
/**
* @notice fund Geyser by locking up reward tokens for distribution
* @param amount number of reward tokens to lock up as funding
* @param duration period (seconds) over which funding will be unlocked
*/
function fund(uint256 amount, uint256 duration) external {
_update();
_fund(address(_token), amount, duration, block.timestamp);
}
/**
* @notice fund Geyser by locking up reward tokens for distribution
* @param amount number of reward tokens to lock up as funding
* @param duration period (seconds) over which funding will be unlocked
* @param start time (seconds) at which funding begins to unlock
*/
function fund(
uint256 amount,
uint256 duration,
uint256 start
) external {
_update();
_fund(address(_token), amount, duration, start);
}
/**
* @dev updates the internal accounting for rewards per staked share
* retrieves unlocked tokens and adds on any unvested rewards from the last unstake operation
*/
function _update() private {
lastUpdated = block.timestamp;
if (totalStakingShares == 0) {
rewardsPerStakedShare = 0;
return;
}
uint256 rewardsToUnlock = _unlockTokens(address(_token)) + rewardDust;
rewardDust = 0;
// global accounting
rewardsPerStakedShare +=
(rewardsToUnlock * 10**DECIMALS) /
totalStakingShares;
}
/**
* @return total number of locked reward tokens
*/
function totalLocked() public view returns (uint256) {
if (lockedShares(address(_token)) == 0) {
return 0;
}
return
(_token.balanceOf(address(this)) * lockedShares(address(_token))) /
totalShares(address(_token));
}
/**
* @return total number of unlocked reward tokens
*/
function totalUnlocked() public view returns (uint256) {
uint256 unlockedShares =
totalShares(address(_token)) - lockedShares(address(_token));
if (unlockedShares == 0) {
return 0;
}
return
(_token.balanceOf(address(this)) * unlockedShares) /
totalShares(address(_token));
}
/**
* @dev internal helper to get current usage ratio
* @return GYSR usage ratio
*/
function _usage() private view returns (uint256) {
if (totalStakingShares == 0) {
return 0;
}
return
((totalStakingShares - totalRawStakingShares) * 10**DECIMALS) /
totalStakingShares;
}
/**
* @param addr address of interest
* @return number of active stakes for user
*/
function stakeCount(address addr) public view returns (uint256) {
return stakes[addr].length;
}
}
/*
ERC20FriendlyRewardModuleFactory
https://github.com/gysr-io/core
SPDX-License-Identifier: MIT
*/
pragma solidity 0.8.4;
import "./interfaces/IModuleFactory.sol";
import "./ERC20FriendlyRewardModule.sol";
/**
* @title ERC20 friendly reward module factory
*
* @notice this factory contract handles deployment for the
* ERC20FriendlyRewardModule contract
*
* @dev it is called by the parent PoolFactory and is responsible
* for parsing constructor arguments before creating a new contract
*/
contract ERC20FriendlyRewardModuleFactory is IModuleFactory {
/**
* @inheritdoc IModuleFactory
*/
function createModule(bytes calldata data)
external
override
returns (address)
{
// validate
require(data.length == 96, "frmf1");
// parse constructor arguments
address token;
uint256 penaltyStart;
uint256 penaltyPeriod;
assembly {
token := calldataload(68)
penaltyStart := calldataload(100)
penaltyPeriod := calldataload(132)
}
// create module
ERC20FriendlyRewardModule module =
new ERC20FriendlyRewardModule(
token,
penaltyStart,
penaltyPeriod,
address(this)
);
module.transferOwnership(msg.sender);
// output
emit ModuleCreated(msg.sender, address(module));
return address(module);
}
}
/*
GysrUtils
https://github.com/gysr-io/core
SPDX-License-Identifier: MIT
*/
pragma solidity 0.8.4;
import "./MathUtils.sol";
/**
* @title GYSR utilities
*
* @notice this library implements utility methods for the GYSR multiplier
* and spending mechanics
*/
library GysrUtils {
using MathUtils for int128;
// constants
uint256 public constant DECIMALS = 18;
uint256 public constant GYSR_PROPORTION = 10**(DECIMALS - 2); // 1%
/**
* @notice compute GYSR bonus as a function of usage ratio, stake amount,
* and GYSR spent
* @param gysr number of GYSR token applied to bonus
* @param amount number of tokens or shares to unstake
* @param total number of tokens or shares in overall pool
* @param ratio usage ratio from 0 to 1
* @return multiplier value
*/
function gysrBonus(
uint256 gysr,
uint256 amount,
uint256 total,
uint256 ratio
) internal pure returns (uint256) {
if (amount == 0) {
return 0;
}
if (total == 0) {
return 0;
}
if (gysr == 0) {
return 10**DECIMALS;
}
// scale GYSR amount with respect to proportion
uint256 portion = (GYSR_PROPORTION * total) / 10**DECIMALS;
if (amount > portion) {
gysr = (gysr * portion) / amount;
}
// 1 + gysr / (0.01 + ratio)
uint256 x = 2**64 + (2**64 * gysr) / (10**(DECIMALS - 2) + ratio);
return
10**DECIMALS +
(uint256(int256(int128(uint128(x)).logbase10())) * 10**DECIMALS) /
2**64;
}
}
/*
MathUtils
https://github.com/gysr-io/core
SPDX-License-Identifier: BSD-4-Clause
*/
pragma solidity 0.8.4;
/**
* @title Math utilities
*
* @notice this library implements various logarithmic math utilies which support
* other contracts and specifically the GYSR multiplier calculation
*
* @dev h/t https://github.com/abdk-consulting/abdk-libraries-solidity
*/
library MathUtils {
/**
* @notice calculate binary logarithm of x
*
* @param x signed 64.64-bit fixed point number, require x > 0
* @return signed 64.64-bit fixed point number
*/
function logbase2(int128 x) internal pure returns (int128) {
unchecked {
require(x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) {
xc >>= 64;
msb += 64;
}
if (xc >= 0x100000000) {
xc >>= 32;
msb += 32;
}
if (xc >= 0x10000) {
xc >>= 16;
msb += 16;
}
if (xc >= 0x100) {
xc >>= 8;
msb += 8;
}
if (xc >= 0x10) {
xc >>= 4;
msb += 4;
}
if (xc >= 0x4) {
xc >>= 2;
msb += 2;
}
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = (msb - 64) << 64;
uint256 ux = uint256(int256(x)) << uint256(127 - msb);
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256(b);
}
return int128(result);
}
}
/**
* @notice calculate natural logarithm of x
* @dev magic constant comes from ln(2) * 2^128 -> hex
* @param x signed 64.64-bit fixed point number, require x > 0
* @return signed 64.64-bit fixed point number
*/
function ln(int128 x) internal pure returns (int128) {
unchecked {
require(x > 0);
return
int128(
int256(
(uint256(int256(logbase2(x))) *
0xB17217F7D1CF79ABC9E3B39803F2F6AF) >> 128
)
);
}
}
/**
* @notice calculate logarithm base 10 of x
* @dev magic constant comes from log10(2) * 2^128 -> hex
* @param x signed 64.64-bit fixed point number, require x > 0
* @return signed 64.64-bit fixed point number
*/
function logbase10(int128 x) internal pure returns (int128) {
require(x > 0);
return
int128(
int256(
(uint256(int256(logbase2(x))) *
0x4d104d427de7fce20a6e420e02236748) >> 128
)
);
}
// wrapper functions to allow testing
function testlogbase2(int128 x) public pure returns (int128) {
return logbase2(x);
}
function testlogbase10(int128 x) public pure returns (int128) {
return logbase10(x);
}
}
/*
OwnerController
https://github.com/gysr-io/core
SPDX-License-Identifier: MIT
*/
pragma solidity 0.8.4;
/**
* @title Owner controller
*
* @notice this base contract implements an owner-controller access model.
*
* @dev the contract is an adapted version of the OpenZeppelin Ownable contract.
* It allows the owner to designate an additional account as the controller to
* perform restricted operations.
*
* Other changes include supporting role verification with a require method
* in addition to the modifier option, and removing some unneeded functionality.
*
* Original contract here:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol
*/
contract OwnerController {
address private _owner;
address private _controller;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
event ControlTransferred(
address indexed previousController,
address indexed newController
);
constructor() {
_owner = msg.sender;
_controller = msg.sender;
emit OwnershipTransferred(address(0), _owner);
emit ControlTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Returns the address of the current controller.
*/
function controller() public view returns (address) {
return _controller;
}
/**
* @dev Modifier that throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == msg.sender, "oc1");
_;
}
/**
* @dev Modifier that throws if called by any account other than the controller.
*/
modifier onlyController() {
require(_controller == msg.sender, "oc2");
_;
}
/**
* @dev Throws if called by any account other than the owner.
*/
function requireOwner() internal view {
require(_owner == msg.sender, "oc1");
}
/**
* @dev Throws if called by any account other than the controller.
*/
function requireController() internal view {
require(_controller == msg.sender, "oc2");
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`). This can
* include renouncing ownership by transferring to the zero address.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual {
requireOwner();
require(newOwner != address(0), "oc3");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
/**
* @dev Transfers control of the contract to a new account (`newController`).
* Can only be called by the owner.
*/
function transferControl(address newController) public virtual {
requireOwner();
require(newController != address(0), "oc4");
emit ControlTransferred(_controller, newController);
_controller = newController;
}
}
/*
IEvents
https://github.com/gysr-io/core
SPDX-License-Identifier: MIT
*/
pragma solidity 0.8.4;
/**
* @title GYSR event system
*
* @notice common interface to define GYSR event system
*/
interface IEvents {
// staking
event Staked(
address indexed user,
address indexed token,
uint256 amount,
uint256 shares
);
event Unstaked(
address indexed user,
address indexed token,
uint256 amount,
uint256 shares
);
event Claimed(
address indexed user,
address indexed token,
uint256 amount,
uint256 shares
);
// rewards
event RewardsDistributed(
address indexed user,
address indexed token,
uint256 amount,
uint256 shares
);
event RewardsFunded(
address indexed token,
uint256 amount,
uint256 shares,
uint256 timestamp
);
event RewardsUnlocked(address indexed token, uint256 shares);
event RewardsExpired(
address indexed token,
uint256 amount,
uint256 shares,
uint256 timestamp
);
// gysr
event GysrSpent(address indexed user, uint256 amount);
event GysrVested(address indexed user, uint256 amount);
event GysrWithdrawn(uint256 amount);
}
/*
IModuleFactory
https://github.com/gysr-io/core
SPDX-License-Identifier: MIT
*/
pragma solidity 0.8.4;
/**
* @title Module factory interface
*
* @notice this defines the common module factory interface used by the
* main factory to create the staking and reward modules for a new Pool.
*/
interface IModuleFactory {
// events
event ModuleCreated(address indexed user, address module);
/**
* @notice create a new Pool module
* @param data binary encoded construction parameters
* @return address of newly created module
*/
function createModule(bytes calldata data) external returns (address);
}
/*
IRewardModule
https://github.com/gysr-io/core
SPDX-License-Identifier: MIT
*/
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IEvents.sol";
import "../OwnerController.sol";
/**
* @title Reward module interface
*
* @notice this contract defines the common interface that any reward module
* must implement to be compatible with the modular Pool architecture.
*/
abstract contract IRewardModule is OwnerController, IEvents {
// constants
uint256 public constant DECIMALS = 18;
/**
* @return array of reward tokens
*/
function tokens() external view virtual returns (address[] memory);
/**
* @return array of reward token balances
*/
function balances() external view virtual returns (uint256[] memory);
/**
* @return GYSR usage ratio for reward module
*/
function usage() external view virtual returns (uint256);
/**
* @return address of module factory
*/
function factory() external view virtual returns (address);
/**
* @notice perform any necessary accounting for new stake
* @param account address of staking account
* @param user address of user
* @param shares number of new shares minted
* @param data addtional data
* @return amount of gysr spent
* @return amount of gysr vested
*/
function stake(
address account,
address user,
uint256 shares,
bytes calldata data
) external virtual returns (uint256, uint256);
/**
* @notice reward user and perform any necessary accounting for unstake
* @param account address of staking account
* @param user address of user
* @param shares number of shares burned
* @param data additional data
* @return amount of gysr spent
* @return amount of gysr vested
*/
function unstake(
address account,
address user,
uint256 shares,
bytes calldata data
) external virtual returns (uint256, uint256);
/**
* @notice reward user and perform and necessary accounting for existing stake
* @param account address of staking account
* @param user address of user
* @param shares number of shares being claimed against
* @param data addtional data
* @return amount of gysr spent
* @return amount of gysr vested
*/
function claim(
address account,
address user,
uint256 shares,
bytes calldata data
) external virtual returns (uint256, uint256);
/**
* @notice method called by anyone to update accounting
* @param user address of user for update
* @dev will only be called ad hoc and should not contain essential logic
*/
function update(address user) external virtual;
/**
* @notice method called by owner to clean up and perform additional accounting
* @dev will only be called ad hoc and should not contain any essential logic
*/
function clean() external virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// 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) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | * @notice compute number of unlockable shares for a specific funding schedule @param token contract address of reward token @param idx index of the funding @return the number of unlockable shares/ funding schedule is in future empty handle zero-duration period or leftover dust from integer division | function unlockable(address token, uint256 idx)
public
view
returns (uint256)
{
Funding storage funding = _fundings[token][idx];
if (block.timestamp < funding.start) {
return 0;
}
if (funding.locked == 0) {
return 0;
}
if (block.timestamp >= funding.start + funding.duration) {
return funding.locked;
}
return
((block.timestamp - funding.updated) * funding.shares) /
funding.duration;
}
| 85,386 | [
1,
9200,
1300,
434,
7186,
429,
24123,
364,
279,
2923,
22058,
4788,
225,
1147,
6835,
1758,
434,
19890,
1147,
225,
2067,
770,
434,
326,
22058,
327,
326,
1300,
434,
7186,
429,
24123,
19,
22058,
4788,
353,
316,
3563,
1008,
1640,
3634,
17,
8760,
3879,
578,
29709,
302,
641,
628,
3571,
16536,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7186,
429,
12,
2867,
1147,
16,
2254,
5034,
2067,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
478,
14351,
2502,
22058,
273,
389,
74,
1074,
899,
63,
2316,
6362,
3465,
15533,
203,
203,
3639,
309,
261,
2629,
18,
5508,
411,
22058,
18,
1937,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
3639,
309,
261,
74,
14351,
18,
15091,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
3639,
309,
261,
2629,
18,
5508,
1545,
22058,
18,
1937,
397,
22058,
18,
8760,
13,
288,
203,
5411,
327,
22058,
18,
15091,
31,
203,
3639,
289,
203,
203,
3639,
327,
203,
5411,
14015,
2629,
18,
5508,
300,
22058,
18,
7007,
13,
380,
22058,
18,
30720,
13,
342,
203,
5411,
22058,
18,
8760,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-07-05
*/
// SPDX-License-Identifier: UNLICENSED
/*
▄▄█ ▄ ██ █▄▄▄▄ ▄█
██ █ █ █ █ ▄▀ ██
██ ██ █ █▄▄█ █▀▀▌ ██
▐█ █ █ █ █ █ █ █ ▐█
▐ █ █ █ █ █ ▐
█ ██ █ ▀
▀ */
/// 🦊🌾 Special thanks to Keno / Boring / Gonpachi / Karbon for review and continued inspiration.
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;
/// @notice Minimal erc20 interface (with EIP 2612) to aid other interfaces.
interface IERC20 {
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
/// @notice Interface for Dai Stablecoin (DAI) `permit()` primitive.
interface IDaiPermit {
function permit(
address holder,
address spender,
uint256 nonce,
uint256 expiry,
bool allowed,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// File @boringcrypto/boring-solidity/contracts/libraries/[email protected]
/// License-Identifier: MIT
/// @dev Adapted for Inari.
library BoringERC20 {
bytes4 private constant SIG_BALANCE_OF = 0x70a08231; // balanceOf(address)
bytes4 private constant SIG_APPROVE = 0x095ea7b3; // approve(address,uint256)
bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256)
bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256)
/// @notice Provides a gas-optimized balance check on this contract to avoid a redundant extcodesize check in addition to the returndatasize check.
/// @param token The address of the ERC-20 token.
/// @return amount The token amount.
function safeBalanceOfSelf(IERC20 token) internal view returns (uint256 amount) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_BALANCE_OF, address(this)));
require(success && data.length >= 32, "BoringERC20: BalanceOf failed");
amount = abi.decode(data, (uint256));
}
/// @notice Provides a safe ERC20.approve version for different ERC-20 implementations.
/// @param token The address of the ERC-20 token.
/// @param to The address of the user to grant spending right.
/// @param amount The token amount to grant spending right over.
function safeApprove(
IERC20 token,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_APPROVE, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Approve failed");
}
/// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations.
/// Reverts on a failed transfer.
/// @param token The address of the ERC-20 token.
/// @param to Transfer tokens to.
/// @param amount The token amount.
function safeTransfer(
IERC20 token,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed");
}
/// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations.
/// Reverts on a failed transfer.
/// @param token The address of the ERC-20 token.
/// @param from Transfer tokens from.
/// @param to Transfer tokens to.
/// @param amount The token amount.
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed");
}
}
// File @boringcrypto/boring-solidity/contracts/[email protected]
/// License-Identifier: MIT
/// @dev Adapted for Inari.
contract BaseBoringBatchable {
/// @dev Helper function to extract a useful revert message from a failed call.
/// If the returned data is malformed or not correctly abi encoded then this call can fail itself.
function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) {
// If the _res length is less than 68, then the transaction failed silently (without a revert message)
if (_returnData.length < 68) return "Transaction reverted silently";
assembly {
// Slice the sighash.
_returnData := add(_returnData, 0x04)
}
return abi.decode(_returnData, (string)); // All that remains is the revert string
}
/// @notice Allows batched call to self (this contract).
/// @param calls An array of inputs for each call.
/// @param revertOnFail If True then reverts after a failed call and stops doing further calls.
function batch(bytes[] calldata calls, bool revertOnFail) external payable {
for (uint256 i = 0; i < calls.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(calls[i]);
if (!success && revertOnFail) {
revert(_getRevertMsg(result));
}
}
}
}
/// @notice Extends `BoringBatchable` with DAI `permit()`.
contract BoringBatchableWithDai is BaseBoringBatchable {
/// @notice Call wrapper that performs `ERC20.permit` using EIP 2612 primitive.
/// Lookup `IDaiPermit.permit`.
function permitDai(
IDaiPermit token,
address holder,
address spender,
uint256 nonce,
uint256 expiry,
bool allowed,
uint8 v,
bytes32 r,
bytes32 s
) public {
token.permit(holder, spender, nonce, expiry, allowed, v, r, s);
}
/// @notice Call wrapper that performs `ERC20.permit` on `token`.
/// Lookup `IERC20.permit`.
// F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert)
// if part of a batch this could be used to grief once as the second call would not need the permit
function permitToken(
IERC20 token,
address from,
address to,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
token.permit(from, to, amount, deadline, v, r, s);
}
}
/// @notice Babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method).
library Babylonian {
// computes square roots using the babylonian method
// credit for this implementation goes to
// https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687
function sqrt(uint256 x) internal pure returns (uint256) {
if (x == 0) return 0;
// this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2);
// however that code costs significantly more gas
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return (r < r1 ? r : r1);
}
}
/// @notice Interface for SushiSwap.
interface ISushiSwap {
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function token0() external pure returns (address);
function token1() external pure returns (address);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
/// @notice Interface for wrapped ether v9.
interface IWETH {
function deposit() external payable;
}
/// @notice Library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math).
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
/// @notice SushiSwap liquidity zaps based on awesomeness from zapper.fi (0xcff6eF0B9916682B37D80c19cFF8949bc1886bC2).
contract SushiZap {
using SafeMath for uint256;
using BoringERC20 for IERC20;
address constant sushiSwapFactory = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac; // SushiSwap factory contract
ISushiSwap constant sushiSwapRouter = ISushiSwap(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // SushiSwap router contract
uint256 constant deadline = 0xf000000000000000000000000000000000000000000000000000000000000000; // placeholder for swap deadline
bytes32 constant pairCodeHash = 0xe18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303; // SushiSwap pair code hash
event ZapIn(address sender, address pool, uint256 tokensRec);
/**
@notice This function is used to invest in given SushiSwap pair through ETH/ERC20 Tokens.
@param to Address to receive LP tokens.
@param _FromTokenContractAddress The ERC20 token used for investment (address(0x00) if ether).
@param _pairAddress The SushiSwap pair address.
@param _amount The amount of fromToken to invest.
@param _minPoolTokens Reverts if less tokens received than this.
@param _swapTarget Excecution target for the first swap.
@param swapData Dex quote data.
@return Amount of LP bought.
*/
function zapIn(
address to,
address _FromTokenContractAddress,
address _pairAddress,
uint256 _amount,
uint256 _minPoolTokens,
address _swapTarget,
bytes calldata swapData
) external payable returns (uint256) {
uint256 toInvest = _pullTokens(
_FromTokenContractAddress,
_amount
);
uint256 LPBought = _performZapIn(
_FromTokenContractAddress,
_pairAddress,
toInvest,
_swapTarget,
swapData
);
require(LPBought >= _minPoolTokens, 'ERR: High Slippage');
emit ZapIn(to, _pairAddress, LPBought);
IERC20(_pairAddress).safeTransfer(to, LPBought);
return LPBought;
}
function _getPairTokens(address _pairAddress) private pure returns (address token0, address token1)
{
ISushiSwap sushiPair = ISushiSwap(_pairAddress);
token0 = sushiPair.token0();
token1 = sushiPair.token1();
}
function _pullTokens(address token, uint256 amount) internal returns (uint256 value) {
if (token == address(0)) {
require(msg.value > 0, 'No eth sent');
return msg.value;
}
require(amount > 0, 'Invalid token amount');
require(msg.value == 0, 'Eth sent with token');
// transfer token
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
return amount;
}
function _performZapIn(
address _FromTokenContractAddress,
address _pairAddress,
uint256 _amount,
address _swapTarget,
bytes memory swapData
) internal returns (uint256) {
uint256 intermediateAmt;
address intermediateToken;
(
address _ToSushipoolToken0,
address _ToSushipoolToken1
) = _getPairTokens(_pairAddress);
if (
_FromTokenContractAddress != _ToSushipoolToken0 &&
_FromTokenContractAddress != _ToSushipoolToken1
) {
// swap to intermediate
(intermediateAmt, intermediateToken) = _fillQuote(
_FromTokenContractAddress,
_pairAddress,
_amount,
_swapTarget,
swapData
);
} else {
intermediateToken = _FromTokenContractAddress;
intermediateAmt = _amount;
}
// divide intermediate into appropriate amount to add liquidity
(uint256 token0Bought, uint256 token1Bought) = _swapIntermediate(
intermediateToken,
_ToSushipoolToken0,
_ToSushipoolToken1,
intermediateAmt
);
return
_sushiDeposit(
_ToSushipoolToken0,
_ToSushipoolToken1,
token0Bought,
token1Bought
);
}
function _sushiDeposit(
address _ToUnipoolToken0,
address _ToUnipoolToken1,
uint256 token0Bought,
uint256 token1Bought
) private returns (uint256) {
IERC20(_ToUnipoolToken0).safeApprove(address(sushiSwapRouter), 0);
IERC20(_ToUnipoolToken1).safeApprove(address(sushiSwapRouter), 0);
IERC20(_ToUnipoolToken0).safeApprove(
address(sushiSwapRouter),
token0Bought
);
IERC20(_ToUnipoolToken1).safeApprove(
address(sushiSwapRouter),
token1Bought
);
(uint256 amountA, uint256 amountB, uint256 LP) = sushiSwapRouter
.addLiquidity(
_ToUnipoolToken0,
_ToUnipoolToken1,
token0Bought,
token1Bought,
1,
1,
address(this),
deadline
);
// returning residue in token0, if any
if (token0Bought.sub(amountA) > 0) {
IERC20(_ToUnipoolToken0).safeTransfer(
msg.sender,
token0Bought.sub(amountA)
);
}
// returning residue in token1, if any
if (token1Bought.sub(amountB) > 0) {
IERC20(_ToUnipoolToken1).safeTransfer(
msg.sender,
token1Bought.sub(amountB)
);
}
return LP;
}
function _fillQuote(
address _fromTokenAddress,
address _pairAddress,
uint256 _amount,
address _swapTarget,
bytes memory swapCallData
) private returns (uint256 amountBought, address intermediateToken) {
uint256 valueToSend;
if (_fromTokenAddress == address(0)) {
valueToSend = _amount;
} else {
IERC20 fromToken = IERC20(_fromTokenAddress);
fromToken.safeApprove(address(_swapTarget), 0);
fromToken.safeApprove(address(_swapTarget), _amount);
}
(address _token0, address _token1) = _getPairTokens(_pairAddress);
IERC20 token0 = IERC20(_token0);
IERC20 token1 = IERC20(_token1);
uint256 initialBalance0 = token0.safeBalanceOfSelf();
uint256 initialBalance1 = token1.safeBalanceOfSelf();
(bool success, ) = _swapTarget.call{value: valueToSend}(swapCallData);
require(success, 'Error Swapping Tokens 1');
uint256 finalBalance0 = token0.safeBalanceOfSelf().sub(
initialBalance0
);
uint256 finalBalance1 = token1.safeBalanceOfSelf().sub(
initialBalance1
);
if (finalBalance0 > finalBalance1) {
amountBought = finalBalance0;
intermediateToken = _token0;
} else {
amountBought = finalBalance1;
intermediateToken = _token1;
}
require(amountBought > 0, 'Swapped to Invalid Intermediate');
}
function _swapIntermediate(
address _toContractAddress,
address _ToSushipoolToken0,
address _ToSushipoolToken1,
uint256 _amount
) private returns (uint256 token0Bought, uint256 token1Bought) {
(address token0, address token1) = _ToSushipoolToken0 < _ToSushipoolToken1 ? (_ToSushipoolToken0, _ToSushipoolToken1) : (_ToSushipoolToken1, _ToSushipoolToken0);
ISushiSwap pair =
ISushiSwap(
uint256(
keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))
)
);
(uint256 res0, uint256 res1, ) = pair.getReserves();
if (_toContractAddress == _ToSushipoolToken0) {
uint256 amountToSwap = calculateSwapInAmount(res0, _amount);
// if no reserve or a new pair is created
if (amountToSwap <= 0) amountToSwap = _amount / 2;
token1Bought = _token2Token(
_toContractAddress,
_ToSushipoolToken1,
amountToSwap
);
token0Bought = _amount.sub(amountToSwap);
} else {
uint256 amountToSwap = calculateSwapInAmount(res1, _amount);
// if no reserve or a new pair is created
if (amountToSwap <= 0) amountToSwap = _amount / 2;
token0Bought = _token2Token(
_toContractAddress,
_ToSushipoolToken0,
amountToSwap
);
token1Bought = _amount.sub(amountToSwap);
}
}
function calculateSwapInAmount(uint256 reserveIn, uint256 userIn) private pure returns (uint256)
{
return
Babylonian
.sqrt(
reserveIn.mul(userIn.mul(3988000) + reserveIn.mul(3988009))
)
.sub(reserveIn.mul(1997)) / 1994;
}
/**
@notice This function is used to swap ERC20 <> ERC20.
@param _FromTokenContractAddress The token address to swap from.
@param _ToTokenContractAddress The token address to swap to.
@param tokens2Trade The amount of tokens to swap.
@return tokenBought The quantity of tokens bought.
*/
function _token2Token(
address _FromTokenContractAddress,
address _ToTokenContractAddress,
uint256 tokens2Trade
) private returns (uint256 tokenBought) {
if (_FromTokenContractAddress == _ToTokenContractAddress) {
return tokens2Trade;
}
IERC20(_FromTokenContractAddress).safeApprove(
address(sushiSwapRouter),
0
);
IERC20(_FromTokenContractAddress).safeApprove(
address(sushiSwapRouter),
tokens2Trade
);
(address token0, address token1) = _FromTokenContractAddress < _ToTokenContractAddress ? (_FromTokenContractAddress, _ToTokenContractAddress) : (_ToTokenContractAddress, _FromTokenContractAddress);
address pair =
address(
uint256(
keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))
)
);
require(pair != address(0), 'No Swap Available');
address[] memory path = new address[](2);
path[0] = _FromTokenContractAddress;
path[1] = _ToTokenContractAddress;
tokenBought = sushiSwapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
path,
address(this),
deadline
)[path.length - 1];
require(tokenBought > 0, 'Error Swapping Tokens 2');
}
function zapOut(
address pair,
address to,
uint256 amount
) external returns (uint256 amount0, uint256 amount1) {
IERC20(pair).safeTransferFrom(msg.sender, pair, amount); // pull `amount` to `pair`
(amount0, amount1) = ISushiSwap(pair).burn(to); // trigger burn to redeem liquidity for `to`
}
function zapOutBalance(
address pair,
address to
) external returns (uint256 amount0, uint256 amount1) {
IERC20(pair).safeTransfer(pair, IERC20(pair).safeBalanceOfSelf()); // transfer local balance to `pair`
(amount0, amount1) = ISushiSwap(pair).burn(to); // trigger burn to redeem liquidity for `to`
}
}
/// @notice Interface for depositing into and withdrawing from Aave lending pool.
interface IAaveBridge {
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
function withdraw(
address token,
uint256 amount,
address destination
) external;
}
/// @notice Interface for depositing into and withdrawing from BentoBox vault.
interface IBentoBridge {
function registerProtocol() external;
function setMasterContractApproval(
address user,
address masterContract,
bool approved,
uint8 v,
bytes32 r,
bytes32 s
) external;
function deposit(
IERC20 token_,
address from,
address to,
uint256 amount,
uint256 share
) external payable returns (uint256 amountOut, uint256 shareOut);
function withdraw(
IERC20 token_,
address from,
address to,
uint256 amount,
uint256 share
) external returns (uint256 amountOut, uint256 shareOut);
}
/// @notice Interface for depositing into and withdrawing from Compound finance protocol.
interface ICompoundBridge {
function underlying() external view returns (address);
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
}
/// @notice Interface for depositing and withdrawing assets from KASHI.
interface IKashiBridge {
function asset() external returns (IERC20);
function addAsset(
address to,
bool skim,
uint256 share
) external returns (uint256 fraction);
function removeAsset(address to, uint256 fraction) external returns (uint256 share);
}
/// @notice Interface for depositing into and withdrawing from SushiBar.
interface ISushiBarBridge {
function enter(uint256 amount) external;
function leave(uint256 share) external;
}
/// @notice Interface for SUSHI MasterChef v2.
interface IMasterChefV2 {
function lpToken(uint256 pid) external view returns (IERC20);
function deposit(uint256 pid, uint256 amount, address to) external;
}
/// @notice Contract that batches SUSHI staking and DeFi strategies - V1 'iroirona'.
contract InariV1 is BoringBatchableWithDai, SushiZap {
using SafeMath for uint256;
using BoringERC20 for IERC20;
IERC20 constant sushiToken = IERC20(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2); // SUSHI token contract
address constant sushiBar = 0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272; // xSUSHI staking contract for SUSHI
ISushiSwap constant sushiSwapSushiETHPair = ISushiSwap(0x795065dCc9f64b5614C407a6EFDC400DA6221FB0); // SUSHI/ETH pair on SushiSwap
IMasterChefV2 constant masterChefv2 = IMasterChefV2(0xEF0881eC094552b2e128Cf945EF17a6752B4Ec5d); // SUSHI MasterChef v2 contract
IAaveBridge constant aave = IAaveBridge(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9); // AAVE lending pool contract for xSUSHI staking into aXSUSHI
IERC20 constant aaveSushiToken = IERC20(0xF256CC7847E919FAc9B808cC216cAc87CCF2f47a); // aXSUSHI staking contract for xSUSHI
IBentoBridge constant bento = IBentoBridge(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); // BENTO vault contract
address constant crSushiToken = 0x338286C0BC081891A4Bda39C7667ae150bf5D206; // crSUSHI staking contract for SUSHI
address constant crXSushiToken = 0x228619CCa194Fbe3Ebeb2f835eC1eA5080DaFbb2; // crXSUSHI staking contract for xSUSHI
address constant wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // ETH wrapper contract v9
/// @notice Initialize this Inari contract.
constructor() {
bento.registerProtocol(); // register this contract with BENTO
}
/// @notice Helper function to approve this contract to spend tokens and enable strategies.
function bridgeToken(IERC20[] calldata token, address[] calldata to) external {
for (uint256 i = 0; i < token.length; i++) {
token[i].safeApprove(to[i], type(uint256).max); // max approve `to` spender to pull `token` from this contract
}
}
/**********
TKN HELPERS
**********/
function withdrawToken(IERC20 token, address to, uint256 amount) external {
token.safeTransfer(to, amount);
}
function withdrawTokenBalance(IERC20 token, address to) external {
token.safeTransfer(to, token.safeBalanceOfSelf());
}
/***********
SUSHI HELPER
***********/
/// @notice Stake SUSHI local balance into xSushi for benefit of `to` by call to `sushiBar`.
function stakeSushiBalance(address to) external {
ISushiBarBridge(sushiBar).enter(sushiToken.safeBalanceOfSelf()); // stake local SUSHI into `sushiBar` xSUSHI
IERC20(sushiBar).safeTransfer(to, IERC20(sushiBar).safeBalanceOfSelf()); // transfer resulting xSUSHI to `to`
}
/***********
CHEF HELPERS
***********/
function depositToMasterChefv2(uint256 pid, uint256 amount, address to) external {
masterChefv2.deposit(pid, amount, to);
}
function balanceToMasterChefv2(uint256 pid, address to) external {
IERC20 lpToken = masterChefv2.lpToken(pid);
masterChefv2.deposit(pid, lpToken.safeBalanceOfSelf(), to);
}
/// @notice Liquidity zap into CHEF.
function zapToMasterChef(
address to,
address _FromTokenContractAddress,
uint256 _amount,
uint256 _minPoolTokens,
uint256 pid,
address _swapTarget,
bytes calldata swapData
) external payable returns (uint256 LPBought) {
uint256 toInvest = _pullTokens(
_FromTokenContractAddress,
_amount
);
IERC20 _pairAddress = masterChefv2.lpToken(pid);
LPBought = _performZapIn(
_FromTokenContractAddress,
address(_pairAddress),
toInvest,
_swapTarget,
swapData
);
require(LPBought >= _minPoolTokens, "ERR: High Slippage");
emit ZapIn(to, address(_pairAddress), LPBought);
masterChefv2.deposit(pid, LPBought, to);
}
/************
KASHI HELPERS
************/
function assetToKashi(IKashiBridge kashiPair, address to, uint256 amount) external returns (uint256 fraction) {
IERC20 asset = kashiPair.asset();
asset.safeTransferFrom(msg.sender, address(bento), amount);
IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), amount, 0);
fraction = kashiPair.addAsset(to, true, amount);
}
function assetToKashiChef(uint256 pid, uint256 amount, address to) external returns (uint256 fraction) {
address kashiPair = address(masterChefv2.lpToken(pid));
IERC20 asset = IKashiBridge(kashiPair).asset();
asset.safeTransferFrom(msg.sender, address(bento), amount);
IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), amount, 0);
fraction = IKashiBridge(kashiPair).addAsset(address(this), true, amount);
masterChefv2.deposit(pid, fraction, to);
}
function assetBalanceToKashi(IKashiBridge kashiPair, address to) external returns (uint256 fraction) {
IERC20 asset = kashiPair.asset();
uint256 balance = asset.safeBalanceOfSelf();
IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), balance, 0);
fraction = kashiPair.addAsset(to, true, balance);
}
function assetBalanceToKashiChef(uint256 pid, address to) external returns (uint256 fraction) {
address kashiPair = address(masterChefv2.lpToken(pid));
IERC20 asset = IKashiBridge(kashiPair).asset();
uint256 balance = asset.safeBalanceOfSelf();
IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), balance, 0);
fraction = IKashiBridge(kashiPair).addAsset(address(this), true, balance);
masterChefv2.deposit(pid, fraction, to);
}
function assetBalanceFromKashi(address kashiPair, address to) external returns (uint256 share) {
share = IKashiBridge(kashiPair).removeAsset(to, IERC20(kashiPair).safeBalanceOfSelf());
}
/// @notice Liquidity zap into KASHI.
function zapToKashi(
address to,
address _FromTokenContractAddress,
IKashiBridge kashiPair,
uint256 _amount,
uint256 _minPoolTokens,
address _swapTarget,
bytes calldata swapData
) external payable returns (uint256 fraction) {
uint256 toInvest = _pullTokens(
_FromTokenContractAddress,
_amount
);
IERC20 _pairAddress = kashiPair.asset();
uint256 LPBought = _performZapIn(
_FromTokenContractAddress,
address(_pairAddress),
toInvest,
_swapTarget,
swapData
);
require(LPBought >= _minPoolTokens, "ERR: High Slippage");
emit ZapIn(to, address(_pairAddress), LPBought);
_pairAddress.safeTransfer(address(bento), LPBought);
IBentoBridge(bento).deposit(_pairAddress, address(bento), address(kashiPair), LPBought, 0);
fraction = kashiPair.addAsset(to, true, LPBought);
}
/*
██ ██ ▄ ▄███▄
█ █ █ █ █ █▀ ▀
█▄▄█ █▄▄█ █ █ ██▄▄
█ █ █ █ █ █ █▄ ▄▀
█ █ █ █ ▀███▀
█ █ █▐
▀ ▀ ▐ */
/***********
AAVE HELPERS
***********/
function balanceToAave(address underlying, address to) external {
aave.deposit(underlying, IERC20(underlying).safeBalanceOfSelf(), to, 0);
}
function balanceFromAave(address aToken, address to) external {
address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token
aave.withdraw(underlying, IERC20(aToken).safeBalanceOfSelf(), to);
}
/**************************
AAVE -> UNDERLYING -> BENTO
**************************/
/// @notice Migrate AAVE `aToken` underlying `amount` into BENTO for benefit of `to` by batching calls to `aave` and `bento`.
function aaveToBento(address aToken, address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) {
IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract
address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token
aave.withdraw(underlying, amount, address(bento)); // burn deposited `aToken` from `aave` into `underlying`
(amountOut, shareOut) = bento.deposit(IERC20(underlying), address(bento), to, amount, 0); // stake `underlying` into BENTO for `to`
}
/**************************
BENTO -> UNDERLYING -> AAVE
**************************/
/// @notice Migrate `underlying` `amount` from BENTO into AAVE for benefit of `to` by batching calls to `bento` and `aave`.
function bentoToAave(IERC20 underlying, address to, uint256 amount) external {
bento.withdraw(underlying, msg.sender, address(this), amount, 0); // withdraw `amount` of `underlying` from BENTO into this contract
aave.deposit(address(underlying), amount, to, 0); // stake `underlying` into `aave` for `to`
}
/*************************
AAVE -> UNDERLYING -> COMP
*************************/
/// @notice Migrate AAVE `aToken` underlying `amount` into COMP/CREAM `cToken` for benefit of `to` by batching calls to `aave` and `cToken`.
function aaveToCompound(address aToken, address cToken, address to, uint256 amount) external {
IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract
address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token
aave.withdraw(underlying, amount, address(this)); // burn deposited `aToken` from `aave` into `underlying`
ICompoundBridge(cToken).mint(amount); // stake `underlying` into `cToken`
IERC20(cToken).safeTransfer(to, IERC20(cToken).safeBalanceOfSelf()); // transfer resulting `cToken` to `to`
}
/*************************
COMP -> UNDERLYING -> AAVE
*************************/
/// @notice Migrate COMP/CREAM `cToken` underlying `amount` into AAVE for benefit of `to` by batching calls to `cToken` and `aave`.
function compoundToAave(address cToken, address to, uint256 amount) external {
IERC20(cToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `cToken` `amount` into this contract
ICompoundBridge(cToken).redeem(amount); // burn deposited `cToken` into `underlying`
address underlying = ICompoundBridge(cToken).underlying(); // sanity check for `underlying` token
aave.deposit(underlying, IERC20(underlying).safeBalanceOfSelf(), to, 0); // stake resulting `underlying` into `aave` for `to`
}
/**********************
SUSHI -> XSUSHI -> AAVE
**********************/
/// @notice Stake SUSHI `amount` into aXSUSHI for benefit of `to` by batching calls to `sushiBar` and `aave`.
function stakeSushiToAave(address to, uint256 amount) external { // SAAVE
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI
aave.deposit(sushiBar, IERC20(sushiBar).safeBalanceOfSelf(), to, 0); // stake resulting xSUSHI into `aave` aXSUSHI for `to`
}
/**********************
AAVE -> XSUSHI -> SUSHI
**********************/
/// @notice Unstake aXSUSHI `amount` into SUSHI for benefit of `to` by batching calls to `aave` and `sushiBar`.
function unstakeSushiFromAave(address to, uint256 amount) external {
aaveSushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` aXSUSHI `amount` into this contract
aave.withdraw(sushiBar, amount, address(this)); // burn deposited aXSUSHI from `aave` into xSUSHI
ISushiBarBridge(sushiBar).leave(amount); // burn resulting xSUSHI from `sushiBar` into SUSHI
sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to`
}
/*
███ ▄███▄ ▄ ▄▄▄▄▀ ████▄
█ █ █▀ ▀ █ ▀▀▀ █ █ █
█ ▀ ▄ ██▄▄ ██ █ █ █ █
█ ▄▀ █▄ ▄▀ █ █ █ █ ▀████
███ ▀███▀ █ █ █ ▀
█ ██ */
/************
BENTO HELPERS
************/
function balanceToBento(IERC20 token, address to) external returns (uint256 amountOut, uint256 shareOut) {
(amountOut, shareOut) = bento.deposit(token, address(this), to, token.safeBalanceOfSelf(), 0);
}
/// @dev Included to be able to approve `bento` in the same transaction (using `batch()`).
function setBentoApproval(
address user,
address masterContract,
bool approved,
uint8 v,
bytes32 r,
bytes32 s
) external {
bento.setMasterContractApproval(user, masterContract, approved, v, r, s);
}
/// @notice Liquidity zap into BENTO.
function zapToBento(
address to,
address _FromTokenContractAddress,
address _pairAddress,
uint256 _amount,
uint256 _minPoolTokens,
address _swapTarget,
bytes calldata swapData
) external payable returns (uint256 LPBought) {
uint256 toInvest = _pullTokens(
_FromTokenContractAddress,
_amount
);
LPBought = _performZapIn(
_FromTokenContractAddress,
_pairAddress,
toInvest,
_swapTarget,
swapData
);
require(LPBought >= _minPoolTokens, "ERR: High Slippage");
emit ZapIn(to, _pairAddress, LPBought);
bento.deposit(IERC20(_pairAddress), address(this), to, LPBought, 0);
}
/// @notice Liquidity unzap from BENTO.
function zapFromBento(
address pair,
address to,
uint256 amount
) external returns (uint256 amount0, uint256 amount1) {
bento.withdraw(IERC20(pair), msg.sender, pair, amount, 0); // withdraw `amount` to `pair` from BENTO
(amount0, amount1) = ISushiSwap(pair).burn(to); // trigger burn to redeem liquidity for `to`
}
/***********************
SUSHI -> XSUSHI -> BENTO
***********************/
/// @notice Stake SUSHI `amount` into BENTO xSUSHI for benefit of `to` by batching calls to `sushiBar` and `bento`.
function stakeSushiToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI
(amountOut, shareOut) = bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).safeBalanceOfSelf(), 0); // stake resulting xSUSHI into BENTO for `to`
}
/***********************
BENTO -> XSUSHI -> SUSHI
***********************/
/// @notice Unstake xSUSHI `amount` from BENTO into SUSHI for benefit of `to` by batching calls to `bento` and `sushiBar`.
function unstakeSushiFromBento(address to, uint256 amount) external {
bento.withdraw(IERC20(sushiBar), msg.sender, address(this), amount, 0); // withdraw `amount` of xSUSHI from BENTO into this contract
ISushiBarBridge(sushiBar).leave(amount); // burn withdrawn xSUSHI from `sushiBar` into SUSHI
sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to`
}
/*
▄█▄ █▄▄▄▄ ▄███▄ ██ █▀▄▀█
█▀ ▀▄ █ ▄▀ █▀ ▀ █ █ █ █ █
█ ▀ █▀▀▌ ██▄▄ █▄▄█ █ ▄ █
█▄ ▄▀ █ █ █▄ ▄▀ █ █ █ █
▀███▀ █ ▀███▀ █ █
▀ █ ▀
▀ */
// - COMPOUND - //
/***********
COMP HELPERS
***********/
function balanceToCompound(ICompoundBridge cToken) external {
IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token
cToken.mint(underlying.safeBalanceOfSelf());
}
function balanceFromCompound(address cToken) external {
ICompoundBridge(cToken).redeem(IERC20(cToken).safeBalanceOfSelf());
}
/**************************
COMP -> UNDERLYING -> BENTO
**************************/
/// @notice Migrate COMP/CREAM `cToken` `cTokenAmount` into underlying and BENTO for benefit of `to` by batching calls to `cToken` and `bento`.
function compoundToBento(address cToken, address to, uint256 cTokenAmount) external returns (uint256 amountOut, uint256 shareOut) {
IERC20(cToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `cToken` `cTokenAmount` into this contract
ICompoundBridge(cToken).redeem(cTokenAmount); // burn deposited `cToken` into `underlying`
IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token
(amountOut, shareOut) = bento.deposit(underlying, address(this), to, underlying.safeBalanceOfSelf(), 0); // stake resulting `underlying` into BENTO for `to`
}
/**************************
BENTO -> UNDERLYING -> COMP
**************************/
/// @notice Migrate `cToken` `underlyingAmount` from BENTO into COMP/CREAM for benefit of `to` by batching calls to `bento` and `cToken`.
function bentoToCompound(address cToken, address to, uint256 underlyingAmount) external {
IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token
bento.withdraw(underlying, msg.sender, address(this), underlyingAmount, 0); // withdraw `underlyingAmount` of `underlying` from BENTO into this contract
ICompoundBridge(cToken).mint(underlyingAmount); // stake `underlying` into `cToken`
IERC20(cToken).safeTransfer(to, IERC20(cToken).safeBalanceOfSelf()); // transfer resulting `cToken` to `to`
}
/**********************
SUSHI -> CREAM -> BENTO
**********************/
/// @notice Stake SUSHI `amount` into crSUSHI and BENTO for benefit of `to` by batching calls to `crSushiToken` and `bento`.
function sushiToCreamToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ICompoundBridge(crSushiToken).mint(amount); // stake deposited SUSHI into crSUSHI
(amountOut, shareOut) = bento.deposit(IERC20(crSushiToken), address(this), to, IERC20(crSushiToken).safeBalanceOfSelf(), 0); // stake resulting crSUSHI into BENTO for `to`
}
/**********************
BENTO -> CREAM -> SUSHI
**********************/
/// @notice Unstake crSUSHI `cTokenAmount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento` and `crSushiToken`.
function sushiFromCreamFromBento(address to, uint256 cTokenAmount) external {
bento.withdraw(IERC20(crSushiToken), msg.sender, address(this), cTokenAmount, 0); // withdraw `cTokenAmount` of `crSushiToken` from BENTO into this contract
ICompoundBridge(crSushiToken).redeem(cTokenAmount); // burn deposited `crSushiToken` into SUSHI
sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to`
}
/***********************
SUSHI -> XSUSHI -> CREAM
***********************/
/// @notice Stake SUSHI `amount` into crXSUSHI for benefit of `to` by batching calls to `sushiBar` and `crXSushiToken`.
function stakeSushiToCream(address to, uint256 amount) external { // SCREAM
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI
ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).safeBalanceOfSelf()); // stake resulting xSUSHI into crXSUSHI
IERC20(crXSushiToken).safeTransfer(to, IERC20(crXSushiToken).safeBalanceOfSelf()); // transfer resulting crXSUSHI to `to`
}
/***********************
CREAM -> XSUSHI -> SUSHI
***********************/
/// @notice Unstake crXSUSHI `cTokenAmount` into SUSHI for benefit of `to` by batching calls to `crXSushiToken` and `sushiBar`.
function unstakeSushiFromCream(address to, uint256 cTokenAmount) external {
IERC20(crXSushiToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `crXSushiToken` `cTokenAmount` into this contract
ICompoundBridge(crXSushiToken).redeem(cTokenAmount); // burn deposited `crXSushiToken` `cTokenAmount` into xSUSHI
ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).safeBalanceOfSelf()); // burn resulting xSUSHI `amount` from `sushiBar` into SUSHI
sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to`
}
/********************************
SUSHI -> XSUSHI -> CREAM -> BENTO
********************************/
/// @notice Stake SUSHI `amount` into crXSUSHI and BENTO for benefit of `to` by batching calls to `sushiBar`, `crXSushiToken` and `bento`.
function stakeSushiToCreamToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI
ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).safeBalanceOfSelf()); // stake resulting xSUSHI into crXSUSHI
(amountOut, shareOut) = bento.deposit(IERC20(crXSushiToken), address(this), to, IERC20(crXSushiToken).safeBalanceOfSelf(), 0); // stake resulting crXSUSHI into BENTO for `to`
}
/********************************
BENTO -> CREAM -> XSUSHI -> SUSHI
********************************/
/// @notice Unstake crXSUSHI `cTokenAmount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento`, `crXSushiToken` and `sushiBar`.
function unstakeSushiFromCreamFromBento(address to, uint256 cTokenAmount) external {
bento.withdraw(IERC20(crXSushiToken), msg.sender, address(this), cTokenAmount, 0); // withdraw `cTokenAmount` of `crXSushiToken` from BENTO into this contract
ICompoundBridge(crXSushiToken).redeem(cTokenAmount); // burn deposited `crXSushiToken` `cTokenAmount` into xSUSHI
ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).safeBalanceOfSelf()); // burn resulting xSUSHI from `sushiBar` into SUSHI
sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to`
}
/*
▄▄▄▄▄ ▄ ▄ ██ █ ▄▄
█ ▀▄ █ █ █ █ █ █
▄ ▀▀▀▀▄ █ ▄ █ █▄▄█ █▀▀▀
▀▄▄▄▄▀ █ █ █ █ █ █
█ █ █ █ █
▀ ▀ █ ▀
▀ */
/// @notice Fallback for received ETH - SushiSwap ETH to stake SUSHI into xSUSHI and BENTO for benefit of `to`.
receive() external payable { // INARIZUSHI
(uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHPair.getReserves();
uint256 amountInWithFee = msg.value.mul(997);
uint256 out =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
IWETH(wETH).deposit{value: msg.value}();
IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value);
sushiSwapSushiETHPair.swap(out, 0, address(this), "");
ISushiBarBridge(sushiBar).enter(sushiToken.safeBalanceOfSelf()); // stake resulting SUSHI into `sushiBar` xSUSHI
bento.deposit(IERC20(sushiBar), address(this), msg.sender, IERC20(sushiBar).safeBalanceOfSelf(), 0); // stake resulting xSUSHI into BENTO for `to`
}
/// @notice SushiSwap ETH to stake SUSHI into xSUSHI and BENTO for benefit of `to`.
function inariZushi(address to) external payable returns (uint256 amountOut, uint256 shareOut) {
(uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHPair.getReserves();
uint256 amountInWithFee = msg.value.mul(997);
uint256 out =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
IWETH(wETH).deposit{value: msg.value}();
IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value);
sushiSwapSushiETHPair.swap(out, 0, address(this), "");
ISushiBarBridge(sushiBar).enter(sushiToken.safeBalanceOfSelf()); // stake resulting SUSHI into `sushiBar` xSUSHI
(amountOut, shareOut) = bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).safeBalanceOfSelf(), 0); // stake resulting xSUSHI into BENTO for `to`
}
/// @notice Simple SushiSwap `fromToken` `amountIn` to `toToken` for benefit of `to`.
function swap(address fromToken, address toToken, address to, uint256 amountIn) external returns (uint256 amountOut) {
(address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken);
ISushiSwap pair =
ISushiSwap(
uint256(
keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))
)
);
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountInWithFee = amountIn.mul(997);
IERC20(fromToken).safeTransferFrom(msg.sender, address(pair), amountIn);
if (toToken > fromToken) {
amountOut =
amountInWithFee.mul(reserve1) /
reserve0.mul(1000).add(amountInWithFee);
pair.swap(0, amountOut, to, "");
} else {
amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
pair.swap(amountOut, 0, to, "");
}
}
/// @notice Simple SushiSwap local `fromToken` balance in this contract to `toToken` for benefit of `to`.
function swapBalance(address fromToken, address toToken, address to) external returns (uint256 amountOut) {
(address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken);
ISushiSwap pair =
ISushiSwap(
uint256(
keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))
)
);
uint256 amountIn = IERC20(fromToken).safeBalanceOfSelf();
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountInWithFee = amountIn.mul(997);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
if (toToken > fromToken) {
amountOut =
amountInWithFee.mul(reserve1) /
reserve0.mul(1000).add(amountInWithFee);
pair.swap(0, amountOut, to, "");
} else {
amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
pair.swap(amountOut, 0, to, "");
}
}
} | burn deposited `aToken` from `aave` into `underlying`
| aave.withdraw(underlying, amount, address(bento)); | 2,388,145 | [
1,
70,
321,
443,
1724,
329,
1375,
69,
1345,
68,
628,
1375,
69,
836,
68,
1368,
1375,
9341,
6291,
68,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
279,
836,
18,
1918,
9446,
12,
9341,
6291,
16,
3844,
16,
1758,
12,
70,
29565,
10019,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.17;
library SafeMath {
/**
* Multiplication with safety check
*/
function Mul(uint256 a, uint256 b) pure internal returns (uint256) {
uint256 c = a * b;
//check result should not be other wise until a=0
assert(a == 0 || c / a == b);
return c;
}
/**
* Division with safety check
*/
function Div(uint256 a, uint256 b) pure internal returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* Subtraction with safety check
*/
function Sub(uint256 a, uint256 b) pure internal returns (uint256) {
//b must be greater that a as we need to store value in unsigned integer
assert(b <= a);
return a - b;
}
/**
* Addition with safety check
*/
function Add(uint256 a, uint256 b) pure internal returns (uint256) {
uint256 c = a + b;
//We need to check result greater than only one number for valid Addition
//refer https://ethereum.stackexchange.com/a/15270/16048
assert(c >= a);
return c;
}
}
/**
* Contract "ERC20Basic"
* Purpose: Defining ERC20 standard with basic functionality like - CheckBalance and Transfer including Transfer event
*/
contract ERC20Basic {
//Give realtime totalSupply of IAC token
uint256 public totalSupply;
//Get IAC token balance for provided address
function balanceOf(address who) view public returns (uint256);
//Transfer IAC token to provided address
function transfer(address _to, uint256 _value) public returns(bool ok);
//Emit Transfer event outside of blockchain for every IAC token transfer
event Transfer(address indexed _from, address indexed _to, uint256 _value);
}
/**
* Contract "ERC20"
* Purpose: Defining ERC20 standard with more advanced functionality like - Authorize spender to transfer IAC token
*/
contract ERC20 is ERC20Basic {
//Get IAC token amount that spender can spend from provided owner's account
function allowance(address owner, address spender) public view returns (uint256);
//Transfer initiated by spender
function transferFrom(address _from, address _to, uint256 _value) public returns(bool ok);
//Add spender to authrize for spending specified amount of IAC Token
function approve(address _spender, uint256 _value) public returns(bool ok);
//Emit event for any approval provided to spender
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* Contract "Ownable"
* Purpose: Defines Owner for contract and provide functionality to transfer ownership to another account
*/
contract Ownable {
//owner variable to store contract owner account
address public owner;
//Constructor for the contract to store owner's account on deployment
function Ownable() public {
owner = msg.sender;
}
//modifier to check transaction initiator is only owner
modifier onlyOwner() {
require (msg.sender == owner);
_;
}
//ownership can be transferred to provided newOwner. Function can only be initiated by contract owner's account
function transferOwnership(address newOwner) public onlyOwner {
require (newOwner != address(0));
owner = newOwner;
}
}
/**
* Contract "Pausable"
* Purpose: Contract to provide functionality to pause and resume Sale in case of emergency
*/
contract Pausable is Ownable {
//flag to indicate whether Sale is paused or not
bool public stopped;
//Emit event when any change happens in crowdsale state
event StateChanged(bool changed);
//modifier to continue with transaction only when Sale is not paused
modifier stopInEmergency {
require(!stopped);
_;
}
//modifier to continue with transaction only when Sale is paused
modifier onlyInEmergency {
require(stopped);
_;
}
// called by the owner on emergency, pause Sale
function emergencyStop() external onlyOwner {
stopped = true;
//Emit event when crowdsale state changes
StateChanged(true);
}
// called by the owner on end of emergency, resumes Sale
function release() external onlyOwner onlyInEmergency {
stopped = false;
//Emit event when crowdsale state changes
StateChanged(true);
}
}
/**
* Contract "IAC"
* Purpose: Create IAC token
*/
contract Injii is ERC20, Ownable {
using SafeMath for uint256;
/* Public variables of the token */
//To store name for token
string public constant name = "Injii Access Coins";
//To store symbol for token
string public constant symbol = "IAC";
//To store decimal places for token
uint8 public constant decimals = 0;
//To store decimal version for token
string public version = 'v1.0';
//flag to indicate whether transfer of IAC Token is allowed or not
bool public locked;
//map to store IAC Token balance corresponding to address
mapping(address => uint256) balances;
//To store spender with allowed amount of IAC Token to spend corresponding to IAC Token holder's account
mapping (address => mapping (address => uint256)) allowed;
//To handle ERC20 short address attack
modifier onlyPayloadSize(uint256 size) {
require(msg.data.length >= size + 4);
_;
}
// Lock transfer during Sale
modifier onlyUnlocked() {
require(!locked);
_;
}
//Contructor to define IAC Token properties
function Injii() public {
// lock the transfer function during Sale
locked = true;
//initial token supply is 0
totalSupply = 0;
}
//Implementation for transferring IAC Token to provided address
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public onlyUnlocked returns (bool){
//Check provided IAC Token should not be 0
if (_to != address(0) && _value >= 1) {
//deduct IAC Token amount from transaction initiator
balances[msg.sender] = balances[msg.sender].Sub(_value);
//Add IAC Token to balace of target account
balances[_to] = balances[_to].Add(_value);
//Emit event for transferring IAC Token
Transfer(msg.sender, _to, _value);
return true;
}
else{
return false;
}
}
//Transfer initiated by spender
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) public onlyUnlocked returns (bool) {
//Check provided IAC Token should not be 0
if (_to != address(0) && _from != address(0)) {
//Get amount of IAC Token for which spender is authorized
var _allowance = allowed[_from][msg.sender];
//Add amount of IAC Token in trarget account's balance
balances[_to] = balances[_to].Add(_value);
//Deduct IAC Token amount from _from account
balances[_from] = balances[_from].Sub(_value);
//Deduct Authorized amount for spender
allowed[_from][msg.sender] = _allowance.Sub(_value);
//Emit event for Transfer
Transfer(_from, _to, _value);
return true;
}else{
return false;
}
}
//Get IAC Token balance for provided address
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
//Add spender to authorize for spending specified amount of IAC Token
function approve(address _spender, uint256 _value) public returns (bool) {
require(_spender != address(0));
//do not allow decimals
uint256 iacToApprove = _value;
allowed[msg.sender][_spender] = iacToApprove;
//Emit event for approval provided to spender
Approval(msg.sender, _spender, iacToApprove);
return true;
}
//Get IAC Token amount that spender can spend from provided owner's account
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract Metadata {
address public owner;
mapping (uint => address) registerMap;
function Metadata() public {
owner = msg.sender;
registerMap[0] = msg.sender;
}
//get contract address by its ID
function getAddress (uint addressId) public view returns (address){
return registerMap[addressId];
}
//add or replace contract address by id. This is also the order of deployment
//0 = owner
//1 = Ecosystem
//2 = Crowdsale. This will deploy the token contract also.
//3 = Company Inventory
function addAddress (uint addressId, address addressContract) public {
assert(addressContract != 0x0 );
require (owner == msg.sender || owner == tx.origin);
registerMap[addressId] = addressContract;
}
}
contract Ecosystem is Ownable{
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
//variable of type metadata to store metadata contract object
Metadata private objMetadata;
Crowdsale private objCrowdsale;
uint256 constant private ecosystemContractID = 1;
uint256 constant private crowdsaleContractID = 2;
bool public crowdsaleAddressSet;
event TokensReceived(address receivedFrom, uint256 numberOfTokensReceive);
//Constructor
function Ecosystem(address _metadataContractAddr) public {
assert(_metadataContractAddr != address(0));
//passing address of meta data contract to metadata type address variable
objMetadata = Metadata(_metadataContractAddr);
//register this contract in metadata
objMetadata.addAddress(ecosystemContractID, this);
}
function SetCrowdsaleAddress () public onlyOwner {
require(!crowdsaleAddressSet);
address crowdsaleContractAddress = objMetadata.getAddress(crowdsaleContractID);
assert(crowdsaleContractAddress != address(0));
objCrowdsale = Crowdsale(crowdsaleContractAddress);
crowdsaleAddressSet = true;
}
function rewardUser(address user, uint256 iacToSend) public onlyOwner{
assert(crowdsaleAddressSet);
objCrowdsale.transfer(user, iacToSend);
}
function tokenFallback(address _from, uint _value){
TokensReceived(_from, _value);
}
}
contract CompanyInventory is Ownable{
using SafeMath for uint256;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
//record timestamp when the lock was initiated
uint256 public startBlock;
//to record how many tokens are unlocked
uint256 public unlockedTokens;
uint256 public initialReleaseDone = 0;
uint256 public secondReleaseDone = 0;
uint256 public totalSuppliedAfterLock = 0;
uint256 public balance = 0;
uint256 public totalSupplyFromInventory;
//total number of tokens available in inventory
uint256 public totalRemainInInventory;
//variable of type metadata to store metadata contract object
Metadata private objMetadata;
Crowdsale private objCrowdsale;
uint256 constant private crowdsaleContractID = 2;
uint256 constant private inventoryContractID = 3;
//Emit event when tokens are transferred from company inventory
event TransferredUnlockedTokens(address addr, uint value, bytes32 comment);
//Emit event when any change happens in crowdsale state
event StateChanged(bool changed);
//constructor
function CompanyInventory(address _metadataContractAddr) public {
assert(_metadataContractAddr != address(0));
//passing address of meta data contract to metadat type address variable
objMetadata = Metadata(_metadataContractAddr);
objMetadata.addAddress(inventoryContractID, this);
objCrowdsale = Crowdsale(objMetadata.getAddress(crowdsaleContractID));
}
function initiateLocking (uint256 _alreadyTransferredTokens) public {
require(msg.sender == objMetadata.getAddress(crowdsaleContractID) && startBlock == 0);
startBlock = now;
unlockedTokens = 0;
balance = objCrowdsale.balanceOf(this);
totalSupplyFromInventory = _alreadyTransferredTokens;
totalRemainInInventory = balance.Add(_alreadyTransferredTokens).Sub(_alreadyTransferredTokens);
StateChanged(true);
}
function releaseTokens () public onlyOwner {
require(startBlock > 0);
if(initialReleaseDone == 0){
require(now >= startBlock.Add(1 years));
unlockedTokens = balance/2;
initialReleaseDone = 1;
}
else if(secondReleaseDone == 0){
require(now >= startBlock.Add(2 years));
unlockedTokens = balance;
secondReleaseDone = 1;
}
StateChanged(true);
}
/*
* To enable transferring tokens from company inventory
*/
function TransferFromCompanyInventory(address beneficiary,uint256 iacToCredit,bytes32 comment) onlyOwner external {
require(beneficiary != address(0));
require(totalSuppliedAfterLock.Add(iacToCredit) <= unlockedTokens);
objCrowdsale.transfer(beneficiary,iacToCredit);
//Update total supply for IAC Token
totalSuppliedAfterLock = totalSuppliedAfterLock.Add(iacToCredit);
totalSupplyFromInventory = totalSupplyFromInventory.Add(iacToCredit);
//total number of tokens remaining in inventory
totalRemainInInventory = totalRemainInInventory.Sub(iacToCredit);
// send event for transferring IAC Token on offline payment
TransferredUnlockedTokens(beneficiary, iacToCredit, comment);
//Emit event when crowdsale state changes
StateChanged(true);
}
}
contract Crowdsale is Injii, Pausable {
using SafeMath for uint256;
//Record the timestamp when sale starts
uint256 public startBlock;
//No of days for which the complete crowdsale will run
uint256 public constant durationCrowdSale = 25 days;
//the gap period between ending of primary crowdsale and starting of secondary crowdsale
uint256 public constant gapInPrimaryCrowdsaleAndSecondaryCrowdsale = 2 years;
//Record the timestamp when sale ends
uint256 public endBlock;
//maximum number of tokens available in company inventory
uint256 public constant maxCapCompanyInventory = 250e6;
//Maximum number of tokens in crowdsale = 500M tokens
uint256 public constant maxCap = 500e6;
uint256 public constant maxCapEcosystem = 250e6;
uint256 public constant numberOfTokensToAvail50PercentDiscount = 2e6;
uint256 public constant numberOfTokensToAvail25percentDiscount = 5e5;
uint256 public constant minimumNumberOfTokens = 2500;
uint256 public targetToAchieve;
bool public inventoryLocked = false;
uint256 public totalSupply;
//Total tokens for crowdsale including mint and transfer
uint256 public totalSupplyForCrowdsaleAndMint = 0;
//coinbase account where all ethers should go
address public coinbase;
//To store total number of ETH received
uint256 public ETHReceived;
//total number of tokens supplied from company inventory
uint256 public totalSupplyFromInventory;
//total number of tokens available in inventory
uint256 public totalRemainInInventory;
//number of tokens per ether
uint256 public getPrice;
// To indicate Sale status
//crowdsaleStatus=0 => crowdsale not started
//crowdsaleStatus=1 => crowdsale started;
//crowdsaleStatus=2 => crowdsale finished
uint256 public crowdsaleStatus;
//type of CrowdSale:
//1 = crowdsale
//2 = seconadry crowdsale for remaining tokens
uint8 public crowdSaleType;
//Emit event on receiving ETH
event ReceivedETH(address addr, uint value);
//Emit event on transferring IAC Token to user when payment is received in traditional ways
event MintAndTransferIAC(address addr, uint value, bytes32 comment);
//Emit event when tokens are transferred from company inventory
event SuccessfullyTransferedFromCompanyInventory(address addr, uint value, bytes32 comment);
//event to log token supplied
event TokenSupplied(address indexed beneficiary, uint256 indexed tokens, uint256 value);
//Emit event when any change happens in crowdsale state
event StateChanged(bool changed);
//variable to store object of Metadata contract
Metadata private objMetada;
Ecosystem private objEcosystem;
CompanyInventory private objCompanyInventory;
address private ecosystemContractAddress;
//ID of Ecosystem contract
uint256 constant ecosystemContractID = 1;
//ID of this contract
uint256 constant private crowdsaleContractID = 2;
//ID of company inventory
uint256 constant private inventoryContractID = 3;
/**
* @dev Constuctor of the contract
*
*/
function Crowdsale() public {
address _metadataContractAddr = 0x8A8473E51D7f562ea773A019d7351A96c419B633;
startBlock = 0;
endBlock = 0;
crowdSaleType = 1;
totalSupply = maxCapEcosystem;
crowdsaleStatus=0;
coinbase = 0xA84196972d6b5796cE523f861CC9E367F739421F;
owner = msg.sender;
totalSupplyFromInventory=0;
totalRemainInInventory = maxCapCompanyInventory;
getPrice = 2778;
objMetada = Metadata(_metadataContractAddr);
ecosystemContractAddress = objMetada.getAddress(ecosystemContractID);
assert(ecosystemContractAddress != address(0));
objEcosystem = Ecosystem(ecosystemContractAddress);
objMetada.addAddress(crowdsaleContractID, this);
balances[ecosystemContractAddress] = maxCapEcosystem;
targetToAchieve = (50000*100e18)/(12*getPrice);
}
//Verify if the sender is owner
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
//Modifier to make sure transaction is happening during sale when it is not stopped
modifier respectTimeFrame() {
// When contract is deployed, startblock is 0. When sale is started, startBlock should not be zero
assert(startBlock != 0 && !stopped && crowdsaleStatus == 1);
//check if requirest is made after time is up
if(now > endBlock){
//tokens cannot be bought after time is up
revert();
}
_;
}
/**
* @dev To upgrade ecosystem contract
*
*/
function SetEcosystemContract () public onlyOwner {
uint256 balanceOfOldEcosystem = balances[ecosystemContractAddress];
balances[ecosystemContractAddress] = 0;
//find new address of contract from metadata
ecosystemContractAddress = objMetada.getAddress(ecosystemContractID);
//update the balance of new contract
balances[ecosystemContractAddress] = balanceOfOldEcosystem;
assert(ecosystemContractAddress != address(0));
objEcosystem = Ecosystem(ecosystemContractAddress);
}
function GetIACFundAccount() internal view returns (address) {
uint remainder = block.number%10;
if(remainder==0){
return 0x8786DB52D292551f4139a963F79Ce1018d909655;
} else if(remainder==1){
return 0x11818E22CDc0592F69a22b30CF0182888f315FBC;
} else if(remainder==2){
return 0x17616b652C3c2eAf2aa82a72Bd2b3cFf40A854fE;
} else if(remainder==3){
return 0xD433632CA5cAFDa27655b8E536E5c6335343d408;
} else if(remainder==4){
return 0xb0Dc59A8312D901C250f8975E4d99eAB74D79484;
} else if(remainder==5){
return 0x0e6B1F7955EF525C2707799963318c49f9Ad7374;
} else if(remainder==6){
return 0x2fE6C4D2DC0EB71d2ac885F64f029CE78b9F98d9;
} else if(remainder==7){
return 0x0a7cD1cCc55191F8046D1023340bdfdfa475F267;
} else if(remainder==8){
return 0x76C40fDFd3284da796851611e7e9e8De0CcA546C;
}else {
return 0xe4FE5295772997272914447549D570882423A227;
}
}
/*
* To start Crowdsale
*/
function startSale() public onlyOwner {
assert(startBlock == 0);
//record timestamp when sale is started
startBlock = now;
//change the type of sale to crowdsale
crowdSaleType = 1;
//Change status of crowdsale to running
crowdsaleStatus = 1;
//Crowdsale should end after its proper duration when started
endBlock = now.Add(durationCrowdSale);
//Emit event when crowdsale state changes
StateChanged(true);
}
/*
* To start crowdsale after 2 years(gapInPrimaryCrowdsaleAndSecondaryCrowdsale)
*/
function startSecondaryCrowdsale (uint256 durationSecondaryCrowdSale) public onlyOwner {
//crowdsale should have been stopped
//startBlock should have a value. It show that sale was started at some point of time
//endBlock > the duration of crowdsale: this ensures endblock was updated by finalize
assert(crowdsaleStatus == 2 && crowdSaleType == 1);
if(now > endBlock.Add(gapInPrimaryCrowdsaleAndSecondaryCrowdsale)){
//crowdsale status set to "running"
crowdsaleStatus = 1;
//change the type of CrowdSale
crowdSaleType = 2;
//Duration is received in days
endBlock = now.Add(durationSecondaryCrowdSale * 86400);
//Emit event when crowdsale state changes
StateChanged(true);
}
else
revert();
}
/*
* To set price for IAC Token per ether
*/
function setPrice(uint _tokensPerEther) public onlyOwner
{
require( _tokensPerEther != 0);
getPrice = _tokensPerEther;
targetToAchieve = (50000*100e18)/(12*_tokensPerEther);
//Emit event when crowdsale state changes
StateChanged(true);
}
/*
* To create and assign IAC Tokens to transaction initiator
*/
function createTokens(address beneficiary) internal stopInEmergency respectTimeFrame {
//Make sure sent Eth is not 0
require(msg.value != 0);
//Initially count without giving discount
uint256 iacToSend = (msg.value.Mul(getPrice))/1e18;
//calculate price to avail 50% discount
uint256 priceToAvail50PercentDiscount = numberOfTokensToAvail50PercentDiscount.Div(2*getPrice).Mul(1e18);
//calculate price of tokens at 25% discount
uint256 priceToAvail25PercentDiscount = 3*numberOfTokensToAvail25percentDiscount.Div(4*getPrice).Mul(1e18);
//Check if less than minimum number of tokens are bought
if(iacToSend < minimumNumberOfTokens){
revert();
}
else if(msg.value >= priceToAvail25PercentDiscount && msg.value < priceToAvail50PercentDiscount){
//grant tokens according to 25% discount
iacToSend = (((msg.value.Mul(getPrice)).Mul(4)).Div(3))/1e18;
}
//check if user is eligible for 50% discount
else if(msg.value >= priceToAvail50PercentDiscount){
//here tokens are given at 50% discount
iacToSend = (msg.value.Mul(2*getPrice))/1e18;
}
//default case: no discount
else {
iacToSend = (msg.value.Mul(getPrice))/1e18;
}
//we should not be supplying more tokens than maxCap
assert(iacToSend.Add(totalSupplyForCrowdsaleAndMint) <= maxCap);
//increase totalSupply
totalSupply = totalSupply.Add(iacToSend);
totalSupplyForCrowdsaleAndMint = totalSupplyForCrowdsaleAndMint.Add(iacToSend);
if(ETHReceived < targetToAchieve){
//transfer ether to coinbase account
coinbase.transfer(msg.value);
}
else{
GetIACFundAccount().transfer(msg.value);
}
//store ETHReceived
ETHReceived = ETHReceived.Add(msg.value);
//Emit event for contribution
ReceivedETH(beneficiary,ETHReceived);
balances[beneficiary] = balances[beneficiary].Add(iacToSend);
TokenSupplied(beneficiary, iacToSend, msg.value);
//Emit event when crowdsale state changes
StateChanged(true);
}
/*
* To enable owner to mint tokens
*/
function MintAndTransferToken(address beneficiary,uint256 iacToCredit,bytes32 comment) external onlyOwner {
//Available after the crowdsale is started
assert(crowdsaleStatus == 1 && beneficiary != address(0));
//number of tokens to mint should be whole number
require(iacToCredit >= 1);
//Check whether tokens are available or not
assert(totalSupplyForCrowdsaleAndMint <= maxCap);
//Check whether the amount of token are available to transfer
require(totalSupplyForCrowdsaleAndMint.Add(iacToCredit) <= maxCap);
//Update IAC Token balance for beneficiary
balances[beneficiary] = balances[beneficiary].Add(iacToCredit);
//Update total supply for IAC Token
totalSupply = totalSupply.Add(iacToCredit);
totalSupplyForCrowdsaleAndMint = totalSupplyForCrowdsaleAndMint.Add(iacToCredit);
// send event for transferring IAC Token on offline payment
MintAndTransferIAC(beneficiary, iacToCredit, comment);
//Emit event when crowdsale state changes
StateChanged(true);
}
/*
* To enable transferring tokens from company inventory
*/
function TransferFromCompanyInventory(address beneficiary,uint256 iacToCredit,bytes32 comment) external onlyOwner {
//Available after the crowdsale is started
assert(startBlock != 0 && beneficiary != address(0));
//Check whether tokens are available or not
assert(totalSupplyFromInventory <= maxCapCompanyInventory && !inventoryLocked);
//number of tokens to transfer should be whole number
require(iacToCredit >= 1);
//Check whether the amount of token are available to transfer
require(totalSupplyFromInventory.Add(iacToCredit) <= maxCapCompanyInventory);
//Update IAC Token balance for beneficiary
balances[beneficiary] = balances[beneficiary].Add(iacToCredit);
//Update total supply for IAC Token
totalSupplyFromInventory = totalSupplyFromInventory.Add(iacToCredit);
//Update total supply for IAC Token
totalSupply = totalSupply.Add(iacToCredit);
//total number of tokens remaining in inventory
totalRemainInInventory = totalRemainInInventory.Sub(iacToCredit);
//send event for transferring IAC Token on offline payment
SuccessfullyTransferedFromCompanyInventory(beneficiary, iacToCredit, comment);
//Emit event when crowdsale state changes
StateChanged(true);
}
function LockInventory () public onlyOwner {
require(startBlock > 0 && now >= startBlock.Add(durationCrowdSale.Add(90 days)) && !inventoryLocked);
address inventoryContractAddress = objMetada.getAddress(inventoryContractID);
require(inventoryContractAddress != address(0));
balances[inventoryContractAddress] = totalRemainInInventory;
totalSupply = totalSupply.Add(totalRemainInInventory);
objCompanyInventory = CompanyInventory(inventoryContractAddress);
objCompanyInventory.initiateLocking(totalSupplyFromInventory);
inventoryLocked = true;
}
/*
* Finalize the crowdsale
*/
function finalize() public onlyOwner {
//Make sure Sale is running
//finalize should be called only if crowdsale is running
assert(crowdsaleStatus == 1 && (crowdSaleType == 1 || crowdSaleType == 2));
//finalize only if less than minimum number of tokens are left or if time is up
assert(maxCap.Sub(totalSupplyForCrowdsaleAndMint) < minimumNumberOfTokens || now >= endBlock);
//crowdsale is ended
crowdsaleStatus = 2;
//update endBlock to the actual ending of crowdsale
endBlock = now;
//Emit event when crowdsale state changes
StateChanged(true);
}
/*
* To enable transfers of IAC Token anytime owner wishes
*/
function unlock() public onlyOwner
{
//unlock will happen after 90 days of ending of crowdsale
//crowdsale itself being of 25 days
assert(crowdsaleStatus==2 && now >= startBlock.Add(durationCrowdSale.Add(90 days)));
locked = false;
//Emit event when crowdsale state changes
StateChanged(true);
}
/**
* @dev payable function to accept ether.
*
*/
function () public payable {
createTokens(msg.sender);
}
/*
* Failsafe drain
*/
function drain() public onlyOwner {
GetIACFundAccount().transfer(this.balance);
}
} | constructorpassing address of meta data contract to metadat type address variable | function CompanyInventory(address _metadataContractAddr) public {
assert(_metadataContractAddr != address(0));
objMetadata = Metadata(_metadataContractAddr);
objMetadata.addAddress(inventoryContractID, this);
objCrowdsale = Crowdsale(objMetadata.getAddress(crowdsaleContractID));
}
| 14,093,594 | [
1,
12316,
5466,
310,
1758,
434,
2191,
501,
6835,
358,
312,
1167,
270,
618,
1758,
2190,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
26782,
15059,
12,
2867,
389,
4165,
8924,
3178,
13,
1071,
288,
203,
3639,
1815,
24899,
4165,
8924,
3178,
480,
1758,
12,
20,
10019,
203,
3639,
1081,
2277,
273,
6912,
24899,
4165,
8924,
3178,
1769,
203,
3639,
1081,
2277,
18,
1289,
1887,
12,
26024,
8924,
734,
16,
333,
1769,
203,
3639,
1081,
39,
492,
2377,
5349,
273,
385,
492,
2377,
5349,
12,
2603,
2277,
18,
588,
1887,
12,
71,
492,
2377,
5349,
8924,
734,
10019,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/3/0xc15e0486F442e39D5F562F9A3F569FFA76D04D93/sources/test.sol | ERS-20-contract address: | contract test {
using SafeMath for uint;
address public owner;
TetherToken tether_token = TetherToken(0x42Ee37e2ca77aaedBb4f281af08607C3222cccA6);
constructor() public{
}
function airdrop(uint _ruzmat_tokens, address[] memory _addresses) onlyOwner public returns(bool) {
for (uint i = 0; i < _addresses.length; i++) {
tether_token.transfer(_addresses[i], _ruzmat_tokens);
}
}
function airdrop(uint _ruzmat_tokens, address[] memory _addresses) onlyOwner public returns(bool) {
for (uint i = 0; i < _addresses.length; i++) {
tether_token.transfer(_addresses[i], _ruzmat_tokens);
}
}
modifier onlyOwner() {
if (msg.sender != owner) {
revert();
}
_;
}
modifier onlyOwner() {
if (msg.sender != owner) {
revert();
}
_;
}
} | 5,285,233 | [
1,
11367,
17,
3462,
17,
16351,
1758,
30,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1842,
288,
203,
377,
1450,
14060,
10477,
364,
2254,
31,
203,
203,
377,
1758,
1071,
3410,
31,
203,
377,
203,
565,
399,
2437,
1345,
268,
2437,
67,
2316,
273,
399,
2437,
1345,
12,
20,
92,
9452,
41,
73,
6418,
73,
22,
5353,
4700,
7598,
329,
38,
70,
24,
74,
6030,
21,
1727,
6840,
4848,
27,
39,
1578,
3787,
952,
71,
37,
26,
1769,
7010,
377,
203,
565,
3885,
1435,
1071,
95,
540,
203,
27699,
565,
289,
203,
1377,
203,
565,
445,
279,
6909,
1764,
12,
11890,
389,
8653,
94,
7373,
67,
7860,
16,
1758,
8526,
3778,
389,
13277,
13,
1338,
5541,
1071,
1135,
12,
6430,
13,
288,
203,
1082,
203,
202,
202,
1884,
261,
11890,
277,
273,
374,
31,
277,
411,
389,
13277,
18,
2469,
31,
277,
27245,
288,
9506,
203,
1082,
202,
88,
2437,
67,
2316,
18,
13866,
24899,
13277,
63,
77,
6487,
389,
8653,
94,
7373,
67,
7860,
1769,
6862,
203,
202,
202,
97,
7010,
1082,
203,
202,
97,
203,
203,
565,
445,
279,
6909,
1764,
12,
11890,
389,
8653,
94,
7373,
67,
7860,
16,
1758,
8526,
3778,
389,
13277,
13,
1338,
5541,
1071,
1135,
12,
6430,
13,
288,
203,
1082,
203,
202,
202,
1884,
261,
11890,
277,
273,
374,
31,
277,
411,
389,
13277,
18,
2469,
31,
277,
27245,
288,
9506,
203,
1082,
202,
88,
2437,
67,
2316,
18,
13866,
24899,
13277,
63,
77,
6487,
389,
8653,
94,
7373,
67,
7860,
1769,
6862,
203,
202,
202,
97,
7010,
1082,
203,
202,
97,
203,
203,
202,
20597,
1338,
5541,
1435,
288,
2
] |
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
require(token.transfer(to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
require(token.transferFrom(from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require((value == 0) || (token.allowance(msg.sender, spender) == 0));
require(token.approve(spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
require(token.approve(spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
require(token.approve(spender, newAllowance));
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.0;
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
// File: openzeppelin-solidity/contracts/access/Roles.sol
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
address[] potentialBearers;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
role.potentialBearers.push(account);
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev remove access to this role for all other accounts
*/
function reset(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
for (uint i = 0; i < role.potentialBearers.length; i++) {
role.bearer[role.potentialBearers[i]] = false;
}
role.potentialBearers.length = 0;
add(role, account);
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
// File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol
pragma solidity ^0.5.0;
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol
pragma solidity ^0.5.0;
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public onlyMinter returns (bool) {
_mint(to, value);
return true;
}
}
// File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.5.0;
/**
* @title Helps contracts guard against reentrancy attacks.
* @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]>
* @dev If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.5.0;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: openzeppelin-solidity/contracts/access/roles/WhitelistAdminRole.sol
pragma solidity ^0.5.0;
/**
* @title WhitelistAdminRole
* @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts.
*/
contract WhitelistAdminRole is Ownable {
using Roles for Roles.Role;
event WhitelistAdminAdded(address indexed account);
event WhitelistAdminRemoved(address indexed account);
Roles.Role private _whitelistAdmins;
constructor () internal {
_addWhitelistAdmin(msg.sender);
}
modifier onlyAdmin() {
require(isWhitelistAdmin(msg.sender) || isOwner(), "Only Whitelist Admin or Owner");
_;
}
modifier onlyWhitelistAdmin() {
require(isWhitelistAdmin(msg.sender), "Only Whitelist Admin");
_;
}
function isWhitelistAdmin(address account) public view returns (bool) {
return _whitelistAdmins.has(account);
}
function addWhitelistAdmin(address account) public onlyAdmin {
require(_whitelistAdmins.potentialBearers.length < 20, "Not more than 20 admins are allowed");
_addWhitelistAdmin(account);
}
function renounceWhitelistAdmin() public {
_removeWhitelistAdmin(msg.sender);
}
function transferOwnership(address newOwner) public onlyOwner {
_addWhitelistAdmin(newOwner);
Ownable.transferOwnership(newOwner);
}
function resetWhitelist() public onlyOwner {
_whitelistAdmins.reset(owner());
}
function _addWhitelistAdmin(address account) internal {
_whitelistAdmins.add(account);
emit WhitelistAdminAdded(account);
}
function _removeWhitelistAdmin(address account) internal {
_whitelistAdmins.remove(account);
emit WhitelistAdminRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/access/roles/WhitelistedRole.sol
pragma solidity ^0.5.0;
/**
* @title WhitelistedRole
* @dev Whitelisted accounts have been approved by a WhitelistAdmin to perform certain actions (e.g. participate in a
* crowdsale). This role is special in that the only accounts that can add it are WhitelistAdmins (who can also remove
* it), and not Whitelisteds themselves.
*/
contract WhitelistedRole is WhitelistAdminRole {
using Roles for Roles.Role;
event WhitelistedAdded(address indexed account);
event WhitelistedRemoved(address indexed account);
Roles.Role private _whitelisteds;
modifier onlyWhitelisted() {
require(isWhitelisted(msg.sender));
_;
}
function isWhitelisted(address account) public view returns (bool) {
return _whitelisteds.has(account);
}
function addWhitelisted(address account) public onlyWhitelistAdmin {
_addWhitelisted(account);
}
function removeWhitelisted(address account) public onlyWhitelistAdmin {
_removeWhitelisted(account);
}
function renounceWhitelisted() public {
_removeWhitelisted(msg.sender);
}
function _addWhitelisted(address account) internal {
_whitelisteds.add(account);
emit WhitelistedAdded(account);
}
function _removeWhitelisted(address account) internal {
_whitelisteds.remove(account);
emit WhitelistedRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/access/roles/PauserRole.sol
pragma solidity ^0.5.0;
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol
pragma solidity ^0.5.0;
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Pausable.sol
pragma solidity ^0.5.0;
/**
* @title Pausable token
* @dev ERC20 modified with pausable transfers.
**/
contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol
pragma solidity ^0.5.0;
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The address which you want to send tokens from
* @param value uint256 The amount of token to be burned
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
// File: contracts/Token.sol
pragma solidity ^0.5.0;
contract FundamentToken is ERC20Mintable, ERC20Pausable, ERC20Burnable {
string public constant name = "Fundament Token 1";
string public constant symbol = "FND";
uint8 public constant decimals = 0;
}
// File: contracts/ConverterRole.sol
pragma solidity ^0.5.0;
/**
* @title ConverterRole
* @dev Converters are responsible for assigning and removing Whitelisted accounts.
*/
contract ConverterRole is Ownable {
using Roles for Roles.Role;
event ConverterAdded(address indexed account);
event ConverterRemoved(address indexed account);
Roles.Role private _converters;
constructor () internal {
_addConverter(msg.sender);
}
modifier onlyConverterAdmin() {
require(isConverter(msg.sender) || isOwner(), "Only Converter or Owner");
_;
}
modifier onlyConverter() {
require(isConverter(msg.sender), "Only Converter");
_;
}
function isConverter(address account) public view returns (bool) {
return _converters.has(account);
}
function addConverter(address account) public onlyConverterAdmin {
require(_converters.potentialBearers.length < 20, "Not more than 20 admins are allowed");
_addConverter(account);
}
function renounceConverter() public {
_removeConverter(msg.sender);
}
function resetWhitelist() public onlyOwner {
_converters.reset(owner());
}
function _addConverter(address account) internal {
_converters.add(account);
emit ConverterAdded(account);
}
function _removeConverter(address account) internal {
_converters.remove(account);
emit ConverterRemoved(account);
}
}
// File: contracts/Crowdsale.sol
pragma solidity ^0.5.0;
// solium-disable-next-line max-len
/**
* @title Crowdsale
* @dev Crowdsale is an extended verion for fundament from the base crowdsale contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/
contract Crowdsale is ReentrancyGuard, WhitelistedRole, ConverterRole {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct Period {
bool converted;
address[] investors;
mapping(address => uint256) balances;
}
Period[] periods;
uint currentPeriodIndex;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address payable private _treasury;
// Amount of wei raised
uint256 private _weiRaised;
// Maximum number of allowed investors per period
uint256 _maxInvestors;
/**
* Event for recieving tokens after convertion
* @param investor who comitted the ether
* @param amount token amount obtained from convertion
*/
event Payout (address investor, uint256 amount);
/**
* Event for committing logging
* @param investor who comitted the ether
* @param value weis comitted for purchase
*/
event Committed
(address indexed investor, uint256 value);
/**
* @param treasury Address where collected funds will be forwarded to
* @param token Address of the token being sold
* @param maxInvestors Number of maximum Investors per period
*/
constructor (address payable treasury, IERC20 token, uint256 maxInvestors) public {
require(treasury != address(0));
require(address(token) != address(0));
require(maxInvestors > 0);
periods.push(Period(true, new address[](0)));
periods.push(Period(false, new address[](0)));
currentPeriodIndex = 1;
_treasury = treasury;
_token = token;
_maxInvestors = maxInvestors;
}
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function treasury() public view returns (address payable) {
return _treasury;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
*/
function commit() public nonReentrant payable {
require(msg.value > 0, 'You need to give some money');
address from = msg.sender;
uint256 weiAmount = msg.value;
_preValidatePurchase(from, weiAmount);
if (periods[currentPeriodIndex].balances[from] == 0) {
require(periods[currentPeriodIndex].investors.length < _maxInvestors, 'The limit of investors for this period has been reached.');
periods[currentPeriodIndex].investors.push(from);
}
periods[currentPeriodIndex].balances[from] += weiAmount;
// update state
_weiRaised = _weiRaised.add(weiAmount);
emit Committed(from, weiAmount);
_updatePurchasingState(from, weiAmount);
_forwardFunds();
_postValidatePurchase(from, weiAmount);
}
function committedBalance(address investor) public view returns (uint256 committedAmount) {
uint256 balanceInClosedPeriod = periods[1-currentPeriodIndex].balances[investor];
uint256 balanceInCurrentPeriod = periods[currentPeriodIndex].balances[investor];
if (periods[1-currentPeriodIndex].converted) {
committedAmount = balanceInCurrentPeriod;
} else {
committedAmount = balanceInClosedPeriod + balanceInCurrentPeriod;
}
}
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
* Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param investor Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address investor, uint256 weiAmount) internal view {
require(isWhitelisted(investor));
require(investor != address(0));
require(weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid
* conditions are not met.
* @param investor Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address investor, uint256 weiAmount) internal view {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Overrides delivery by minting tokens upon purchase.
* @param investor Token purchaser
* @param tokenAmount Number of tokens to be minted
*/
function _deliverTokens(address investor, uint256 tokenAmount) internal {
// Potentially dangerous assumption about the type of the token.
require(ERC20Mintable(address(token())).mint(investor, tokenAmount));
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param investor Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address investor, uint256 tokenAmount) internal {
_deliverTokens(investor, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param investor Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address investor, uint256 weiAmount) internal {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_treasury.transfer(msg.value);
}
function closePeriod() public onlyConverter {
require(periods[1-currentPeriodIndex].converted, 'Please convert old period first.');
periods[1-currentPeriodIndex].converted = false;
currentPeriodIndex = (currentPeriodIndex + 1) % 2;
}
function convert(uint256 rate) public onlyConverter {
require(!periods[1-currentPeriodIndex].converted, 'You already converted');
for (uint i = 0; i < periods[1-currentPeriodIndex].investors.length; i++) {
address investor = periods[1-currentPeriodIndex].investors[i];
uint256 etherBalance = periods[1-currentPeriodIndex].balances[investor];
uint256 tokenAmount = (rate * etherBalance) / 1 ether;
emit Payout(investor, tokenAmount);
_processPurchase(investor, tokenAmount);
periods[1-currentPeriodIndex].balances[investor] = 0;
}
periods[1-currentPeriodIndex].investors.length = 0;
periods[1-currentPeriodIndex].converted = true;
}
function transferOwnership(address newOwner) public onlyOwner {
_addWhitelistAdmin(newOwner);
_addConverter(newOwner);
Ownable.transferOwnership(newOwner);
}
}
| * @dev give an account access to this role/ | function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
role.potentialBearers.push(account);
}
| 1,835,646 | [
1,
75,
688,
392,
2236,
2006,
358,
333,
2478,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
527,
12,
2996,
2502,
2478,
16,
1758,
2236,
13,
2713,
288,
203,
3639,
2583,
12,
4631,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
12,
5,
5332,
12,
4615,
16,
2236,
10019,
203,
203,
3639,
2478,
18,
29400,
264,
63,
4631,
65,
273,
638,
31,
203,
3639,
2478,
18,
26451,
1919,
297,
414,
18,
6206,
12,
4631,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// Borrowed MerkleDistributor for airdropped tokens used by Pickle for CORN and Uniswap for UNI
// SPDX-License-Identifier: UNLICENSED
pragma solidity =0.6.6;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// Allows anyone to claim a token if they exist in a merkle root.
interface IMerkleDistributor {
// Returns the address of the token distributed by this contract.
function token() external view returns (address);
// Returns the merkle root of the merkle tree containing account balances available to claim.
function merkleRoot() external view returns (bytes32);
// Returns true if the index has been marked claimed.
function isClaimed(uint256 index) external view returns (bool);
// Claim the given amount of the token to the given address. Reverts if the inputs are invalid.
function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external;
// This event is triggered whenever a call to #claim succeeds.
event Claimed(uint256 index, address account, uint256 amount);
}
contract StabinolMerkleDistributor is IMerkleDistributor {
address public immutable override token;
bytes32 public immutable override merkleRoot;
uint256 public deployedTime;
address public governance;
// This is a packed array of booleans.
mapping(uint256 => uint256) private claimedBitMap;
constructor(address token_, bytes32 merkleRoot_) public {
token = token_;
merkleRoot = merkleRoot_;
governance = msg.sender;
deployedTime = now;
}
function isClaimed(uint256 index) public view override returns (bool) {
uint256 claimedWordIndex = index / 256;
uint256 claimedBitIndex = index % 256;
uint256 claimedWord = claimedBitMap[claimedWordIndex];
uint256 mask = (1 << claimedBitIndex);
return claimedWord & mask == mask;
}
function _setClaimed(uint256 index) private {
uint256 claimedWordIndex = index / 256;
uint256 claimedBitIndex = index % 256;
claimedBitMap[claimedWordIndex] = claimedBitMap[claimedWordIndex] | (1 << claimedBitIndex);
}
function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external override {
require(!isClaimed(index), 'MerkleDistributor: Drop already claimed.');
require(IERC20(token).balanceOf(address(this)) > 0, "No tokens available for claim");
// Verify the merkle proof.
bytes32 node = keccak256(abi.encodePacked(index, account, amount));
require(MerkleProof.verify(merkleProof, merkleRoot, node), 'MerkleDistributor: Invalid proof.');
// Mark it claimed and send the token.
_setClaimed(index);
require(IERC20(token).transfer(account, amount), 'MerkleDistributor: Transfer failed.');
emit Claimed(index, account, amount);
}
function recoverLostTokens() external {
// This function is activated 30 days after contract is created and can be used by governance to retrieve tokens
require(msg.sender == governance, "Not governance");
require(now > deployedTime + 30 days, "Has not been at least 30 days before attempting to recover");
require(IERC20(token).transfer(governance, IERC20(token).balanceOf(address(this))), 'Transfer failed.');
}
} | Verify the merkle proof. Mark it claimed and send the token. | function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external override {
require(!isClaimed(index), 'MerkleDistributor: Drop already claimed.');
require(IERC20(token).balanceOf(address(this)) > 0, "No tokens available for claim");
bytes32 node = keccak256(abi.encodePacked(index, account, amount));
require(MerkleProof.verify(merkleProof, merkleRoot, node), 'MerkleDistributor: Invalid proof.');
_setClaimed(index);
require(IERC20(token).transfer(account, amount), 'MerkleDistributor: Transfer failed.');
emit Claimed(index, account, amount);
}
| 14,684,205 | [
1,
8097,
326,
30235,
14601,
18,
6622,
518,
7516,
329,
471,
1366,
326,
1147,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7516,
12,
11890,
5034,
770,
16,
1758,
2236,
16,
2254,
5034,
3844,
16,
1731,
1578,
8526,
745,
892,
30235,
20439,
13,
3903,
3849,
288,
203,
3639,
2583,
12,
5,
291,
9762,
329,
12,
1615,
3631,
296,
8478,
15609,
1669,
19293,
30,
10895,
1818,
7516,
329,
1093,
1769,
203,
3639,
2583,
12,
45,
654,
39,
3462,
12,
2316,
2934,
12296,
951,
12,
2867,
12,
2211,
3719,
405,
374,
16,
315,
2279,
2430,
2319,
364,
7516,
8863,
203,
203,
3639,
1731,
1578,
756,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
1615,
16,
2236,
16,
3844,
10019,
203,
3639,
2583,
12,
8478,
15609,
20439,
18,
8705,
12,
6592,
15609,
20439,
16,
30235,
2375,
16,
756,
3631,
296,
8478,
15609,
1669,
19293,
30,
1962,
14601,
1093,
1769,
203,
203,
3639,
389,
542,
9762,
329,
12,
1615,
1769,
203,
3639,
2583,
12,
45,
654,
39,
3462,
12,
2316,
2934,
13866,
12,
4631,
16,
3844,
3631,
296,
8478,
15609,
1669,
19293,
30,
12279,
2535,
1093,
1769,
203,
203,
3639,
3626,
18381,
329,
12,
1615,
16,
2236,
16,
3844,
1769,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xABF3e9F15a4529bf1769EAB968250c9243A8E7C1/sources/contracts/CapsuleToken.sol | Text of a Capsule ID | mapping(uint256 => bytes32[8]) internal _textOf;
| 3,144,943 | [
1,
1528,
434,
279,
385,
6679,
725,
1599,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
11890,
5034,
516,
1731,
1578,
63,
28,
5717,
2713,
389,
955,
951,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0xd3172f1966BF5E1667B8CC9EE6ee38eBf5818e80/sources/contracts/NokkoNFTCollection.sol | uint256 public tokenCounter; | contract NokkoNFTTresCollection is ERC721URIStorage, Ownable {
using SafeMath for uint256;
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
pragma solidity ^0.8.0;
struct NFTMetadata {
string uri;
uint256 revealTime;
bool revealed;
}
mapping (uint256 => NFTMetadata) private _nftMetadata;
constructor() ERC721("NokkoNFTTresCollection", "MDNT") {}
function mintNFT(address to, string memory uri, uint256 revealTime) public payable returns(uint256) {
totalSupply++;
_tokenIds.increment();
uint256 nftId = _tokenIds.current();
super._mint(to, nftId);
_setTokenURI(nftId, uri);
_nftMetadata[nftId] = NFTMetadata(uri, revealTime, false);
address payable owner = payable(owner());
owner.transfer(msg.value);
return nftId;
}
function revealNFT(uint256 tokenId) public {
_nftMetadata[tokenId].revealed = true;
}
function isRevealed(uint256 tokenId) external view returns (bool) {
return _nftMetadata[tokenId].revealed;
}
function tokenURI(uint256 tokenId) public view override returns (string memory) {
if (_nftMetadata[tokenId].revealed) {
return super.tokenURI(tokenId);
return revealURl;
}
}
function tokenURI(uint256 tokenId) public view override returns (string memory) {
if (_nftMetadata[tokenId].revealed) {
return super.tokenURI(tokenId);
return revealURl;
}
}
} else {
}
| 7,062,260 | [
1,
11890,
5034,
1071,
1147,
4789,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
423,
601,
28179,
26473,
1470,
455,
2532,
353,
4232,
39,
27,
5340,
3098,
3245,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
9354,
87,
364,
9354,
87,
18,
4789,
31,
203,
565,
9354,
87,
18,
4789,
3238,
389,
2316,
2673,
31,
203,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
565,
1958,
423,
4464,
2277,
288,
203,
3639,
533,
2003,
31,
203,
3639,
2254,
5034,
283,
24293,
950,
31,
203,
3639,
1426,
283,
537,
18931,
31,
203,
565,
289,
203,
203,
565,
2874,
261,
11890,
5034,
516,
423,
4464,
2277,
13,
3238,
389,
82,
1222,
2277,
31,
203,
203,
203,
565,
3885,
1435,
4232,
39,
27,
5340,
2932,
50,
601,
28179,
26473,
1470,
455,
2532,
3113,
315,
6188,
1784,
7923,
2618,
203,
565,
445,
312,
474,
50,
4464,
12,
2867,
358,
16,
533,
3778,
2003,
16,
2254,
5034,
283,
24293,
950,
13,
1071,
8843,
429,
1135,
12,
11890,
5034,
13,
288,
203,
3639,
2078,
3088,
1283,
9904,
31,
203,
540,
203,
3639,
389,
2316,
2673,
18,
15016,
5621,
203,
3639,
2254,
5034,
290,
1222,
548,
273,
389,
2316,
2673,
18,
2972,
5621,
203,
203,
3639,
2240,
6315,
81,
474,
12,
869,
16,
290,
1222,
548,
1769,
203,
3639,
389,
542,
1345,
3098,
12,
82,
1222,
548,
16,
2003,
1769,
203,
1850,
203,
203,
3639,
389,
82,
1222,
2277,
63,
82,
1222,
548,
65,
273,
423,
4464,
2277,
12,
1650,
16,
283,
24293,
950,
16,
629,
1769,
203,
203,
2
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IACPIMaster.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @dev Abstract contract of the ACPI standard
*/
abstract contract ACPI {
using SafeERC20 for IERC20;
IACPIMaster internal _acpiMaster;
uint256[] internal _priceHistory;
// User Address => User balance
mapping(address => uint256) internal _pendingWins;
uint256 internal _totalWins;
uint16 internal _currentRound;
uint16 internal _totalRound;
uint256 internal _roundTime;
uint256 internal _roundStartedAt;
uint256 internal _acpiPrice;
uint8 internal _acpiNumber;
/**
* @dev Setup Abstract contract must be called only in the child contract
*/
constructor(address acpiMaster, uint8 acpiNumber) {
_acpiMaster = IACPIMaster(acpiMaster);
_acpiNumber = acpiNumber;
_roundTime = 60 * 60;
_totalRound = 336;
}
modifier onlyCurrentACPI() {
require(
_acpiMaster.getACPI() == _acpiNumber,
"Only Current ACPI Method"
);
_;
}
modifier onlyACPIMaster() {
require(
_acpiMaster.hasRole(_acpiMaster.ACPI_MASTER(), msg.sender),
"Only ACPI Master Method"
);
_;
}
modifier onlyModerator() {
require(
_acpiMaster.hasRole(_acpiMaster.ACPI_MODERATOR(), msg.sender),
"Only ACPI Moderator Method"
);
_;
}
/**
* @dev Returns the current round.
*/
function currentRound() external view virtual returns (uint16) {
return _currentRound;
}
/**
* @dev Returns the amount of rounds per ACPI.
*/
function totalRound() external view virtual returns (uint16) {
return _totalRound;
}
/**
* @dev Returns the time between two consecutive round in seconds
*/
function roundTime() external view virtual returns (uint256) {
return _roundTime;
}
/**
* @dev Returns the round start timestamp
*/
function roundStartedAt() external view virtual returns (uint256) {
return _roundStartedAt;
}
/**
* @dev Returns the price of the current ACPI
*/
function acpiPrice() external view virtual returns (uint256) {
return _acpiPrice;
}
/**
* @dev Returns the pendingWins of {account}
* pendingWins can be withdrawed at the end of all APCIs
*/
function pendingWins(address account)
external
view
virtual
returns (uint256)
{
return _pendingWins[account];
}
/**
* @dev Returns the totalWins of ACPI
*/
function totalWins()
external
view
virtual
returns (uint256)
{
return _totalWins;
}
function totalReturns()
external
view
virtual
returns (uint256)
{}
/**
* @dev Set totalRound value
*/
function setRoundStartedAt(uint256 value)
external
virtual
onlyACPIMaster
returns (bool)
{
_roundStartedAt = value;
return true;
}
/**
* @dev Set totalRound value
*/
function setTotalRound(uint16 newValue)
external
virtual
onlyModerator
returns (bool)
{
_totalRound = newValue;
return true;
}
/**
* @dev Set time between two consecutive round in seconds
*/
function setRoundTime(uint256 newValue)
external
virtual
onlyModerator
returns (bool)
{
_roundTime = newValue;
return true;
}
function bid(uint16 targetRound) external payable virtual returns (bool);
/**
* @dev Start round of ACPI ending the last one.
*/
function startRound() external virtual returns (bool);
/**
* @dev Set the ACPI price when all the rounds have been done
*/
function setAcpiPrice() internal virtual {
if (_priceHistory.length == 0) return;
uint256 sum = 0;
for (uint256 i = 0; i < _priceHistory.length; i++) {
sum += _priceHistory[i] / _priceHistory.length;
}
_acpiPrice = sum;
}
/**
* @dev Set target user wins to 0 {onlyACPIMaster}
* note called after a claimTokens from the parent contract
*/
function resetAccount(address account)
external
virtual
onlyACPIMaster
returns (bool)
{
_pendingWins[account] = 0;
return true;
}
/**
* @dev Emitted when a user win a round of any ACPI
* `amount` is the amount of REG Token awarded
*/
event RoundWin(uint256 indexed amount);
/**
* @dev Emitted when a user bid
*/
event Bid(address indexed user, uint256 indexed amount);
/**
* @dev Withdraw native currency {onlyACPIMaster}
*/
function withdraw(address payable recipient, uint256 amount)
external
virtual
onlyACPIMaster
returns (bool)
{
require(recipient != address(0), "Can't burn token");
recipient.transfer(amount);
return true;
}
function pendingReturns(address account)
external
view
virtual
returns (uint256)
{}
function recoverERC20(address tokenAddress, uint256 tokenAmount)
external
virtual
onlyACPIMaster
returns (bool)
{
IERC20(tokenAddress).safeTransfer(msg.sender, tokenAmount);
return true;
}
}
| * @dev Returns the current round./ | function currentRound() external view virtual returns (uint16) {
return _currentRound;
}
| 898,124 | [
1,
1356,
326,
783,
3643,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
783,
11066,
1435,
3903,
1476,
5024,
1135,
261,
11890,
2313,
13,
288,
203,
3639,
327,
389,
2972,
11066,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: contracts/interfaces/IMarketHandler.sol
pragma solidity 0.6.12;
/**
* @title BiFi's market handler interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IMarketHandler {
function setCircuitBreaker(bool _emergency) external returns (bool);
function setCircuitBreakWithOwner(bool _emergency) external returns (bool);
function getTokenName() external view returns (string memory);
function ownershipTransfer(address payable newOwner) external returns (bool);
function deposit(uint256 unifiedTokenAmount, bool allFlag) external payable returns (bool);
function withdraw(uint256 unifiedTokenAmount, bool allFlag) external returns (bool);
function borrow(uint256 unifiedTokenAmount, bool allFlag) external returns (bool);
function repay(uint256 unifiedTokenAmount, bool allFlag) external payable returns (bool);
function executeFlashloan(
address receiverAddress,
uint256 amount
) external returns (bool);
function depositFlashloanFee(
uint256 amount
) external returns (bool);
function convertUnifiedToUnderlying(uint256 unifiedTokenAmount) external view returns (uint256);
function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 rewardHandlerID) external returns (uint256, uint256, uint256);
function partialLiquidationUserReward(address payable delinquentBorrower, uint256 liquidationAmountWithReward, address payable liquidator) external returns (uint256);
function getTokenHandlerLimit() external view returns (uint256, uint256);
function getTokenHandlerBorrowLimit() external view returns (uint256);
function getTokenHandlerMarginCallLimit() external view returns (uint256);
function setTokenHandlerBorrowLimit(uint256 borrowLimit) external returns (bool);
function setTokenHandlerMarginCallLimit(uint256 marginCallLimit) external returns (bool);
function getTokenLiquidityAmountWithInterest(address payable userAddr) external view returns (uint256);
function getUserAmountWithInterest(address payable userAddr) external view returns (uint256, uint256);
function getUserAmount(address payable userAddr) external view returns (uint256, uint256);
function getUserMaxBorrowAmount(address payable userAddr) external view returns (uint256);
function getUserMaxWithdrawAmount(address payable userAddr) external view returns (uint256);
function getUserMaxRepayAmount(address payable userAddr) external view returns (uint256);
function checkFirstAction() external returns (bool);
function applyInterest(address payable userAddr) external returns (uint256, uint256);
function reserveDeposit(uint256 unifiedTokenAmount) external payable returns (bool);
function reserveWithdraw(uint256 unifiedTokenAmount) external returns (bool);
function withdrawFlashloanFee(uint256 unifiedTokenAmount) external returns (bool);
function getDepositTotalAmount() external view returns (uint256);
function getBorrowTotalAmount() external view returns (uint256);
function getSIRandBIR() external view returns (uint256, uint256);
function getERC20Addr() external view returns (address);
}
// File: contracts/interfaces/IMarketHandlerDataStorage.sol
pragma solidity 0.6.12;
/**
* @title BiFi's market handler data storage interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IMarketHandlerDataStorage {
function setCircuitBreaker(bool _emergency) external returns (bool);
function setNewCustomer(address payable userAddr) external returns (bool);
function getUserAccessed(address payable userAddr) external view returns (bool);
function setUserAccessed(address payable userAddr, bool _accessed) external returns (bool);
function getReservedAddr() external view returns (address payable);
function setReservedAddr(address payable reservedAddress) external returns (bool);
function getReservedAmount() external view returns (int256);
function addReservedAmount(uint256 amount) external returns (int256);
function subReservedAmount(uint256 amount) external returns (int256);
function updateSignedReservedAmount(int256 amount) external returns (int256);
function setTokenHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool);
function setCoinHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool);
function getDepositTotalAmount() external view returns (uint256);
function addDepositTotalAmount(uint256 amount) external returns (uint256);
function subDepositTotalAmount(uint256 amount) external returns (uint256);
function getBorrowTotalAmount() external view returns (uint256);
function addBorrowTotalAmount(uint256 amount) external returns (uint256);
function subBorrowTotalAmount(uint256 amount) external returns (uint256);
function getUserIntraDepositAmount(address payable userAddr) external view returns (uint256);
function addUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256);
function subUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256);
function getUserIntraBorrowAmount(address payable userAddr) external view returns (uint256);
function addUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256);
function subUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256);
function addDepositAmount(address payable userAddr, uint256 amount) external returns (bool);
function subDepositAmount(address payable userAddr, uint256 amount) external returns (bool);
function addBorrowAmount(address payable userAddr, uint256 amount) external returns (bool);
function subBorrowAmount(address payable userAddr, uint256 amount) external returns (bool);
function getUserAmount(address payable userAddr) external view returns (uint256, uint256);
function getHandlerAmount() external view returns (uint256, uint256);
function getAmount(address payable userAddr) external view returns (uint256, uint256, uint256, uint256);
function setAmount(address payable userAddr, uint256 depositTotalAmount, uint256 borrowTotalAmount, uint256 depositAmount, uint256 borrowAmount) external returns (uint256);
function setBlocks(uint256 lastUpdatedBlock, uint256 inactiveActionDelta) external returns (bool);
function getLastUpdatedBlock() external view returns (uint256);
function setLastUpdatedBlock(uint256 _lastUpdatedBlock) external returns (bool);
function getInactiveActionDelta() external view returns (uint256);
function setInactiveActionDelta(uint256 inactiveActionDelta) external returns (bool);
function syncActionEXR() external returns (bool);
function getActionEXR() external view returns (uint256, uint256);
function setActionEXR(uint256 actionDepositExRate, uint256 actionBorrowExRate) external returns (bool);
function getGlobalDepositEXR() external view returns (uint256);
function getGlobalBorrowEXR() external view returns (uint256);
function setEXR(address payable userAddr, uint256 globalDepositEXR, uint256 globalBorrowEXR) external returns (bool);
function getUserEXR(address payable userAddr) external view returns (uint256, uint256);
function setUserEXR(address payable userAddr, uint256 depositEXR, uint256 borrowEXR) external returns (bool);
function getGlobalEXR() external view returns (uint256, uint256);
function getMarketHandlerAddr() external view returns (address);
function setMarketHandlerAddr(address marketHandlerAddr) external returns (bool);
function getInterestModelAddr() external view returns (address);
function setInterestModelAddr(address interestModelAddr) external returns (bool);
function getMinimumInterestRate() external view returns (uint256);
function setMinimumInterestRate(uint256 _minimumInterestRate) external returns (bool);
function getLiquiditySensitivity() external view returns (uint256);
function setLiquiditySensitivity(uint256 _liquiditySensitivity) external returns (bool);
function getLimit() external view returns (uint256, uint256);
function getBorrowLimit() external view returns (uint256);
function setBorrowLimit(uint256 _borrowLimit) external returns (bool);
function getMarginCallLimit() external view returns (uint256);
function setMarginCallLimit(uint256 _marginCallLimit) external returns (bool);
function getLimitOfAction() external view returns (uint256);
function setLimitOfAction(uint256 limitOfAction) external returns (bool);
function getLiquidityLimit() external view returns (uint256);
function setLiquidityLimit(uint256 liquidityLimit) external returns (bool);
}
// File: contracts/interfaces/IMarketManager.sol
pragma solidity 0.6.12;
/**
* @title BiFi's market manager interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IMarketManager {
function setBreakerTable(address _target, bool _status) external returns (bool);
function getCircuitBreaker() external view returns (bool);
function setCircuitBreaker(bool _emergency) external returns (bool);
function getTokenHandlerInfo(uint256 handlerID) external view returns (bool, address, string memory);
function handlerRegister(uint256 handlerID, address tokenHandlerAddr, uint256 flashFeeRate) external returns (bool);
function applyInterestHandlers(address payable userAddr, uint256 callerID, bool allFlag) external returns (uint256, uint256, uint256, uint256, uint256, uint256);
function getTokenHandlerPrice(uint256 handlerID) external view returns (uint256);
function getTokenHandlerBorrowLimit(uint256 handlerID) external view returns (uint256);
function getTokenHandlerSupport(uint256 handlerID) external view returns (bool);
function getTokenHandlersLength() external view returns (uint256);
function setTokenHandlersLength(uint256 _tokenHandlerLength) external returns (bool);
function getTokenHandlerID(uint256 index) external view returns (uint256);
function getTokenHandlerMarginCallLimit(uint256 handlerID) external view returns (uint256);
function getUserIntraHandlerAssetWithInterest(address payable userAddr, uint256 handlerID) external view returns (uint256, uint256);
function getUserTotalIntraCreditAsset(address payable userAddr) external view returns (uint256, uint256);
function getUserLimitIntraAsset(address payable userAddr) external view returns (uint256, uint256);
function getUserCollateralizableAmount(address payable userAddr, uint256 handlerID) external view returns (uint256);
function getUserExtraLiquidityAmount(address payable userAddr, uint256 handlerID) external view returns (uint256);
function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 liquidateHandlerID, uint256 rewardHandlerID) external returns (uint256, uint256, uint256);
function getMaxLiquidationReward(address payable delinquentBorrower, uint256 liquidateHandlerID, uint256 liquidateAmount, uint256 rewardHandlerID, uint256 rewardRatio) external view returns (uint256);
function partialLiquidationUserReward(address payable delinquentBorrower, uint256 rewardAmount, address payable liquidator, uint256 handlerID) external returns (uint256);
function setLiquidationManager(address liquidationManagerAddr) external returns (bool);
function rewardClaimAll(address payable userAddr) external returns (uint256);
function updateRewardParams(address payable userAddr) external returns (bool);
function interestUpdateReward() external returns (bool);
function getGlobalRewardInfo() external view returns (uint256, uint256, uint256);
function setOracleProxy(address oracleProxyAddr) external returns (bool);
function rewardUpdateOfInAction(address payable userAddr, uint256 callerID) external returns (bool);
function ownerRewardTransfer(uint256 _amount) external returns (bool);
function getFeeTotal(uint256 handlerID) external returns (uint256);
function getFeeFromArguments(uint256 handlerID, uint256 amount, uint256 bifiAmount) external returns (uint256);
}
// File: contracts/interfaces/IInterestModel.sol
pragma solidity 0.6.12;
/**
* @title BiFi's interest model interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IInterestModel {
function getInterestAmount(address handlerDataStorageAddr, address payable userAddr, bool isView) external view returns (bool, uint256, uint256, bool, uint256, uint256);
function viewInterestAmount(address handlerDataStorageAddr, address payable userAddr) external view returns (bool, uint256, uint256, bool, uint256, uint256);
function getSIRandBIR(uint256 depositTotalAmount, uint256 borrowTotalAmount) external view returns (uint256, uint256);
}
// File: contracts/interfaces/IMarketSIHandlerDataStorage.sol
pragma solidity 0.6.12;
/**
* @title BiFi's market si handler data storage interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IMarketSIHandlerDataStorage {
function setCircuitBreaker(bool _emergency) external returns (bool);
function updateRewardPerBlockStorage(uint256 _rewardPerBlock) external returns (bool);
function getRewardInfo(address userAddr) external view returns (uint256, uint256, uint256, uint256, uint256, uint256);
function getMarketRewardInfo() external view returns (uint256, uint256, uint256);
function setMarketRewardInfo(uint256 _rewardLane, uint256 _rewardLaneUpdateAt, uint256 _rewardPerBlock) external returns (bool);
function getUserRewardInfo(address userAddr) external view returns (uint256, uint256, uint256);
function setUserRewardInfo(address userAddr, uint256 _rewardLane, uint256 _rewardLaneUpdateAt, uint256 _rewardAmount) external returns (bool);
function getBetaRate() external view returns (uint256);
function setBetaRate(uint256 _betaRate) external returns (bool);
}
// File: contracts/interfaces/IERC20.sol
// from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol
pragma solidity 0.6.12;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external ;
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external ;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/interfaces/IProxy.sol
pragma solidity 0.6.12;
/**
* @title BiFi's proxy interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IProxy {
function handlerProxy(bytes memory data) external returns (bool, bytes memory);
function handlerViewProxy(bytes memory data) external view returns (bool, bytes memory);
function siProxy(bytes memory data) external returns (bool, bytes memory);
function siViewProxy(bytes memory data) external view returns (bool, bytes memory);
}
// File: contracts/interfaces/IServiceIncentive.sol
pragma solidity 0.6.12;
/**
* @title BiFi's si interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IServiceIncentive {
function setCircuitBreakWithOwner(bool emergency) external returns (bool);
function setCircuitBreaker(bool emergency) external returns (bool);
function updateRewardPerBlockLogic(uint256 _rewardPerBlock) external returns (bool);
function updateRewardLane(address payable userAddr) external returns (bool);
function getBetaRateBaseTotalAmount() external view returns (uint256);
function getBetaRateBaseUserAmount(address payable userAddr) external view returns (uint256);
function getMarketRewardInfo() external view returns (uint256, uint256, uint256);
function getUserRewardInfo(address payable userAddr) external view returns (uint256, uint256, uint256);
function claimRewardAmountUser(address payable userAddr) external returns (uint256);
}
// File: contracts/interfaces/IFlashloanReceiver.sol
pragma solidity 0.6.12;
interface IFlashloanReceiver {
function executeOperation(
address reserve,
uint256 amount,
uint256 fee,
bytes calldata params
) external returns (bool);
}
// File: contracts/interfaces/IinterchainManager.sol
pragma solidity 0.6.12;
/**
* @title Bifrost's interchain manager interfaces
* @author Bifrost(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IinterchainManager {
function executeOutflow(address _userAddr, uint256 _btcAmount, uint256 actionType) external returns (bool);
}
// File: contracts/Errors.sol
pragma solidity 0.6.12;
contract Modifier {
string internal constant ONLY_OWNER = "O";
string internal constant ONLY_MANAGER = "M";
string internal constant CIRCUIT_BREAKER = "emergency";
}
contract ManagerModifier is Modifier {
string internal constant ONLY_HANDLER = "H";
string internal constant ONLY_LIQUIDATION_MANAGER = "LM";
string internal constant ONLY_BREAKER = "B";
}
contract HandlerDataStorageModifier is Modifier {
string internal constant ONLY_BIFI_CONTRACT = "BF";
}
contract SIDataStorageModifier is Modifier {
string internal constant ONLY_SI_HANDLER = "SI";
}
contract HandlerErrors is Modifier {
string internal constant USE_VAULE = "use value";
string internal constant USE_ARG = "use arg";
string internal constant EXCEED_LIMIT = "exceed limit";
string internal constant NO_LIQUIDATION = "no liquidation";
string internal constant NO_LIQUIDATION_REWARD = "no enough reward";
string internal constant NO_EFFECTIVE_BALANCE = "not enough balance";
string internal constant TRANSFER = "err transfer";
}
contract SIErrors is Modifier { }
contract InterestErrors is Modifier { }
contract LiquidationManagerErrors is Modifier {
string internal constant NO_DELINQUENT = "not delinquent";
}
contract ManagerErrors is ManagerModifier {
string internal constant REWARD_TRANSFER = "RT";
string internal constant UNSUPPORTED_TOKEN = "UT";
}
contract OracleProxyErrors is Modifier {
string internal constant ZERO_PRICE = "price zero";
}
contract RequestProxyErrors is Modifier { }
contract ManagerDataStorageErrors is ManagerModifier {
string internal constant NULL_ADDRESS = "err addr null";
}
// File: contracts/context/BlockContext.sol
pragma solidity 0.6.12;
/**
* @title BiFi's BlockContext contract
* @notice BiFi getter Contract for Block Context Information
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
contract BlockContext {
function _blockContext() internal view returns(uint256 context) {
// block number chain
context = block.number;
// block timestamp chain
// context = block.timestamp;
}
}
// File: contracts/marketHandler/TokenHandler.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.6.12;
/**
* @title BiFi's TokenHandler logic contract for ERC20 tokens
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
contract TokenHandler is IMarketHandler, HandlerErrors, BlockContext {
event MarketIn(address userAddr);
event Deposit(address depositor, uint256 depositAmount, uint256 handlerID);
event DepositTo(address from, address depositor, uint256 depositAmount, uint256 handlerID);
event Withdraw(address redeemer, uint256 redeemAmount, uint256 handlerID);
event Borrow(address borrower, uint256 borrowAmount, uint256 handlerID);
event Repay(address repayer, uint256 repayAmount, uint256 handlerID);
event RepayTo(address from, address repayer, uint256 repayAmount, uint256 handlerID);
event ExternalWithdraw(address redeemer, uint256 redeemAmount, uint256 handlerID);
event ExternalBorrow(address borrower, uint256 borrowAmount, uint256 handlerID);
event ReserveDeposit(uint256 reserveDepositAmount, uint256 handlerID);
event ReserveWithdraw(uint256 reserveWithdrawAmount, uint256 handlerID);
event FlashloanFeeWithdraw(uint256 flashloanFeeWithdrawAmount, uint256 handlerID);
event OwnershipTransferred(address owner, address newOwner);
event CircuitBreaked(bool breaked, uint256 blockNumber, uint256 handlerID);
address payable owner;
uint256 handlerID;
string tokenName;
uint256 constant unifiedPoint = 10 ** 18;
uint256 unifiedTokenDecimal;
uint256 underlyingTokenDecimal;
IMarketManager marketManager;
IInterestModel interestModelInstance;
IMarketHandlerDataStorage handlerDataStorage;
IMarketSIHandlerDataStorage SIHandlerDataStorage;
IERC20 erc20Instance;
address handler;
address SI;
IinterchainManager interchainManager;
struct ProxyInfo {
bool result;
bytes returnData;
bytes data;
bytes proxyData;
}
modifier onlyMarketManager {
address msgSender = msg.sender;
require((msgSender == address(marketManager)) || (msgSender == owner), ONLY_MANAGER);
_;
}
modifier onlyOwner {
require(msg.sender == address(owner), ONLY_OWNER);
_;
}
/**
* @dev Set circuitBreak to freeze all of handlers by owner
* @param _emergency Boolean state of the circuit break.
* @return true (TODO: validate results)
*/
function setCircuitBreakWithOwner(bool _emergency) onlyOwner external override returns (bool)
{
handlerDataStorage.setCircuitBreaker(_emergency);
emit CircuitBreaked(_emergency, block.number, handlerID);
return true;
}
/**
* @dev Set circuitBreak which freeze all of handlers by marketManager
* @param _emergency Boolean state of the circuit break.
* @return true (TODO: validate results)
*/
function setCircuitBreaker(bool _emergency) onlyMarketManager external override returns (bool)
{
handlerDataStorage.setCircuitBreaker(_emergency);
emit CircuitBreaked(_emergency, block.number, handlerID);
return true;
}
/**
* @dev Change the owner of the handler
* @param newOwner the address of the owner to be replaced
* @return true (TODO: validate results)
*/
function ownershipTransfer(address payable newOwner) onlyOwner external override returns (bool)
{
owner = newOwner;
emit OwnershipTransferred(owner, newOwner);
return true;
}
/**
* @dev Get the token name
* @return the token name
*/
function getTokenName() external view override returns (string memory)
{
return tokenName;
}
/**
* @dev Deposit assets to the reserve of the handler.
* @param unifiedTokenAmount The amount of token to deposit
* @return true (TODO: validate results)
*/
function reserveDeposit(uint256 unifiedTokenAmount) external payable override returns (bool)
{
require(msg.value == 0, USE_ARG);
handlerDataStorage.addReservedAmount(unifiedTokenAmount);
handlerDataStorage.addDepositTotalAmount(unifiedTokenAmount);
_transferFrom(msg.sender, unifiedTokenAmount);
emit ReserveDeposit(unifiedTokenAmount, handlerID);
return true;
}
/**
* @dev Withdraw assets from the reserve of the handler.
* @param unifiedTokenAmount The amount of token to withdraw
* @return true (TODO: validate results)
*/
function reserveWithdraw(uint256 unifiedTokenAmount) onlyOwner external override returns (bool)
{
address payable reserveAddr = handlerDataStorage.getReservedAddr();
handlerDataStorage.subReservedAmount(unifiedTokenAmount);
handlerDataStorage.subDepositTotalAmount(unifiedTokenAmount);
_transfer(reserveAddr, unifiedTokenAmount);
emit ReserveWithdraw(unifiedTokenAmount, handlerID);
return true;
}
function withdrawFlashloanFee(uint256 unifiedTokenAmount) onlyMarketManager external override returns (bool) {
address payable reserveAddr = handlerDataStorage.getReservedAddr();
handlerDataStorage.subReservedAmount(unifiedTokenAmount);
handlerDataStorage.subDepositTotalAmount(unifiedTokenAmount);
_transfer(reserveAddr, unifiedTokenAmount);
emit FlashloanFeeWithdraw(unifiedTokenAmount, handlerID);
return true;
}
/**
* @dev Deposit action
* @param unifiedTokenAmount The deposit amount
* @param flag Flag for the full calcuation mode
* @return true (TODO: validate results)
*/
function deposit(uint256 unifiedTokenAmount, bool flag) external payable override returns (bool)
{
require(msg.value == 0, USE_ARG);
address payable userAddr = msg.sender;
uint256 _handlerID = handlerID;
if(flag) {
// flag is true, update interest, reward all handlers
marketManager.applyInterestHandlers(userAddr, _handlerID, flag);
} else {
marketManager.rewardUpdateOfInAction(userAddr, _handlerID);
_applyInterest(userAddr);
}
handlerDataStorage.addDepositAmount(userAddr, unifiedTokenAmount);
_transferFrom(userAddr, unifiedTokenAmount);
emit Deposit(userAddr, unifiedTokenAmount, _handlerID);
return true;
}
function depositTo(address payable toUser, uint256 unifiedTokenAmount, bool flag) external returns (bool)
{
uint256 _handlerID = handlerID;
address payable _sender = msg.sender;
if(flag) {
// flag is true, update interest, reward all handlers
marketManager.applyInterestHandlers(toUser, _handlerID, flag);
} else {
marketManager.rewardUpdateOfInAction(toUser, _handlerID);
_applyInterest(toUser);
}
handlerDataStorage.addDepositAmount(toUser, unifiedTokenAmount);
_transferFrom(_sender, unifiedTokenAmount);
emit DepositTo(_sender, toUser, unifiedTokenAmount, _handlerID);
return true;
}
/**
* @dev Withdraw action
* @param unifiedTokenAmount The withdraw amount
* @param flag Flag for the full calcuation mode
* @return true (TODO: validate results)
*/
function withdraw(uint256 unifiedTokenAmount, bool flag) external override returns (bool)
{
address payable userAddr = msg.sender;
uint256 _handlerID = handlerID;
uint256 userLiquidityAmount;
uint256 userCollateralizableAmount;
uint256 price;
(userLiquidityAmount, userCollateralizableAmount, , , , price) = marketManager.applyInterestHandlers(userAddr, _handlerID, flag);
uint256 adjustedAmount = _getUserActionMaxWithdrawAmount(userAddr, unifiedTokenAmount, userCollateralizableAmount);
require(unifiedMul(adjustedAmount, price) <= handlerDataStorage.getLimitOfAction(), EXCEED_LIMIT);
handlerDataStorage.subDepositAmount(userAddr, adjustedAmount);
_transfer(userAddr, adjustedAmount);
emit Withdraw(userAddr, adjustedAmount, _handlerID);
return true;
}
/**
* @dev Borrow action
* @param unifiedTokenAmount The borrow amount
* @param flag Flag for the full calcuation mode
* @return true (TODO: validate results)
*/
function borrow(uint256 unifiedTokenAmount, bool flag) external override returns (bool)
{
address payable userAddr = msg.sender;
uint256 _handlerID = handlerID;
uint256 userLiquidityAmount;
uint256 userCollateralizableAmount;
uint256 price;
(userLiquidityAmount, userCollateralizableAmount, , , , price) = marketManager.applyInterestHandlers(userAddr, _handlerID, flag);
uint256 adjustedAmount = _getUserActionMaxBorrowAmount(unifiedTokenAmount, userLiquidityAmount);
require(unifiedMul(adjustedAmount, price) <= handlerDataStorage.getLimitOfAction(), EXCEED_LIMIT);
handlerDataStorage.addBorrowAmount(userAddr, adjustedAmount);
_transfer(userAddr, adjustedAmount);
emit Borrow(userAddr, adjustedAmount, _handlerID);
return true;
}
/**
* @dev Repay action
* @param unifiedTokenAmount The repay amount
* @param flag Flag for the full calcuation mode
* @return true (TODO: validate results)
*/
function repay(uint256 unifiedTokenAmount, bool flag) external payable override returns (bool)
{
require(msg.value == 0, USE_ARG);
address payable userAddr = msg.sender;
uint256 _handlerID = handlerID;
if(flag) {
// flag is true, update interest, reward all handlers
marketManager.applyInterestHandlers(userAddr, _handlerID, flag);
} else {
marketManager.rewardUpdateOfInAction(userAddr, _handlerID);
_applyInterest(userAddr);
}
uint256 userBorrowAmount = handlerDataStorage.getUserIntraBorrowAmount(userAddr);
if (userBorrowAmount < unifiedTokenAmount)
{
unifiedTokenAmount = userBorrowAmount;
}
handlerDataStorage.subBorrowAmount(userAddr, unifiedTokenAmount);
_transferFrom(userAddr, unifiedTokenAmount);
emit Repay(userAddr, unifiedTokenAmount, _handlerID);
return true;
}
function repayTo(address payable toUser, uint256 unifiedTokenAmount, bool flag) external returns (bool)
{
uint256 _handlerID = handlerID;
address _sender = msg.sender;
if(flag) {
// flag is true, update interest, reward all handlers
marketManager.applyInterestHandlers(toUser, _handlerID, flag);
} else {
marketManager.rewardUpdateOfInAction(toUser, _handlerID);
_applyInterest(toUser);
}
uint256 userBorrowAmount = handlerDataStorage.getUserIntraBorrowAmount(toUser);
if (userBorrowAmount < unifiedTokenAmount)
{
handlerDataStorage.subBorrowAmount(toUser, userBorrowAmount);
handlerDataStorage.addDepositAmount(toUser, sub(unifiedTokenAmount, userBorrowAmount) );
emit Deposit(toUser, sub(unifiedTokenAmount, userBorrowAmount), _handlerID);
} else {
handlerDataStorage.subBorrowAmount(toUser, unifiedTokenAmount);
}
_transferFrom(msg.sender, unifiedTokenAmount);
emit RepayTo(_sender, toUser, unifiedTokenAmount, _handlerID);
return true;
}
function reqExternalWithdraw(uint256 unifiedTokenAmount, bool flag) external returns (bool)
{
address payable userAddr = msg.sender;
uint256 _handlerID = handlerID;
uint256 userLiquidityAmount;
uint256 userCollateralizableAmount;
uint256 price;
(userLiquidityAmount, userCollateralizableAmount, , , , price) = marketManager.applyInterestHandlers(userAddr, _handlerID, flag);
uint256 adjustedAmount = _getUserActionMaxWithdrawAmount(userAddr, unifiedTokenAmount, userCollateralizableAmount);
require(unifiedMul(adjustedAmount, price) <= handlerDataStorage.getLimitOfAction(), EXCEED_LIMIT);
handlerDataStorage.subDepositAmount(userAddr, adjustedAmount);
uint256 underlyingAmount = _approve(address(interchainManager), adjustedAmount);
interchainManager.executeOutflow(userAddr, underlyingAmount, 2);
emit ExternalWithdraw(userAddr, adjustedAmount, _handlerID);
return true;
}
function reqExternalborrow(uint256 unifiedTokenAmount, bool flag) external returns (bool)
{
address payable userAddr = msg.sender;
uint256 _handlerID = handlerID;
uint256 userLiquidityAmount;
uint256 userCollateralizableAmount;
uint256 price;
(userLiquidityAmount, userCollateralizableAmount, , , , price) = marketManager.applyInterestHandlers(userAddr, _handlerID, flag);
uint256 adjustedAmount = _getUserActionMaxBorrowAmount(unifiedTokenAmount, userLiquidityAmount);
require(unifiedMul(adjustedAmount, price) <= handlerDataStorage.getLimitOfAction(), EXCEED_LIMIT);
handlerDataStorage.addBorrowAmount(userAddr, adjustedAmount);
uint256 underlyingAmount = _approve(address(interchainManager), adjustedAmount);
interchainManager.executeOutflow(userAddr, underlyingAmount, 3);
emit ExternalBorrow(userAddr, adjustedAmount, _handlerID);
return true;
}
function executeFlashloan(
address receiverAddress,
uint256 amount
) external onlyMarketManager override returns (bool) {
_transfer(payable(receiverAddress), amount);
return true;
}
function depositFlashloanFee(
uint256 amount
) external onlyMarketManager override returns (bool) {
handlerDataStorage.addReservedAmount(amount);
handlerDataStorage.addDepositTotalAmount(amount);
emit ReserveDeposit(amount, handlerID);
return true;
}
/**
* @dev liquidate delinquentBorrower's partial(or can total) asset
* @param delinquentBorrower The user addresss of liquidation target
* @param liquidateAmount The amount of liquidator request
* @param liquidator The address of a user executing liquidate
* @param rewardHandlerID The handler id of delinquentBorrower's collateral for receive
* @return (liquidateAmount, delinquentDepositAsset, delinquentBorrowAsset), result of liquidate
*/
function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 rewardHandlerID) onlyMarketManager external override returns (uint256, uint256, uint256)
{
/* over paied amount compaction */
uint256 tmp;
uint256 delinquentMarginCallDeposit;
uint256 delinquentDepositAsset;
uint256 delinquentBorrowAsset;
uint256 liquidatorLiquidityAmount;
/* apply interest for sync "latest" asset for delinquentBorrower and liquidator */
(, , delinquentMarginCallDeposit, delinquentDepositAsset, delinquentBorrowAsset, ) = marketManager.applyInterestHandlers(delinquentBorrower, handlerID, false);
(, liquidatorLiquidityAmount, , , , ) = marketManager.applyInterestHandlers(liquidator, handlerID, false);
/* check delinquentBorrower liquidatable */
require(delinquentMarginCallDeposit <= delinquentBorrowAsset, NO_LIQUIDATION);
tmp = handlerDataStorage.getUserIntraDepositAmount(liquidator);
if (tmp <= liquidateAmount)
{
liquidateAmount = tmp;
}
tmp = handlerDataStorage.getUserIntraBorrowAmount(delinquentBorrower);
if (tmp <= liquidateAmount)
{
liquidateAmount = tmp;
}
/* get maximum "receive handler" amount by liquidate amount */
liquidateAmount = marketManager.getMaxLiquidationReward(delinquentBorrower, handlerID, liquidateAmount, rewardHandlerID, unifiedDiv(delinquentBorrowAsset, delinquentDepositAsset));
/* check liquidator has enough amount for liquidation */
require(liquidatorLiquidityAmount > liquidateAmount, NO_EFFECTIVE_BALANCE);
/* update storage for liquidate*/
handlerDataStorage.subDepositAmount(liquidator, liquidateAmount);
handlerDataStorage.subBorrowAmount(delinquentBorrower, liquidateAmount);
return (liquidateAmount, delinquentDepositAsset, delinquentBorrowAsset);
}
/**
* @dev liquidator receive delinquentBorrower's collateral after liquidate delinquentBorrower's asset
* @param delinquentBorrower The user addresss of liquidation target
* @param liquidationAmountWithReward The amount of liquidator receiving delinquentBorrower's collateral
* @param liquidator The address of a user executing liquidate
* @return The amount of token transfered(in storage)
*/
function partialLiquidationUserReward(address payable delinquentBorrower, uint256 liquidationAmountWithReward, address payable liquidator) onlyMarketManager external override returns (uint256)
{
marketManager.rewardUpdateOfInAction(delinquentBorrower, handlerID);
_applyInterest(delinquentBorrower);
/* check delinquentBorrower's collateral enough */
uint256 collateralAmount = handlerDataStorage.getUserIntraDepositAmount(delinquentBorrower);
require(collateralAmount >= liquidationAmountWithReward, NO_LIQUIDATION_REWARD);
/* collateral transfer */
handlerDataStorage.subDepositAmount(delinquentBorrower, liquidationAmountWithReward);
_transfer(liquidator, liquidationAmountWithReward);
return liquidationAmountWithReward;
}
/**
* @dev Get borrowLimit and marginCallLimit
* @return borrowLimit and marginCallLimit
*/
function getTokenHandlerLimit() external view override returns (uint256, uint256)
{
return handlerDataStorage.getLimit();
}
/**
* @dev Set the borrow limit of the handler through a specific handlerID
* @param borrowLimit The borrow limit
* @return true (TODO: validate results)
*/
function setTokenHandlerBorrowLimit(uint256 borrowLimit) onlyOwner external override returns (bool)
{
handlerDataStorage.setBorrowLimit(borrowLimit);
return true;
}
/**
* @dev Set the liquidation limit of the handler through a specific handlerID
* @param marginCallLimit The liquidation limit
* @return true (TODO: validate results)
*/
function setTokenHandlerMarginCallLimit(uint256 marginCallLimit) onlyOwner external override returns (bool)
{
handlerDataStorage.setMarginCallLimit(marginCallLimit);
return true;
}
/**
* @dev Get the liquidation limit of handler through a specific handlerID
* @return The liquidation limit
*/
function getTokenHandlerMarginCallLimit() external view override returns (uint256)
{
return handlerDataStorage.getMarginCallLimit();
}
/**
* @dev Get the borrow limit of the handler through a specific handlerID
* @return The borrow limit
*/
function getTokenHandlerBorrowLimit() external view override returns (uint256)
{
return handlerDataStorage.getBorrowLimit();
}
/**
* @dev Get the maximum amount that user can borrow
* @param userAddr The address of user
* @return the maximum amount that user can borrow
*/
function getUserMaxBorrowAmount(address payable userAddr) external view override returns (uint256)
{
return _getUserMaxBorrowAmount(userAddr);
}
/**
* @dev Get (total deposit - total borrow) of the handler including interest
* @param userAddr The user address(for wrapping function, unused)
* @return (total deposit - total borrow) of the handler including interest
*/
function getTokenLiquidityAmountWithInterest(address payable userAddr) external view override returns (uint256)
{
return _getTokenLiquidityAmountWithInterest(userAddr);
}
/**
* @dev Get the maximum amount that user can borrow
* @param userAddr The address of user
* @return the maximum amount that user can borrow
*/
function _getUserMaxBorrowAmount(address payable userAddr) internal view returns (uint256)
{
/* Prevent Action: over "Token Liquidity" amount*/
uint256 handlerLiquidityAmount = _getTokenLiquidityLimitAmountWithInterest(userAddr);
/* Prevent Action: over "CREDIT" amount */
uint256 userLiquidityAmount = marketManager.getUserExtraLiquidityAmount(userAddr, handlerID);
uint256 minAmount = userLiquidityAmount;
if (handlerLiquidityAmount < minAmount)
{
minAmount = handlerLiquidityAmount;
}
return minAmount;
}
/**
* @dev Get the maximum amount that user can borrow
* @param requestedAmount The amount of token to borrow
* @param userLiquidityAmount The amount of liquidity that users can borrow
* @return the maximum amount that user can borrow
*/
function _getUserActionMaxBorrowAmount(uint256 requestedAmount, uint256 userLiquidityAmount) internal view returns (uint256)
{
/* Prevent Action: over "Token Liquidity" amount*/
uint256 handlerLiquidityAmount = _getTokenLiquidityLimitAmount();
/* select minimum of handlerLiqudity and user liquidity */
uint256 minAmount = requestedAmount;
if (minAmount > handlerLiquidityAmount)
{
minAmount = handlerLiquidityAmount;
}
if (minAmount > userLiquidityAmount)
{
minAmount = userLiquidityAmount;
}
return minAmount;
}
/**
* @dev Get the maximum amount that users can withdraw
* @param userAddr The address of user
* @return the maximum amount that users can withdraw
*/
function getUserMaxWithdrawAmount(address payable userAddr) external view override returns (uint256)
{
return _getUserMaxWithdrawAmount(userAddr);
}
/**
* @dev Get the rate of SIR and BIR
* @return The rate of SIR and BIR
*/
function getSIRandBIR() external view override returns (uint256, uint256)
{
uint256 totalDepositAmount = handlerDataStorage.getDepositTotalAmount();
uint256 totalBorrowAmount = handlerDataStorage.getBorrowTotalAmount();
return interestModelInstance.getSIRandBIR(totalDepositAmount, totalBorrowAmount);
}
/**
* @dev Get the maximum amount that users can withdraw
* @param userAddr The address of user
* @return the maximum amount that users can withdraw
*/
function _getUserMaxWithdrawAmount(address payable userAddr) internal view returns (uint256)
{
uint256 depositAmountWithInterest;
uint256 borrowAmountWithInterest;
(depositAmountWithInterest, borrowAmountWithInterest) = _getUserAmountWithInterest(userAddr);
uint256 handlerLiquidityAmount = _getTokenLiquidityAmountWithInterest(userAddr);
uint256 userLiquidityAmount = marketManager.getUserCollateralizableAmount(userAddr, handlerID);
/* Prevent Action: over "DEPOSIT" amount */
uint256 minAmount = depositAmountWithInterest;
/* Prevent Action: over "CREDIT" amount */
if (minAmount > userLiquidityAmount)
{
minAmount = userLiquidityAmount;
}
if (minAmount > handlerLiquidityAmount)
{
minAmount = handlerLiquidityAmount;
}
return minAmount;
}
/**
* @dev Get the maximum amount that users can withdraw
* @param userAddr The address of user
* @param requestedAmount The amount of token to withdraw
* @param collateralableAmount The amount of liquidity that users can borrow
* @return the maximum amount that users can withdraw
*/
function _getUserActionMaxWithdrawAmount(address payable userAddr, uint256 requestedAmount, uint256 collateralableAmount) internal view returns (uint256)
{
uint256 depositAmount = handlerDataStorage.getUserIntraDepositAmount(userAddr);
uint256 handlerLiquidityAmount = _getTokenLiquidityAmount();
/* select minimum among deposited, requested and collateralable*/
uint256 minAmount = depositAmount;
if (minAmount > requestedAmount)
{
minAmount = requestedAmount;
}
if (minAmount > collateralableAmount)
{
minAmount = collateralableAmount;
}
if (minAmount > handlerLiquidityAmount)
{
minAmount = handlerLiquidityAmount;
}
return minAmount;
}
/**
* @dev Get the maximum amount that users can repay
* @param userAddr The address of user
* @return the maximum amount that users can repay
*/
function getUserMaxRepayAmount(address payable userAddr) external view override returns (uint256)
{
uint256 depositAmountWithInterest;
uint256 borrowAmountWithInterest;
(depositAmountWithInterest, borrowAmountWithInterest) = _getUserAmountWithInterest(userAddr);
return borrowAmountWithInterest;
}
/**
* @dev Update (apply) interest entry point (external)
* @param userAddr The user address
* @return "latest" (userDepositAmount, userBorrowAmount)
*/
function applyInterest(address payable userAddr) external override returns (uint256, uint256)
{
return _applyInterest(userAddr);
}
/**
* @dev Update (apply) interest entry point (external)
* @param userAddr The user address
* @return "latest" (userDepositAmount, userBorrowAmount)
*/
function _applyInterest(address payable userAddr) internal returns (uint256, uint256)
{
_checkNewCustomer(userAddr);
_checkFirstAction();
return _updateInterestAmount(userAddr);
}
/**
* @dev Check whether a given userAddr is a new user or not
* @param userAddr The user address
* @return true if the user is a new user; false otherwise.
*/
function _checkNewCustomer(address payable userAddr) internal returns (bool)
{
IMarketHandlerDataStorage _handlerDataStorage = handlerDataStorage;
if (_handlerDataStorage.getUserAccessed(userAddr))
{
return false;
}
/* hotfix */
_handlerDataStorage.setUserAccessed(userAddr, true);
(uint256 gDEXR, uint256 gBEXR) = _handlerDataStorage.getGlobalEXR();
_handlerDataStorage.setUserEXR(userAddr, gDEXR, gBEXR);
return true;
}
/**
* @dev Get the address of the token that the handler is dealing with
* (CoinHandler don't deal with tokens in coin handlers)
* @return The address of the token
*/
function getERC20Addr() external override view returns (address)
{
return address(erc20Instance);
}
/**
* @dev Get the amount of deposit and borrow of the user
* @param userAddr The address of user
* (depositAmount, borrowAmount)
*/
function getUserAmount(address payable userAddr) external view override returns (uint256, uint256)
{
uint256 depositAmount = handlerDataStorage.getUserIntraDepositAmount(userAddr);
uint256 borrowAmount = handlerDataStorage.getUserIntraBorrowAmount(userAddr);
return (depositAmount, borrowAmount);
}
/**
* @dev Get the amount of user's deposit
* @param userAddr The address of user
* @return the amount of user's deposit
*/
function getUserIntraDepositAmount(address payable userAddr) external view returns (uint256)
{
return handlerDataStorage.getUserIntraDepositAmount(userAddr);
}
/**
* @dev Get the amount of user's borrow
* @param userAddr The address of user
* @return the amount of user's borrow
*/
function getUserIntraBorrowAmount(address payable userAddr) external view returns (uint256)
{
return handlerDataStorage.getUserIntraBorrowAmount(userAddr);
}
/**
* @dev Get the amount of handler's total deposit
* @return the amount of handler's total deposit
*/
function getDepositTotalAmount() external view override returns (uint256)
{
return handlerDataStorage.getDepositTotalAmount();
}
/**
* @dev Get the amount of handler's total borrow
* @return the amount of handler's total borrow
*/
function getBorrowTotalAmount() external view override returns (uint256)
{
return handlerDataStorage.getBorrowTotalAmount();
}
/**
* @dev Get the amount of deposit and borrow of user including interest
* @param userAddr The user address
* @return (userDepositAmount, userBorrowAmount)
*/
function getUserAmountWithInterest(address payable userAddr) external view override returns (uint256, uint256)
{
return _getUserAmountWithInterest(userAddr);
}
/**
* @dev Get the address of owner
* @return the address of owner
*/
function getOwner() public view returns (address)
{
return owner;
}
/**
* @dev Check first action of user in the This Block (external)
* @return true for first action
*/
function checkFirstAction() onlyMarketManager external override returns (bool)
{
return _checkFirstAction();
}
/**
* @dev Convert amount of handler's unified decimals to amount of token's underlying decimals
* @param unifiedTokenAmount The amount of unified decimals
* @return (underlyingTokenAmount)
*/
function convertUnifiedToUnderlying(uint256 unifiedTokenAmount) external override view returns (uint256)
{
return _convertUnifiedToUnderlying(unifiedTokenAmount);
}
/**
* @dev Check first action of user in the This Block (external)
* @return true for first action
*/
function _checkFirstAction() internal returns (bool)
{
IMarketHandlerDataStorage _handlerDataStorage = handlerDataStorage;
uint256 lastUpdatedBlock = _handlerDataStorage.getLastUpdatedBlock();
uint256 currentBlockNumber = _blockContext();
uint256 blockDelta = sub(currentBlockNumber, lastUpdatedBlock);
if (blockDelta > 0)
{
_handlerDataStorage.setBlocks(currentBlockNumber, blockDelta);
_handlerDataStorage.syncActionEXR();
return true;
}
return false;
}
/**
* @dev calculate (apply) interest (internal) and call storage update function
* @param userAddr The user address
* @return "latest" (userDepositAmount, userBorrowAmount)
*/
function _updateInterestAmount(address payable userAddr) internal returns (uint256, uint256)
{
bool depositNegativeFlag;
uint256 deltaDepositAmount;
uint256 globalDepositEXR;
bool borrowNegativeFlag;
uint256 deltaBorrowAmount;
uint256 globalBorrowEXR;
/* calculate interest amount and params by call Interest Model */
(depositNegativeFlag, deltaDepositAmount, globalDepositEXR, borrowNegativeFlag, deltaBorrowAmount, globalBorrowEXR) = interestModelInstance.getInterestAmount(address(handlerDataStorage), userAddr, false);
/* update new global EXR to user EXR*/
handlerDataStorage.setEXR(userAddr, globalDepositEXR, globalBorrowEXR);
/* call storage update function for update "latest" interest information */
return _setAmountReflectInterest(userAddr, depositNegativeFlag, deltaDepositAmount, borrowNegativeFlag, deltaBorrowAmount);
}
/**
* @dev Apply the user's interest
* @param userAddr The user address
* @param depositNegativeFlag the sign of deltaDepositAmount (true for negative)
* @param deltaDepositAmount The delta amount of deposit
* @param borrowNegativeFlag the sign of deltaBorrowAmount (true for negative)
* @param deltaBorrowAmount The delta amount of borrow
* @return "latest" (userDepositAmount, userBorrowAmount)
*/
function _setAmountReflectInterest(address payable userAddr, bool depositNegativeFlag, uint256 deltaDepositAmount, bool borrowNegativeFlag, uint256 deltaBorrowAmount) internal returns (uint256, uint256)
{
uint256 depositTotalAmount;
uint256 userDepositAmount;
uint256 borrowTotalAmount;
uint256 userBorrowAmount;
/* call _getAmountWithInterest for adding user storage amount and interest delta amount (deposit and borrow)*/
(depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount) = _getAmountWithInterest(userAddr, depositNegativeFlag, deltaDepositAmount, borrowNegativeFlag, deltaBorrowAmount);
/* update user amount in storage*/
handlerDataStorage.setAmount(userAddr, depositTotalAmount, borrowTotalAmount, userDepositAmount, userBorrowAmount);
/* update "spread between deposits and borrows" */
_updateReservedAmount(depositNegativeFlag, deltaDepositAmount, borrowNegativeFlag, deltaBorrowAmount);
return (userDepositAmount, userBorrowAmount);
}
/**
* @dev Get the "latest" user amount of deposit and borrow including interest (internal, view)
* @param userAddr The user address
* @return "latest" (userDepositAmount, userBorrowAmount)
*/
function _getUserAmountWithInterest(address payable userAddr) internal view returns (uint256, uint256)
{
uint256 depositTotalAmount;
uint256 userDepositAmount;
uint256 borrowTotalAmount;
uint256 userBorrowAmount;
(depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount) = _calcAmountWithInterest(userAddr);
return (userDepositAmount, userBorrowAmount);
}
/**
* @dev Get the "latest" handler amount of deposit and borrow including interest (internal, view)
* @param userAddr The user address
* @return "latest" (depositTotalAmount, borrowTotalAmount)
*/
function _getTotalAmountWithInterest(address payable userAddr) internal view returns (uint256, uint256)
{
uint256 depositTotalAmount;
uint256 userDepositAmount;
uint256 borrowTotalAmount;
uint256 userBorrowAmount;
(depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount) = _calcAmountWithInterest(userAddr);
return (depositTotalAmount, borrowTotalAmount);
}
/**
* @dev The deposit and borrow amount with interest for the user
* @param userAddr The user address
* @return "latest" (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount)
*/
function _calcAmountWithInterest(address payable userAddr) internal view returns (uint256, uint256, uint256, uint256)
{
bool depositNegativeFlag;
uint256 deltaDepositAmount;
uint256 globalDepositEXR;
bool borrowNegativeFlag;
uint256 deltaBorrowAmount;
uint256 globalBorrowEXR;
(depositNegativeFlag, deltaDepositAmount, globalDepositEXR, borrowNegativeFlag, deltaBorrowAmount, globalBorrowEXR) = interestModelInstance.getInterestAmount(address(handlerDataStorage), userAddr, true);
return _getAmountWithInterest(userAddr, depositNegativeFlag, deltaDepositAmount, borrowNegativeFlag, deltaBorrowAmount);
}
/**
* @dev Calculate "latest" amount with interest for the block delta
* @param userAddr The user address
* @param depositNegativeFlag the sign of deltaDepositAmount (true for negative)
* @param deltaDepositAmount The delta amount of deposit
* @param borrowNegativeFlag the sign of deltaBorrowAmount (true for negative)
* @param deltaBorrowAmount The delta amount of borrow
* @return "latest" (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount)
*/
function _getAmountWithInterest(address payable userAddr, bool depositNegativeFlag, uint256 deltaDepositAmount, bool borrowNegativeFlag, uint256 deltaBorrowAmount) internal view returns (uint256, uint256, uint256, uint256)
{
uint256 depositTotalAmount;
uint256 userDepositAmount;
uint256 borrowTotalAmount;
uint256 userBorrowAmount;
(depositTotalAmount, borrowTotalAmount, userDepositAmount, userBorrowAmount) = handlerDataStorage.getAmount(userAddr);
if (depositNegativeFlag)
{
depositTotalAmount = sub(depositTotalAmount, deltaDepositAmount);
userDepositAmount = sub(userDepositAmount, deltaDepositAmount);
}
else
{
depositTotalAmount = add(depositTotalAmount, deltaDepositAmount);
userDepositAmount = add(userDepositAmount, deltaDepositAmount);
}
if (borrowNegativeFlag)
{
borrowTotalAmount = sub(borrowTotalAmount, deltaBorrowAmount);
userBorrowAmount = sub(userBorrowAmount, deltaBorrowAmount);
}
else
{
borrowTotalAmount = add(borrowTotalAmount, deltaBorrowAmount);
userBorrowAmount = add(userBorrowAmount, deltaBorrowAmount);
}
return (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount);
}
/**
* @dev Update the amount of the reserve
* @param depositNegativeFlag the sign of deltaDepositAmount (true for negative)
* @param deltaDepositAmount The delta amount of deposit
* @param borrowNegativeFlag the sign of deltaBorrowAmount (true for negative)
* @param deltaBorrowAmount The delta amount of borrow
* @return true (TODO: validate results)
*/
function _updateReservedAmount(bool depositNegativeFlag, uint256 deltaDepositAmount, bool borrowNegativeFlag, uint256 deltaBorrowAmount) internal returns (bool)
{
int256 signedDeltaDepositAmount = int(deltaDepositAmount);
int256 signedDeltaBorrowAmount = int(deltaBorrowAmount);
if (depositNegativeFlag)
{
signedDeltaDepositAmount = signedDeltaDepositAmount * (-1);
}
if (borrowNegativeFlag)
{
signedDeltaBorrowAmount = signedDeltaBorrowAmount * (-1);
}
/* signedDeltaReservedAmount is singed amount */
int256 signedDeltaReservedAmount = signedSub(signedDeltaBorrowAmount, signedDeltaDepositAmount);
handlerDataStorage.updateSignedReservedAmount(signedDeltaReservedAmount);
return true;
}
/**
* @dev Sends the handler's assets to the given user
* @param userAddr The address of user
* @param unifiedTokenAmount The amount of token to send in unified token amount
* @return true (TODO: validate results)
*/
function _transfer(address payable userAddr, uint256 unifiedTokenAmount) internal returns (bool)
{
uint256 beforeBalance = erc20Instance.balanceOf(userAddr);
uint256 underlyingAmount = _convertUnifiedToUnderlying(unifiedTokenAmount);
erc20Instance.transfer(userAddr, underlyingAmount);
uint256 afterBalance = erc20Instance.balanceOf(userAddr);
require(underlyingAmount == sub(afterBalance, beforeBalance), TRANSFER);
return true;
}
// TODO: need review
function _approve(address userAddr, uint256 unifiedTokenAmount) internal returns (uint256)
{
uint256 beforeBalance = erc20Instance.allowance(address(this), userAddr);
uint256 underlyingAmount = _convertUnifiedToUnderlying(unifiedTokenAmount);
erc20Instance.approve(userAddr, underlyingAmount);
uint256 afterBalance = erc20Instance.allowance(address(this), userAddr);
require(underlyingAmount == sub(afterBalance, beforeBalance), TRANSFER);
return underlyingAmount;
}
/**
* @dev Sends the assets from the user to the contract
* @param userAddr The address of user
* @param unifiedTokenAmount The amount of token to send in unified token amount
* @return true (TODO: validate results)
*/
function _transferFrom(address payable userAddr, uint256 unifiedTokenAmount) internal returns (bool)
{
uint256 beforeBalance = erc20Instance.balanceOf(userAddr);
uint256 underlyingAmount = _convertUnifiedToUnderlying(unifiedTokenAmount);
erc20Instance.transferFrom(userAddr, address(this), underlyingAmount);
uint256 afterBalance = erc20Instance.balanceOf(userAddr);
require(underlyingAmount == sub(beforeBalance, afterBalance), TRANSFER);
return true;
}
/**
* @dev Convert amount of handler's unified decimals to amount of token's underlying decimals
* @param unifiedTokenAmount The amount of unified decimals
* @return (underlyingTokenAmount)
*/
function _convertUnifiedToUnderlying(uint256 unifiedTokenAmount) internal view returns (uint256)
{
return div(mul(unifiedTokenAmount, underlyingTokenDecimal), unifiedTokenDecimal);
}
/**
* @dev Convert amount of token's underlying decimals to amount of handler's unified decimals
* @param underlyingTokenAmount The amount of underlying decimals
* @return (unifiedTokenAmount)
*/
function _convertUnderlyingToUnified(uint256 underlyingTokenAmount) internal view returns (uint256)
{
return div(mul(underlyingTokenAmount, unifiedTokenDecimal), underlyingTokenDecimal);
}
/**
* @dev Get (total deposit - total borrow) of the handler
* @return (total deposit - total borrow) of the handler
*/
function _getTokenLiquidityAmount() internal view returns (uint256)
{
IMarketHandlerDataStorage _handlerDataStorage = handlerDataStorage;
uint256 depositTotalAmount;
uint256 borrowTotalAmount;
(depositTotalAmount, borrowTotalAmount) = _handlerDataStorage.getHandlerAmount();
if (depositTotalAmount == 0 || depositTotalAmount < borrowTotalAmount)
{
return 0;
}
return sub(depositTotalAmount, borrowTotalAmount);
}
/**
* @dev Get (total deposit * liquidity limit - total borrow) of the handler
* @return (total deposit * liquidity limit - total borrow) of the handler
*/
function _getTokenLiquidityLimitAmount() internal view returns (uint256)
{
IMarketHandlerDataStorage _handlerDataStorage = handlerDataStorage;
uint256 depositTotalAmount;
uint256 borrowTotalAmount;
(depositTotalAmount, borrowTotalAmount) = _handlerDataStorage.getHandlerAmount();
uint256 liquidityDeposit = unifiedMul(depositTotalAmount, _handlerDataStorage.getLiquidityLimit());
if (depositTotalAmount == 0 || liquidityDeposit < borrowTotalAmount) {
return 0;
}
return sub(liquidityDeposit, borrowTotalAmount);
}
/**
* @dev Get (total deposit - total borrow) of the handler including interest
* @param userAddr The user address(for wrapping function, unused)
* @return (total deposit - total borrow) of the handler including interest
*/
function _getTokenLiquidityAmountWithInterest(address payable userAddr) internal view returns (uint256)
{
uint256 depositTotalAmount;
uint256 borrowTotalAmount;
(depositTotalAmount, borrowTotalAmount) = _getTotalAmountWithInterest(userAddr);
if (depositTotalAmount == 0 || depositTotalAmount < borrowTotalAmount)
{
return 0;
}
return sub(depositTotalAmount, borrowTotalAmount);
}
/**
* @dev Get (total deposit * liquidity limit - total borrow) of the handler including interest
* @param userAddr The user address(for wrapping function, unused)
* @return (total deposit * liquidity limit - total borrow) of the handler including interest
*/
function _getTokenLiquidityLimitAmountWithInterest(address payable userAddr) internal view returns (uint256)
{
uint256 depositTotalAmount;
uint256 borrowTotalAmount;
(depositTotalAmount, borrowTotalAmount) = _getTotalAmountWithInterest(userAddr);
uint256 liquidityDeposit = unifiedMul(depositTotalAmount, handlerDataStorage.getLiquidityLimit());
if (depositTotalAmount == 0 || liquidityDeposit < borrowTotalAmount)
{
return 0;
}
return sub(liquidityDeposit, borrowTotalAmount);
}
/**
* @dev Set the unifiedPoint of token's decimal
* @param _unifiedTokenDecimal the unifiedPoint of token's decimal
* @return true (TODO: validate results)
*/
function setUnifiedTokenDecimal(uint256 _unifiedTokenDecimal) onlyOwner external returns (bool)
{
unifiedTokenDecimal = _unifiedTokenDecimal;
return true;
}
/**
* @dev Get the decimal of token
* @return (uint256, uint256) the decimal of token and the unifiedPoint of token's decimal
*/
function getTokenDecimals() external view returns (uint256, uint256)
{
return (underlyingTokenDecimal, unifiedTokenDecimal);
}
/**
* @dev Get the unifiedPoint of token's decimal (for fixed decimal number)
* @return the unifiedPoint of token's decimal
*/
/* default: UnifiedTokenDecimal Function */
function getUnifiedTokenDecimal() external view returns (uint256)
{
return unifiedTokenDecimal;
}
/**
* @dev Get the decimal of the underlying token
* @return the decimal of the underlying token
*/
/* default: UnderlyingTokenDecimal Function */
function getUnderlyingTokenDecimal() external view returns (uint256)
{
return underlyingTokenDecimal;
}
/**
* @dev Set the decimal of token
* @param _underlyingTokenDecimal the decimal of token
* @return true (TODO: validate results)
*/
function setUnderlyingTokenDecimal(uint256 _underlyingTokenDecimal) onlyOwner external returns (bool)
{
underlyingTokenDecimal = _underlyingTokenDecimal;
return true;
}
/**
* @dev Set the address of the marketManager contract
* @param marketManagerAddr The address of the marketManager contract
* @return true (TODO: validate results)
*/
function setMarketManager(address marketManagerAddr) onlyOwner public returns (bool)
{
marketManager = IMarketManager(marketManagerAddr);
return true;
}
/**
* @dev Set the address of the InterestModel contract
* @param interestModelAddr The address of the InterestModel contract
* @return true (TODO: validate results)
*/
function setInterestModel(address interestModelAddr) onlyOwner public returns (bool)
{
interestModelInstance = IInterestModel(interestModelAddr);
return true;
}
/**
* @dev Set the address of the marketDataStorage contract
* @param marketDataStorageAddr The address of the marketDataStorage contract
* @return true (TODO: validate results)
*/
function setHandlerDataStorage(address marketDataStorageAddr) onlyOwner public returns (bool)
{
handlerDataStorage = IMarketHandlerDataStorage(marketDataStorageAddr);
return true;
}
/**
* @dev Set the address and name of the underlying ERC-20 token
* @param erc20Addr The address of ERC-20 token
* @param name The name of ERC-20 token
* @return true (TODO: validate results)
*/
function setErc20(address erc20Addr, string memory name) onlyOwner public returns (bool)
{
erc20Instance = IERC20(erc20Addr);
tokenName = name;
return true;
}
/**
* @dev Set the address of the siHandlerDataStorage contract
* @param SIHandlerDataStorageAddr The address of the siHandlerDataStorage contract
* @return true (TODO: validate results)
*/
function setSiHandlerDataStorage(address SIHandlerDataStorageAddr) onlyOwner public returns (bool)
{
SIHandlerDataStorage = IMarketSIHandlerDataStorage(SIHandlerDataStorageAddr);
return true;
}
/**
* @dev Get the address of the siHandlerDataStorage contract
* @return The address of the siHandlerDataStorage contract
*/
function getSiHandlerDataStorage() public view returns (address)
{
return address(SIHandlerDataStorage);
}
/**
* @dev Get the address of the marketManager contract
* @return The address of the marketManager contract
*/
function getMarketManagerAddr() public view returns (address)
{
return address(marketManager);
}
/**
* @dev Get the address of the InterestModel contract
* @return The address of the InterestModel contract
*/
function getInterestModelAddr() public view returns (address)
{
return address(interestModelInstance);
}
/**
* @dev Get the address of handler's dataStroage
* @return the address of handler's dataStroage
*/
function getHandlerDataStorageAddr() public view returns (address)
{
return address(handlerDataStorage);
}
/**
* @dev Get the address of the underlying ERC-20 token
* @return The address of the underlying ERC-20 token
*/
function getErc20Addr() public view returns (address)
{
return address(erc20Instance);
}
/**
* @dev Get the outgoing limit of tokens
* @return The outgoing limit of tokens
*/
function getLimitOfAction() external view returns (uint256)
{
return handlerDataStorage.getLimitOfAction();
}
function get_interchainManager() external view returns (address) {
return address(interchainManager);
}
function set_interchainManager(IinterchainManager _interchainManager) onlyOwner external returns (bool) {
interchainManager = _interchainManager;
return true;
}
/* ******************* Safe Math ******************* */
// from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol
// Subject to the MIT license.
function add(uint256 a, uint256 b) internal pure returns (uint256)
{
uint256 c = a + b;
require(c >= a, "add overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256)
{
return _sub(a, b, "sub overflow");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256)
{
return _mul(a, b);
}
function div(uint256 a, uint256 b) internal pure returns (uint256)
{
return _div(a, b, "div by zero");
}
function mod(uint256 a, uint256 b) internal pure returns (uint256)
{
return _mod(a, b, "mod by zero");
}
function _sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256)
{
require(b <= a, errorMessage);
return a - b;
}
function _mul(uint256 a, uint256 b) internal pure returns (uint256)
{
if (a == 0)
{
return 0;
}
uint256 c = a * b;
require((c / a) == b, "mul overflow");
return c;
}
function _div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256)
{
require(b > 0, errorMessage);
return a / b;
}
function _mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256)
{
require(b != 0, errorMessage);
return a % b;
}
function unifiedDiv(uint256 a, uint256 b) internal pure returns (uint256)
{
return _div(_mul(a, unifiedPoint), b, "unified div by zero");
}
function unifiedMul(uint256 a, uint256 b) internal pure returns (uint256)
{
return _div(_mul(a, b), unifiedPoint, "unified mul by zero");
}
function signedAdd(int256 a, int256 b) internal pure returns (int256)
{
int256 c = a + b;
require(((b >= 0) && (c >= a)) || ((b < 0) && (c < a)), "SignedSafeMath: addition overflow");
return c;
}
function signedSub(int256 a, int256 b) internal pure returns (int256)
{
int256 c = a - b;
require(((b >= 0) && (c <= a)) || ((b < 0) && (c > a)), "SignedSafeMath: subtraction overflow");
return c;
}
} | * @dev Set the address and name of the underlying ERC-20 token @param erc20Addr The address of ERC-20 token @param name The name of ERC-20 token @return true (TODO: validate results)/ | function setErc20(address erc20Addr, string memory name) onlyOwner public returns (bool)
{
erc20Instance = IERC20(erc20Addr);
tokenName = name;
return true;
}
| 1,420,326 | [
1,
694,
326,
1758,
471,
508,
434,
326,
6808,
4232,
39,
17,
3462,
1147,
225,
6445,
71,
3462,
3178,
1021,
1758,
434,
4232,
39,
17,
3462,
1147,
225,
508,
1021,
508,
434,
4232,
39,
17,
3462,
1147,
327,
638,
261,
6241,
30,
1954,
1686,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
444,
41,
1310,
3462,
12,
2867,
6445,
71,
3462,
3178,
16,
533,
3778,
508,
13,
1338,
5541,
1071,
1135,
261,
6430,
13,
203,
202,
95,
203,
202,
202,
12610,
3462,
1442,
273,
467,
654,
39,
3462,
12,
12610,
3462,
3178,
1769,
203,
202,
202,
2316,
461,
273,
508,
31,
203,
202,
202,
2463,
638,
31,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/40/0x5c844eB862F5813dE3148d50aCbdd496682348E3/sources/contracts/KROCO.sol | Número máximo de la colección
| uint256 public maxSupply = 4444; | 9,555,989 | [
1,
50,
132,
123,
81,
2439,
312,
132,
99,
92,
381,
83,
443,
7125,
276,
790,
952,
77,
132,
116,
82,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
1071,
943,
3088,
1283,
273,
1059,
6334,
24,
31,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x08e6Da9BbeEf3aad00191164abeBAfF12a86a39a/sources/project_/src/contracts/Lottery.sol | Ensuring the lottery is within a valid time | function batchBuyLottoTicket(
uint256 _lotteryId,
uint256 _numberOfTickets
)
external
notContract()
{
require(
getCurrentTime() >= allLotteries[_lotteryId].startingTimestamp,
"Invalid time for mint:start"
);
require(
getCurrentTime() < allLotteries[_lotteryId].closingTimestamp,
"Invalid time for mint:end"
);
if(allLotteries[_lotteryId].lotteryStatus == Status.NotStarted) {
if(allLotteries[_lotteryId].startingTimestamp >= getCurrentTime()) {
allLotteries[_lotteryId].lotteryStatus = Status.Open;
}
}
require(
allLotteries[_lotteryId].lotteryStatus == Status.Open,
"Lottery not in state for mint"
);
require(
_numberOfTickets <= 50,
"Batch mint too large"
);
uint256 totalCost
) = this.costToBuyTickets(_lotteryId, _numberOfTickets);
msg.sender,
address(this),
totalCost
);
allLotteries[_lotteryId].prizePoolInUSD = allLotteries[_lotteryId].prizePoolInUSD + totalCost;
uint256[] memory chosenNumberForEachTicket = new uint256[](_numberOfTickets);
uint256 numberForTicket = allLotteries[_lotteryId].nTokensSold + 1;
for (uint256 i = 0; i < _numberOfTickets; i++) {
chosenNumberForEachTicket[i] = numberForTicket;
numberForTicket++;
}
allLotteries[_lotteryId].nTokensSold = allLotteries[_lotteryId].nTokensSold + _numberOfTickets;
msg.sender,
_lotteryId,
_numberOfTickets,
chosenNumberForEachTicket
);
msg.sender,
ticketIds,
chosenNumberForEachTicket,
totalCost
);
}
| 5,643,817 | [
1,
664,
87,
4017,
326,
17417,
387,
93,
353,
3470,
279,
923,
813,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2581,
38,
9835,
48,
352,
869,
13614,
12,
203,
3639,
2254,
5034,
389,
23372,
387,
93,
548,
16,
203,
3639,
2254,
5034,
389,
2696,
951,
6264,
2413,
203,
565,
262,
203,
565,
3903,
203,
565,
486,
8924,
1435,
203,
565,
288,
203,
3639,
2583,
12,
203,
5411,
5175,
950,
1435,
1545,
777,
48,
352,
387,
606,
63,
67,
23372,
387,
93,
548,
8009,
18526,
4921,
16,
203,
5411,
315,
1941,
813,
364,
312,
474,
30,
1937,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
5175,
950,
1435,
411,
777,
48,
352,
387,
606,
63,
67,
23372,
387,
93,
548,
8009,
19506,
4921,
16,
203,
5411,
315,
1941,
813,
364,
312,
474,
30,
409,
6,
203,
3639,
11272,
203,
3639,
309,
12,
454,
48,
352,
387,
606,
63,
67,
23372,
387,
93,
548,
8009,
23372,
387,
93,
1482,
422,
2685,
18,
1248,
9217,
13,
288,
203,
5411,
309,
12,
454,
48,
352,
387,
606,
63,
67,
23372,
387,
93,
548,
8009,
18526,
4921,
1545,
5175,
950,
10756,
288,
203,
7734,
777,
48,
352,
387,
606,
63,
67,
23372,
387,
93,
548,
8009,
23372,
387,
93,
1482,
273,
2685,
18,
3678,
31,
203,
5411,
289,
203,
3639,
289,
203,
3639,
2583,
12,
203,
5411,
777,
48,
352,
387,
606,
63,
67,
23372,
387,
93,
548,
8009,
23372,
387,
93,
1482,
422,
2685,
18,
3678,
16,
203,
5411,
315,
48,
352,
387,
93,
486,
316,
919,
364,
312,
474,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
389,
2696,
951,
6264,
2
] |
pragma solidity ^0.4.21;
/**
* [email protected]/contracts/math/SafeMath.sol
*/
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
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;
}
}
/**
* [email protected]/contracts/ownership/Ownable.sol
*/
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* [email protected]/contracts/token/ERC20/ERC20Basic.sol
*/
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* [email protected]/contracts/token/ERC20/ERC20.sol
*/
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* [email protected]/contracts/token/ERC20/BasicToken.sol
*/
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* [email protected]/contracts/token/ERC20/StandardToken.sol
*/
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* [email protected]/contracts/token/ERC20/BurnableToken.sol
*/
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
/**
* [email protected]/contracts/token/ERC20/MintableToken.sol
*/
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
/**
* [email protected]/contracts/token/ERC20/CappedToken.sol
*/
/**
* @title Capped token
* @dev Mintable token with a token cap.
*/
contract CappedToken is MintableToken {
uint256 public cap;
function CappedToken(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
/**
* DNC Token, totalSupply 100000000000000000
*/
contract DncToken is BurnableToken, CappedToken(10000000000000000000000000) {
string public name = "Treasure Box";
string public symbol = "TSB";
uint8 public decimals = 18;
function burn(uint256 _value) onlyOwner public {
super.burn(_value);
}
} | * DNC Token, totalSupply 100000000000000000/ | contract DncToken is BurnableToken, CappedToken(10000000000000000000000000) {
string public name = "Treasure Box";
string public symbol = "TSB";
uint8 public decimals = 18;
function burn(uint256 _value) onlyOwner public {
super.burn(_value);
}
} | 13,540,883 | [
1,
8609,
39,
3155,
16,
2078,
3088,
1283,
2130,
12648,
17877,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
463,
14202,
1345,
353,
605,
321,
429,
1345,
16,
11200,
1845,
1345,
12,
21,
12648,
12648,
2787,
11706,
13,
288,
203,
565,
533,
1071,
508,
273,
315,
56,
266,
3619,
8549,
14432,
203,
565,
533,
1071,
3273,
273,
315,
8047,
38,
14432,
203,
565,
2254,
28,
1071,
15105,
273,
6549,
31,
203,
203,
565,
445,
18305,
12,
11890,
5034,
389,
1132,
13,
1338,
5541,
1071,
288,
203,
3639,
2240,
18,
70,
321,
24899,
1132,
1769,
203,
565,
289,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/56/0xD4FDcfb15FDc9427AD7aF1219860f2fD43546424/sources/MasterChef.sol | MasterChef is the master of Egg. He can make Egg and he is a fair guy. Note that it's ownable and the owner wields tremendous power. The ownership will be transferred to a governance smart contract once EGG is sufficiently distributed and the community can show to govern itself. Have fun reading it. Hopefully it's bug-free. God bless. Info of each user. | contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeBEP20 for IBEP20;
struct UserInfo {
}
struct PoolInfo {
}
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
EggToken _egg,
address _devaddr,
address _feeAddress,
uint256 _eggPerBlock,
uint256 _startBlock
EggToken public egg;
address public devaddr;
uint256 public eggPerBlock;
uint256 public constant BONUS_MULTIPLIER = 1;
address public feeAddress;
PoolInfo[] public poolInfo;
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
uint256 public totalAllocPoint = 0;
uint256 public startBlock;
) public {
egg = _egg;
devaddr = _devaddr;
feeAddress = _feeAddress;
eggPerBlock = _eggPerBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner {
require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accEggPerShare: 0,
depositFeeBP: _depositFeeBP
}));
}
function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner {
require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accEggPerShare: 0,
depositFeeBP: _depositFeeBP
}));
}
function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner {
require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accEggPerShare: 0,
depositFeeBP: _depositFeeBP
}));
}
function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner {
require(_depositFeeBP <= 10000, "set: invalid deposit fee basis points");
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].depositFeeBP = _depositFeeBP;
}
function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner {
require(_depositFeeBP <= 10000, "set: invalid deposit fee basis points");
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].depositFeeBP = _depositFeeBP;
}
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
}
function pendingEgg(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accEggPerShare = pool.accEggPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 eggReward = multiplier.mul(eggPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accEggPerShare = accEggPerShare.add(eggReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accEggPerShare).div(1e12).sub(user.rewardDebt);
}
function pendingEgg(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accEggPerShare = pool.accEggPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 eggReward = multiplier.mul(eggPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accEggPerShare = accEggPerShare.add(eggReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accEggPerShare).div(1e12).sub(user.rewardDebt);
}
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0 || pool.allocPoint == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 eggReward = multiplier.mul(eggPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
pool.accEggPerShare = pool.accEggPerShare.add(eggReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0 || pool.allocPoint == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 eggReward = multiplier.mul(eggPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
pool.accEggPerShare = pool.accEggPerShare.add(eggReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0 || pool.allocPoint == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 eggReward = multiplier.mul(eggPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
pool.accEggPerShare = pool.accEggPerShare.add(eggReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accEggPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeEggTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if(pool.depositFeeBP > 0){
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
user.amount = user.amount.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accEggPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accEggPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeEggTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if(pool.depositFeeBP > 0){
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
user.amount = user.amount.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accEggPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accEggPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeEggTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if(pool.depositFeeBP > 0){
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
user.amount = user.amount.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accEggPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accEggPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeEggTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if(pool.depositFeeBP > 0){
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
user.amount = user.amount.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accEggPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accEggPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeEggTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if(pool.depositFeeBP > 0){
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
user.amount = user.amount.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accEggPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
}else{
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accEggPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeEggTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accEggPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accEggPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeEggTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accEggPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accEggPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeEggTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accEggPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
function safeEggTransfer(address _to, uint256 _amount) internal {
uint256 eggBal = egg.balanceOf(address(this));
if (_amount > eggBal) {
egg.transfer(_to, eggBal);
egg.transfer(_to, _amount);
}
}
function safeEggTransfer(address _to, uint256 _amount) internal {
uint256 eggBal = egg.balanceOf(address(this));
if (_amount > eggBal) {
egg.transfer(_to, eggBal);
egg.transfer(_to, _amount);
}
}
} else {
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
function setFeeAddress(address _feeAddress) public{
require(msg.sender == feeAddress, "setFeeAddress: FORBIDDEN");
feeAddress = _feeAddress;
}
function updateEmissionRate(uint256 _eggPerBlock) public onlyOwner {
massUpdatePools();
eggPerBlock = _eggPerBlock;
}
} | 11,261,947 | [
1,
7786,
39,
580,
74,
353,
326,
4171,
434,
512,
14253,
18,
8264,
848,
1221,
512,
14253,
471,
3904,
353,
279,
284,
1826,
3058,
93,
18,
3609,
716,
518,
1807,
4953,
429,
471,
326,
3410,
341,
491,
87,
268,
2764,
409,
1481,
7212,
18,
1021,
23178,
903,
506,
906,
4193,
358,
279,
314,
1643,
82,
1359,
13706,
6835,
3647,
512,
19491,
353,
18662,
715,
16859,
471,
326,
19833,
848,
2405,
358,
314,
1643,
82,
6174,
18,
21940,
9831,
6453,
518,
18,
670,
1306,
4095,
518,
1807,
7934,
17,
9156,
18,
611,
369,
324,
2656,
18,
3807,
434,
1517,
729,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
13453,
39,
580,
74,
353,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
5948,
52,
3462,
364,
467,
5948,
52,
3462,
31,
203,
203,
203,
565,
1958,
25003,
288,
203,
565,
289,
203,
203,
565,
1958,
8828,
966,
288,
203,
565,
289,
203,
203,
203,
203,
565,
871,
4019,
538,
305,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
3423,
9446,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
512,
6592,
75,
2075,
1190,
9446,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
1769,
203,
203,
565,
3885,
12,
203,
3639,
512,
14253,
1345,
389,
23171,
16,
203,
3639,
1758,
389,
5206,
4793,
16,
203,
3639,
1758,
389,
21386,
1887,
16,
203,
3639,
2254,
5034,
389,
23171,
2173,
1768,
16,
203,
3639,
2254,
5034,
389,
1937,
1768,
203,
565,
512,
14253,
1345,
1071,
25144,
31,
203,
565,
1758,
1071,
4461,
4793,
31,
203,
565,
2254,
5034,
1071,
25144,
2173,
1768,
31,
203,
565,
2254,
5034,
1071,
5381,
605,
673,
3378,
67,
24683,
2053,
654,
273,
404,
31,
203,
565,
1758,
1071,
14036,
1887,
31,
203,
565,
8828,
966,
8526,
1071,
2845,
966,
31,
203,
565,
2874,
261,
11890,
5034,
516,
2874,
261,
2867,
516,
25003,
3719,
1071,
16753,
31,
203,
565,
2254,
5034,
1071,
2078,
8763,
2148,
273,
374,
31,
203,
565,
2254,
5034,
1071,
787,
1768,
31,
203,
565,
262,
1071,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
interface IFactory {
function getPair(address tokenA, address tokenB)
external
view
returns (address pair);
}
/**
* @title : ProximaLiquidityRewardVault
* Developed by ProximusAlpha
*/
contract ProximaLiquidityRewardVault {
using SafeMath for uint256;
/// @dev Proxima Token
IERC20 public pxa;
/// @dev Proxima Governor
address public governance;
/// @dev Proxima Router
address public router;
/// @dev Proxima Factory
address public factory;
/// @dev Proxima developer
address public setter;
/// @dev Pending pxa rewards
uint256 private totalPendingRewards;
/// @dev div const
uint256 private denominator = 10000000;
/// @dev Event emitted when new rewards are locked
event rewardLocked(address[] pairs, address user, uint256 totalLocked);
/// @dev Event emitted when LP retrieves rewards via pair
event pairRewardClaim(address releasedTo, uint256 releasedAmount);
/// @dev Event emitted when user withdraw rewards
event userRewardClaim(address indexed releasedTo, uint256 releasedAmount);
/// @dev Whitelist map
mapping(address => bool) public whiteListedPairs;
/// @dev Pair pending rewardmap
mapping(address => uint256) public pairPendingRewards;
/// @dev User pending reward map
mapping(address => uint256) public userPendingRewards;
/// @dev Governance modifier
modifier onlyGovernance() {
require(msg.sender == governance, "PLRV: Not governance ");
_;
}
/// @dev Router modifier
modifier onlyRouter() {
require(msg.sender == router, "PLRV: Not router ");
_;
}
/// @dev Sets mandate
constructor(IERC20 _pxa, address _setter) public {
pxa = _pxa;
setter = _setter;
totalPendingRewards = 0;
}
/// @dev Locks trade rewards for user and LP of pair(s)
function lockShares(address[] memory pairs, address _who)
external
onlyRouter
returns (bool)
{
uint256 totalPairAllocation = 0;
for (uint8 i = 0; i < pairs.length - 1; i++) {
address forPair = IFactory(factory).getPair(pairs[i], pairs[i + 1]);
if (whiteListedPairs[forPair] == true) {
uint256 pairShare = getCurrentDistribution();
totalPairAllocation = totalPairAllocation.add(pairShare);
totalPendingRewards = totalPendingRewards.add(pairShare);
pairPendingRewards[forPair] = pairPendingRewards[forPair].add(
pairShare
);
}
}
if (totalPairAllocation > 0) {
uint256 userShare = totalPairAllocation.div(pairs.length);
if (pairs.length <= 2) {
userShare = userShare.div(2); // direct pair trade reward correction
}
totalPendingRewards = totalPendingRewards.add(userShare);
userPendingRewards[_who] = userPendingRewards[_who].add(userShare);
totalPairAllocation = totalPairAllocation.add(userShare);
}
emit rewardLocked(pairs, _who, totalPairAllocation);
return true;
}
/// @dev Release accu. rewards for pair
function releasePairShare() external returns (bool) {
uint256 pairShare = pairPendingRewards[msg.sender];
require(pairShare > 0, "PLRV: No pending rewards");
pairPendingRewards[msg.sender] = 0;
safePxaTransfer(msg.sender, pairShare);
totalPendingRewards = totalPendingRewards.sub(pairShare);
emit pairRewardClaim(msg.sender, pairShare);
return true;
}
/// @dev Release accu. rewards for user
function releaseUserShare() external returns (bool) {
uint256 userShare = userPendingRewards[msg.sender];
require(userShare > 0, "PLRV: No pending rewards");
userPendingRewards[msg.sender] = 0;
safePxaTransfer(msg.sender, userShare);
totalPendingRewards = totalPendingRewards.sub(userShare);
emit userRewardClaim(msg.sender, userShare);
return true;
}
/// @dev Sets governance on pair
function applyGovernance(address pair, bool sentiment)
external
onlyGovernance
returns (bool)
{
uint256 pairShare = pairPendingRewards[pair];
if (pairShare > 0) {
pairPendingRewards[pair] = 0;
safePxaTransfer(pair, pairShare);
totalPendingRewards = totalPendingRewards.sub(pairShare);
}
if (sentiment) {
return sewPairSupply(pair);
} else {
return slashPairSupply(pair);
}
}
function sewPairSupply(address pair) internal returns (bool) {
whiteListedPairs[pair] = true;
return true;
}
function slashPairSupply(address pair) internal returns (bool) {
whiteListedPairs[pair] = false;
return true; /// @dev Release accu. rewards for pair
}
/// @dev Whilelist pairs directly
function exemptedPair(address _pair) external returns (bool) {
require(msg.sender == factory, "PLRV : FORBIDDEN");
return sewPairSupply(_pair);
}
/// @dev Safe pxa token transfer
function safePxaTransfer(address _to, uint256 _amount) internal {
uint256 PxaBal = safeBalance();
if (_amount > PxaBal) {
pxa.transfer(_to, PxaBal);
} else {
pxa.transfer(_to, _amount);
}
}
/// @dev Returns current reward distribution . Calculated by x percent of reward pools total weight
function getCurrentDistribution() public view returns (uint256) {
uint256 safeAmount = (safeBalance()).sub(totalPendingRewards);
uint256 numerator = safeAmount.mul(8);
uint256 share = numerator / denominator;
return (share);
}
/// @dev Returns rewardVault balance
function safeBalance() public view returns (uint256) {
return pxa.balanceOf(address(this));
}
/// @dev Ruturns user pending rewards
function getUserPendingShares(address _who)
external
view
returns (uint256)
{
return userPendingRewards[_who];
}
/// @dev Returns Pair pending rewards
function getPairPendingShares(address _who)
external
view
returns (uint256)
{
return pairPendingRewards[_who];
}
/// @dev Sets Governance
function setPairGovernor(address _governance) external {
require(msg.sender == setter, "PLRV: FORBIDDEN");
governance = _governance;
}
/// @dev Sets proxima developer address
function setSetter(address _setter) external {
require(msg.sender == setter, "PLRV: FORBIDDEN");
setter = _setter;
}
/// @dev Sets Proxima router
function setRouter(address _router) external {
require(msg.sender == setter, "PLRV: FORBIDDEN");
router = _router;
}
/// @dev Sets Proxima factory
function setFactory(address _factory) external {
require(msg.sender == setter, "PLRV: FORBIDDEN");
factory = _factory;
}
}
| @dev Sets Governance | function setPairGovernor(address _governance) external {
require(msg.sender == setter, "PLRV: FORBIDDEN");
governance = _governance;
}
| 5,460,072 | [
1,
2785,
611,
1643,
82,
1359,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
4154,
43,
1643,
29561,
12,
2867,
389,
75,
1643,
82,
1359,
13,
3903,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
7794,
16,
315,
6253,
54,
58,
30,
12108,
30198,
8863,
203,
3639,
314,
1643,
82,
1359,
273,
389,
75,
1643,
82,
1359,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./ScheduleCalc.sol";
// interface with ERC20 and the burn function interface from the associated Token contract
interface IERC20Burnable is IERC20 {
function burn(uint256 amount) external;
function decimals() external view returns (uint8);
}
contract TokenLockup {
IERC20Burnable public token;
string private _name;
string private _symbol;
ReleaseSchedule[] public releaseSchedules;
uint public minReleaseScheduleAmount;
uint public maxReleaseDelay;
mapping(address => Timelock[]) public timelocks;
mapping(address => uint) internal _totalTokensUnlocked;
mapping(address => mapping(address => uint)) internal _allowances;
event Approval(address indexed from, address indexed spender, uint amount);
event TimelockBurned(address indexed from, uint timelockId);
event ScheduleCreated(address indexed from, uint scheduleId);
event ScheduleFunded(address indexed from, address indexed to, uint indexed scheduleId, uint amount, uint commencementTimestamp, uint timelockId);
/* The constructor that specifies the token, name and symbol
The name should specify that it is an unlock contract
The symbol should end with " Unlock" & be less than 11 characters for MetaMask "custom token" compatibility
*/
constructor (
address _token,
string memory name_,
string memory symbol_,
uint _minReleaseScheduleAmount,
uint _maxReleaseDelay
) {
_name = name_;
_symbol = symbol_;
token = IERC20Burnable(_token);
require(_minReleaseScheduleAmount > 0, "Min schedule amount > 0");
minReleaseScheduleAmount = _minReleaseScheduleAmount;
maxReleaseDelay = _maxReleaseDelay;
}
function createReleaseSchedule(
uint releaseCount, // total number of releases including any initial "cliff'
uint delayUntilFirstReleaseInSeconds, // "cliff" or 0 for immediate relase
uint initialReleasePortionInBips, // in 100ths of 1%
uint periodBetweenReleasesInSeconds
)
external
returns
(
uint unlockScheduleId
) {
require(delayUntilFirstReleaseInSeconds <= maxReleaseDelay, "first release > max");
require(releaseCount >= 1, "< 1 release");
require(initialReleasePortionInBips <= ScheduleCalc.BIPS_PRECISION, "release > 100%");
if (releaseCount > 1) {
require(periodBetweenReleasesInSeconds > 0, "period = 0");
}
if (releaseCount == 1) {
require(initialReleasePortionInBips == ScheduleCalc.BIPS_PRECISION, "released < 100%");
}
releaseSchedules.push(ReleaseSchedule(
releaseCount,
delayUntilFirstReleaseInSeconds,
initialReleasePortionInBips,
periodBetweenReleasesInSeconds
));
emit ScheduleCreated(msg.sender, unlockScheduleId);
// returning the index of the newly added schedule
return releaseSchedules.length - 1;
}
function fundReleaseSchedule(
address to,
uint amount,
uint commencementTimestamp, // unix timestamp
uint scheduleId
) public returns(bool) {
require(amount >= minReleaseScheduleAmount, "amount < min funding");
require(to != address(0), "to 0 address");
require(scheduleId < releaseSchedules.length, "bad scheduleId");
require(amount >= releaseSchedules[scheduleId].releaseCount, "< 1 token per release");
// It will revert via ERC20 implementation if there's no allowance
require(token.transferFrom(msg.sender, address(this), amount));
require(
commencementTimestamp <= block.timestamp + maxReleaseDelay
, "commencement time out of range");
require(
commencementTimestamp + releaseSchedules[scheduleId].delayUntilFirstReleaseInSeconds <=
block.timestamp + maxReleaseDelay
, "initial release out of range");
Timelock memory timelock;
timelock.scheduleId = scheduleId;
timelock.commencementTimestamp = commencementTimestamp;
timelock.totalAmount = amount;
timelocks[to].push(timelock);
emit ScheduleFunded(msg.sender, to, scheduleId, amount, commencementTimestamp, timelocks[to].length - 1);
return true;
}
function batchFundReleaseSchedule(
address[] memory recipients,
uint[] memory amounts,
uint[] memory commencementTimestamps, // unix timestamp
uint[] memory scheduleIds
) external returns (bool) {
require(amounts.length == recipients.length, "mismatched array length");
for (uint i; i < recipients.length; i++) {
require(fundReleaseSchedule(recipients[i], amounts[i], commencementTimestamps[i], scheduleIds[i]));
}
return true;
}
function lockedBalanceOf(address who) public view returns (uint amount) {
for (uint i = 0; i < timelocks[who].length; i++) {
amount += lockedBalanceOfTimelock(who, i);
}
return amount;
}
function unlockedBalanceOf(address who) public view returns (uint amount) {
for (uint i = 0; i < timelocks[who].length; i++) {
amount += unlockedBalanceOfTimelock(who, i);
}
return amount;
}
function lockedBalanceOfTimelock(address who, uint timelockIndex) public view returns (uint locked) {
return timelocks[who][timelockIndex].totalAmount - totalUnlockedToDateOfTimelock(who, timelockIndex);
}
function unlockedBalanceOfTimelock(address who, uint timelockIndex) public view returns (uint unlocked) {
return totalUnlockedToDateOfTimelock(who, timelockIndex) - timelocks[who][timelockIndex].tokensTransferred;
}
function totalUnlockedToDateOfTimelock(address who, uint timelockIndex) public view returns (uint unlocked) {
return calculateUnlocked(
timelocks[who][timelockIndex].commencementTimestamp,
block.timestamp,
timelocks[who][timelockIndex].totalAmount,
timelocks[who][timelockIndex].scheduleId
);
}
function viewTimelock(address who, uint256 index) public view
returns (Timelock memory timelock) {
return timelocks[who][index];
}
function balanceOf(address who) external view returns (uint) {
return unlockedBalanceOf(who) + lockedBalanceOf(who);
}
function transfer(address to, uint value) external returns (bool) {
return _transfer(msg.sender, to, value);
}
function transferFrom(address from, address to, uint value) external returns (bool) {
require(_allowances[from][msg.sender] >= value, "value > allowance");
_allowances[from][msg.sender] -= value;
return _transfer(from, to, value);
}
// Code from OpenZeppelin's contract/token/ERC20/ERC20.sol, modified
function approve(address spender, uint amount) external returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
// Code from OpenZeppelin's contract/token/ERC20/ERC20.sol, modified
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
// Code from OpenZeppelin's contract/token/ERC20/ERC20.sol, modified
function increaseAllowance(address spender, uint addedValue) external returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue);
return true;
}
// Code from OpenZeppelin's contract/token/ERC20/ERC20.sol, modified
function decreaseAllowance(address spender, uint subtractedValue) external returns (bool) {
uint currentAllowance = _allowances[msg.sender][spender];
require(currentAllowance >= subtractedValue, "decrease > allowance");
_approve(msg.sender, spender, _allowances[msg.sender][spender] - subtractedValue);
return true;
}
function decimals() public view returns (uint8) {
return token.decimals();
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function totalSupply() external view returns (uint) {
return token.balanceOf(address(this));
}
function burn(uint timelockIndex, uint confirmationIdPlusOne) external returns(bool) {
require(timelockIndex < timelocks[msg.sender].length, "No schedule");
// this also protects from overflow below
require(confirmationIdPlusOne == timelockIndex + 1, "Burn not confirmed");
// actually burning the remaining tokens from the unlock
token.burn(lockedBalanceOfTimelock(msg.sender, timelockIndex) + unlockedBalanceOfTimelock(msg.sender, timelockIndex));
// overwrite the timelock to delete with the timelock on the end which will be discarded
// if the timelock to delete is on the end, it will just be deleted in the step after the if statement
if (timelocks[msg.sender].length - 1 != timelockIndex) {
timelocks[msg.sender][timelockIndex] = timelocks[msg.sender][timelocks[msg.sender].length - 1];
}
// delete the timelock on the end
timelocks[msg.sender].pop();
emit TimelockBurned(msg.sender, timelockIndex);
return true;
}
function _transfer(address from, address to, uint value) internal returns (bool) {
require(unlockedBalanceOf(from) >= value, "amount > unlocked");
uint remainingTransfer = value;
// transfer from unlocked tokens
for (uint i = 0; i < timelocks[from].length; i++) {
// if the timelock has no value left
if (timelocks[from][i].tokensTransferred == timelocks[from][i].totalAmount) {
continue;
} else if (remainingTransfer > unlockedBalanceOfTimelock(from, i)) {
// if the remainingTransfer is more than the unlocked balance use it all
remainingTransfer -= unlockedBalanceOfTimelock(from, i);
timelocks[from][i].tokensTransferred += unlockedBalanceOfTimelock(from, i);
} else {
// if the remainingTransfer is less than or equal to the unlocked balance
// use part or all and exit the loop
timelocks[from][i].tokensTransferred += remainingTransfer;
remainingTransfer = 0;
break;
}
}
// should never have a remainingTransfer amount at this point
require(remainingTransfer == 0, "bad transfer");
require(token.transfer(to, value));
return true;
}
function transferTimelock(address to, uint value, uint timelockId) external returns (bool) {
require(unlockedBalanceOfTimelock(msg.sender, timelockId) >= value, "amount > unlocked");
timelocks[msg.sender][timelockId].tokensTransferred += value;
require(token.transfer(to, value));
return true;
}
function calculateUnlocked(uint commencedTimestamp, uint currentTimestamp, uint amount, uint scheduleId) public view returns (uint unlocked) {
return ScheduleCalc.calculateUnlocked(commencedTimestamp, currentTimestamp, amount, releaseSchedules[scheduleId]);
}
// Code from OpenZeppelin's contract/token/ERC20/ERC20.sol, modified
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0));
require(spender != address(0), "spender is 0 address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function scheduleCount() external view returns (uint count) {
return releaseSchedules.length;
}
function timelockOf(address who, uint index) external view returns (Timelock memory timelock) {
return timelocks[who][index];
}
function timelockCountOf(address who) external view returns (uint) {
return timelocks[who].length;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
struct ReleaseSchedule {
uint releaseCount;
uint delayUntilFirstReleaseInSeconds;
uint initialReleasePortionInBips;
uint periodBetweenReleasesInSeconds;
}
struct Timelock {
uint scheduleId;
uint commencementTimestamp;
uint tokensTransferred;
uint totalAmount;
}
library ScheduleCalc {
uint constant BIPS_PRECISION = 10000;
function calculateUnlocked(uint commencedTimestamp, uint currentTimestamp, uint amount, ReleaseSchedule memory releaseSchedule) external pure returns (uint unlocked) {
if(commencedTimestamp > currentTimestamp) {
return 0;
}
uint secondsElapsed = currentTimestamp - commencedTimestamp;
// return the full amount if the total lockup period has expired
// unlocked amounts in each period are truncated and round down remainders smaller than the smallest unit
// unlocking the full amount unlocks any remainder amounts in the final unlock period
// this is done first to reduce computation
if (secondsElapsed >= releaseSchedule.delayUntilFirstReleaseInSeconds +
(releaseSchedule.periodBetweenReleasesInSeconds * (releaseSchedule.releaseCount - 1))) {
return amount;
}
// unlock the initial release if the delay has elapsed
if (secondsElapsed >= releaseSchedule.delayUntilFirstReleaseInSeconds) {
unlocked = (amount * releaseSchedule.initialReleasePortionInBips) / BIPS_PRECISION;
// if at least one period after the delay has passed
if (secondsElapsed - releaseSchedule.delayUntilFirstReleaseInSeconds
>= releaseSchedule.periodBetweenReleasesInSeconds) {
// calculate the number of additional periods that have passed (not including the initial release)
// this discards any remainders (ie it truncates / rounds down)
uint additionalUnlockedPeriods =
(secondsElapsed - releaseSchedule.delayUntilFirstReleaseInSeconds) /
releaseSchedule.periodBetweenReleasesInSeconds;
// calculate the amount of unlocked tokens for the additionalUnlockedPeriods
// multiplication is applied before division to delay truncating to the smallest unit
// this distributes unlocked tokens more evenly across unlock periods
// than truncated division followed by multiplication
unlocked += ((amount - unlocked) * additionalUnlockedPeriods) / (releaseSchedule.releaseCount - 1);
}
}
return unlocked;
}
} | this also protects from overflow below actually burning the remaining tokens from the unlock overwrite the timelock to delete with the timelock on the end which will be discarded if the timelock to delete is on the end, it will just be deleted in the step after the if statement | function burn(uint timelockIndex, uint confirmationIdPlusOne) external returns(bool) {
require(timelockIndex < timelocks[msg.sender].length, "No schedule");
require(confirmationIdPlusOne == timelockIndex + 1, "Burn not confirmed");
token.burn(lockedBalanceOfTimelock(msg.sender, timelockIndex) + unlockedBalanceOfTimelock(msg.sender, timelockIndex));
if (timelocks[msg.sender].length - 1 != timelockIndex) {
timelocks[msg.sender][timelockIndex] = timelocks[msg.sender][timelocks[msg.sender].length - 1];
}
emit TimelockBurned(msg.sender, timelockIndex);
return true;
}
| 14,059,623 | [
1,
2211,
2546,
17151,
87,
628,
9391,
5712,
6013,
18305,
310,
326,
4463,
2430,
628,
326,
7186,
6156,
326,
1658,
292,
975,
358,
1430,
598,
326,
1658,
292,
975,
603,
326,
679,
1492,
903,
506,
20076,
309,
326,
1658,
292,
975,
358,
1430,
353,
603,
326,
679,
16,
518,
903,
2537,
506,
4282,
316,
326,
2235,
1839,
326,
309,
3021,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
18305,
12,
11890,
1658,
292,
975,
1016,
16,
2254,
14296,
548,
13207,
3335,
13,
3903,
1135,
12,
6430,
13,
288,
203,
3639,
2583,
12,
8584,
292,
975,
1016,
411,
1658,
292,
20641,
63,
3576,
18,
15330,
8009,
2469,
16,
315,
2279,
4788,
8863,
203,
203,
3639,
2583,
12,
22275,
548,
13207,
3335,
422,
1658,
292,
975,
1016,
397,
404,
16,
315,
38,
321,
486,
19979,
8863,
203,
203,
3639,
1147,
18,
70,
321,
12,
15091,
13937,
951,
10178,
292,
975,
12,
3576,
18,
15330,
16,
1658,
292,
975,
1016,
13,
397,
25966,
13937,
951,
10178,
292,
975,
12,
3576,
18,
15330,
16,
1658,
292,
975,
1016,
10019,
203,
203,
3639,
309,
261,
8584,
292,
20641,
63,
3576,
18,
15330,
8009,
2469,
300,
404,
480,
1658,
292,
975,
1016,
13,
288,
203,
5411,
1658,
292,
20641,
63,
3576,
18,
15330,
6362,
8584,
292,
975,
1016,
65,
273,
1658,
292,
20641,
63,
3576,
18,
15330,
6362,
8584,
292,
20641,
63,
3576,
18,
15330,
8009,
2469,
300,
404,
15533,
203,
3639,
289,
203,
203,
3639,
3626,
12652,
292,
975,
38,
321,
329,
12,
3576,
18,
15330,
16,
1658,
292,
975,
1016,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/4/0xb5139ba2018fd2150aB59c2Fe511083361Ab3719/sources/contracts/loyalty/Loyalty.sol | contract to manage all bonuses | contract Loyalty is ILoyalty, IERC1155Receiver, LoyaltyBase {
event TrancheUpdated(uint256 _tranche, uint256 _points);
event LoyaltyUpdated(address indexed _user, uint256 _tranche, uint256 _points);
event BaseFeeUpdated(address indexed _user, uint256 _baseFee);
event ProtocolFeeUpdated(address indexed _user, uint256 _protocolFee);
event DiscountMultiplierUpdated(address indexed _user, uint256 _multiplier);
event Deposit(address indexed _user, uint256 _id, uint256 _amount);
event Withdraw(address indexed _user, uint256 _id, uint256 _amount);
import { IERC1155 } from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import { IERC1155Receiver } from "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import { ILoyalty } from "../interfaces/ILoyalty.sol";
import { ILodge } from "../interfaces/ILodge.sol";
import { ISlopes } from "../interfaces/ISlopes.sol";
import { IAvalanche } from "../interfaces/IAvalanche.sol";
import { LoyaltyBase } from "./LoyaltyBase.sol";
struct LoyaltyInfo {
uint256 points;
uint256 tranche;
}
mapping(uint256 => mapping(address => uint256)) public override staked;
mapping(uint256 => bool) public override whitelistedTokens;
modifier Whitelisted(uint256 _id) {
require(whitelistedTokens[_id], "This Lodge token cannot be staked");
_;
}
modifier OnlyOneBoost(address _user) {
require(
userLoyalty[_user].boost == 0,
"Max one boost per account"
);
_;
}
constructor(address _address)
public
LoyaltyBase(_address)
{
whitelistedTokens[0] = true;
whitelistedTokens[1] = true;
whitelistedTokens[2] = true;
_initializeLoyaltyTranches();
}
function _initializeLoyaltyTranches() internal {
}
function setLoyaltyTranche(
uint256 _tranche,
uint256 _points
)
external
HasPatrol("ADMIN")
{
_setLoyaltyTranche(_tranche, _points);
}
function _setLoyaltyTranche(
uint256 _tranche,
uint256 _points
)
internal
{
loyaltyTranches[_tranche] = _points;
emit TrancheUpdated(_tranche, _points);
}
function deposit(uint256 _id, uint256 _amount)
external
override
{
_deposit(_msgSender(), _id, _amount);
}
function _deposit(address _address, uint256 _id, uint256 _amount)
internal
Whitelisted(_id)
NonZeroAmount(_amount)
OnlyOneBoost(_address)
{
IERC1155(lodgeAddress()).safeTransferFrom(_address, address(this), _id, _amount, "");
staked[_id][_address] += _amount;
userLoyalty[_address].boost = ILodge(lodgeAddress()).boost(_id);
userLoyalty[_address].staked = _id + 1;
ISlopes(slopesAddress()).claimAllFor(_address);
IAvalanche(avalancheAddress()).claimFor(_address);
emit Deposit(_address, _id, _amount);
}
function withdraw(uint256 _id, uint256 _amount)
external
override
{
_withdraw(_msgSender(), _id, _amount);
}
function _withdraw(address _address, uint256 _id, uint256 _amount)
internal
{
require(
staked[_id][_address] >= _amount,
"Staked balance not high enough to withdraw this amount"
);
IERC1155(lodgeAddress()).safeTransferFrom(address(this), _address, _id, _amount, "");
staked[_id][_address] -= _amount;
userLoyalty[_address].boost = 0;
userLoyalty[_address].staked = 0;
ISlopes(slopesAddress()).claimAllFor(_address);
IAvalanche(avalancheAddress()).claimFor(_address);
emit Withdraw(_address, _id, _amount);
}
function whitelistToken(uint256 _id)
external
override
HasPatrol("ADMIN")
{
whitelistedTokens[_id] = true;
}
function blacklistToken(uint256 _id)
external
override
HasPatrol("ADMIN")
{
whitelistedTokens[_id] = false;
}
function getBoost(address _user)
external
override
view
returns (uint256)
{
return userLoyalty[_user].boost;
}
function getTotalShares(address _user, uint256 _amount)
external
override
view
returns (uint256)
{
return _amount.add(_amount.mul(userLoyalty[_user].boost).div(1000));
}
function getTotalFee(address _user, uint256 _amount)
external
override
view
returns (uint256)
{
uint256 trancheFee = baseFee - (discountMultiplier * userLoyalty[_user].tranche);
return _amount.mul(trancheFee).div(10000).mul(1000 - userLoyalty[_user].boost).div(1000);
}
function getProtocolFee(uint256 _amount)
external
override
view
returns (uint256)
{
return _amount.mul(protocolFee).div(10000);
}
function updatePoints(address _address)
external
override
OnlySlopes
{
userLoyalty[_address].points = userLoyalty[_address].points.add(1);
if (userLoyalty[_address].points > loyaltyTranches[userLoyalty[_address].tranche.add(1)]) {
userLoyalty[_address].tranche = userLoyalty[_address].tranche.add(1);
}
}
function updatePoints(address _address)
external
override
OnlySlopes
{
userLoyalty[_address].points = userLoyalty[_address].points.add(1);
if (userLoyalty[_address].points > loyaltyTranches[userLoyalty[_address].tranche.add(1)]) {
userLoyalty[_address].tranche = userLoyalty[_address].tranche.add(1);
}
}
function updateTranche(address _address)
public
{
if (userLoyalty[_address].points > loyaltyTranches[userLoyalty[_address].tranche + 1]) {
userLoyalty[_address].tranche = userLoyalty[_address].tranche + 1;
if (userLoyalty[_address].tranche == 0) {
return;
}
if (userLoyalty[_address].points < loyaltyTranches[userLoyalty[_address].tranche]) {
userLoyalty[_address].tranche = userLoyalty[_address].tranche - 1;
}
}
}
function updateTranche(address _address)
public
{
if (userLoyalty[_address].points > loyaltyTranches[userLoyalty[_address].tranche + 1]) {
userLoyalty[_address].tranche = userLoyalty[_address].tranche + 1;
if (userLoyalty[_address].tranche == 0) {
return;
}
if (userLoyalty[_address].points < loyaltyTranches[userLoyalty[_address].tranche]) {
userLoyalty[_address].tranche = userLoyalty[_address].tranche - 1;
}
}
}
} else {
function updateTranche(address _address)
public
{
if (userLoyalty[_address].points > loyaltyTranches[userLoyalty[_address].tranche + 1]) {
userLoyalty[_address].tranche = userLoyalty[_address].tranche + 1;
if (userLoyalty[_address].tranche == 0) {
return;
}
if (userLoyalty[_address].points < loyaltyTranches[userLoyalty[_address].tranche]) {
userLoyalty[_address].tranche = userLoyalty[_address].tranche - 1;
}
}
}
function updateTranche(address _address)
public
{
if (userLoyalty[_address].points > loyaltyTranches[userLoyalty[_address].tranche + 1]) {
userLoyalty[_address].tranche = userLoyalty[_address].tranche + 1;
if (userLoyalty[_address].tranche == 0) {
return;
}
if (userLoyalty[_address].points < loyaltyTranches[userLoyalty[_address].tranche]) {
userLoyalty[_address].tranche = userLoyalty[_address].tranche - 1;
}
}
}
function _getProtocolFee(uint256 _totalFee)
internal
view
returns (uint256)
{
return _totalFee.mul(protocolFee).div(100000);
}
function setBaseFee(uint256 _newFee)
external
HasPatrol("ADMIN")
{
require(_newFee != baseFee, "No change");
require(_newFee <= 90, "Base Fee must remain below 0.09%");
baseFee = _newFee;
emit BaseFeeUpdated(msg.sender, _newFee);
}
function setProtocolFee(
uint256 _newFee
)
external
HasPatrol("ADMIN")
{
require(_newFee != baseFee, "No change");
protocolFee = _newFee;
emit ProtocolFeeUpdated(msg.sender, _newFee);
}
function setDiscountMultiplier(
uint256 _newMultiplier
)
external
HasPatrol("ADMIN")
{
discountMultiplier = _newMultiplier;
emit DiscountMultiplierUpdated(msg.sender, _newMultiplier);
}
function setLoyaltyPoint(
address _address,
uint256 _points
)
external
HasPatrol("ADMIN")
{
userLoyalty[_address].points = _points;
updateTranche(_address);
emit LoyaltyUpdated(_address, userLoyalty[_address].tranche, _points);
}
function supportsInterface(bytes4 interfaceId)
external
override
view
returns (bool)
{
return interfaceId == 0x01ffc9a7
|| interfaceId == 0x4e2312e0;
}
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
override
returns(bytes4)
{
return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"));
}
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
override
returns(bytes4)
{
return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"));
}
function getLoyaltyStats(address _user)
external
view
returns (uint256[] memory _stats)
{
_stats = new uint256[](4);
_stats[0] = userLoyalty[_user].points;
_stats[1] = userLoyalty[_user].tranche;
_stats[2] = userLoyalty[_user].staked;
_stats[3] = userLoyalty[_user].boost;
}
} | 16,997,851 | [
1,
16351,
358,
10680,
777,
324,
265,
6117,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
3176,
93,
15006,
353,
467,
1504,
93,
15006,
16,
467,
654,
39,
2499,
2539,
12952,
16,
3176,
93,
15006,
2171,
288,
203,
565,
871,
840,
304,
18706,
7381,
12,
11890,
5034,
389,
13171,
18706,
16,
2254,
5034,
389,
4139,
1769,
203,
565,
871,
3176,
93,
15006,
7381,
12,
2867,
8808,
389,
1355,
16,
2254,
5034,
389,
13171,
18706,
16,
2254,
5034,
389,
4139,
1769,
203,
565,
871,
3360,
14667,
7381,
12,
2867,
8808,
389,
1355,
16,
2254,
5034,
389,
1969,
14667,
1769,
203,
565,
871,
4547,
14667,
7381,
12,
2867,
8808,
389,
1355,
16,
2254,
5034,
389,
8373,
14667,
1769,
203,
565,
871,
3035,
1883,
23365,
7381,
12,
2867,
8808,
389,
1355,
16,
2254,
5034,
389,
20538,
1769,
203,
565,
871,
4019,
538,
305,
12,
2867,
8808,
389,
1355,
16,
2254,
5034,
389,
350,
16,
2254,
5034,
389,
8949,
1769,
203,
565,
871,
3423,
9446,
12,
2867,
8808,
389,
1355,
16,
2254,
5034,
389,
350,
16,
2254,
5034,
389,
8949,
1769,
203,
203,
203,
5666,
288,
467,
654,
39,
2499,
2539,
289,
628,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
2316,
19,
654,
39,
2499,
2539,
19,
45,
654,
39,
2499,
2539,
18,
18281,
14432,
203,
5666,
288,
467,
654,
39,
2499,
2539,
12952,
289,
628,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
2316,
19,
654,
39,
2499,
2539,
19,
45,
654,
39,
2499,
2539,
12952,
18,
18281,
14432,
203,
5666,
288,
467,
1504,
93,
15006,
289,
628,
315,
6216,
15898,
19,
45,
1504,
93,
2
] |
./full_match/11155111/0x5Faed70fF0851310dEaF48B09934e830433B8385/sources/project_/contracts/ERC20Crowdsale.sol | * @return the number of token units a buyer gets per swapToken unit./ | function swapRate(address _swapTokenAddr) public view returns (uint256) {
return _swapRates[_swapTokenAddr];
}
| 3,834,647 | [
1,
2463,
326,
1300,
434,
1147,
4971,
279,
27037,
5571,
1534,
7720,
1345,
2836,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7720,
4727,
12,
2867,
389,
22270,
1345,
3178,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
22270,
20836,
63,
67,
22270,
1345,
3178,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.13;
import "./interfaces/IERC721Full.sol";
import "./utils/SafeMath.sol";
/// @title Augur Markets interface
/// @notice Gets the winner of each market from Augur
interface IMarket
{
function getWinningPayoutNumerator(uint256 _outcome) external view returns (uint256);
}
/// @title Dai contract interface
/// @notice Various cash functions
interface Cash
{
function approve(address _spender, uint256 _amount) external returns (bool);
function balanceOf(address _ownesr) external view returns (uint256);
function faucet(uint256 _amount) external;
function transfer(address _to, uint256 _amount) external returns (bool);
function transferFrom(address _from, address _to, uint256 _amount) external returns (bool);
}
/// @title Augur OICash interface
/// @notice adding or removing open interest to secure the Augur Oracle
interface OICash
{
function deposit(uint256 _amount) external returns (bool);
function withdraw(uint256 _amount) external returns (bool);
}
//TODO: replace completesets with OICash
//TODO: update design pattens to take into account the recent changes
//TODO: change front end to only approve the same amount that is being sent
//TODO: add test where someone calls exit and they are not the current owner
//TODO: add tests where current owner calls newRental twice
// ^ will also need to figure out how to pass this number in the correct format because decimal
// ^ does not seem to work for more than 100 dai, it needs big number
/// @title Harber
/// @author Andrew Stanger
contract Harber {
using SafeMath for uint256;
/// NUMBER OF TOKENS
/// @dev also equals number of markets on augur
uint256 constant public numberOfTokens = 20;
/// CONTRACT VARIABLES
/// ERC721:
IERC721Full public team;
/// Augur contracts:
IMarket[numberOfTokens] public market;
OICash public augur;
Cash public cash;
/// UINTS, ADDRESSES, BOOLS
/// @dev my whiskey fund, for my 1% cut
address private andrewsAddress;
/// @dev the addresses of the various Augur binary markets. One market for each token. Initiated in the constructor and does not change.
address[numberOfTokens] public marketAddresses;
/// @dev in attodai (so $100 = 100000000000000000000)
uint256[numberOfTokens] public price;
/// @dev an easy way to track the above across all tokens. It should always increment at the same time as the above increments.
uint256 public totalCollected;
/// @dev used to determine the rent due. Rent is due for the period (now - timeLastCollected), at which point timeLastCollected is set to now.
uint256[numberOfTokens] public timeLastCollected;
/// @dev when a token was bought. used only for front end 'owned since' section. Rent collection only needs timeLastCollected.
uint256[numberOfTokens] public timeAcquired;
/// @dev tracks the position of the current owner in the ownerTracker mapping
uint256[numberOfTokens] public currentOwnerIndex;
/// WINNING OUTCOME VARIABLES
/// @dev start with invalid winning outcome
uint256 public winningOutcome = 42069;
//// @dev so the function to manually set the winner can only be called long after
/// @dev ...it should have resolved via Augur. Must be public so others can verify it is accurate.
uint256 public marketExpectedResolutionTime;
/// MARKET RESOLUTION VARIABLES
/// @dev step1:
bool public marketsResolved = false; // must be false for step1, true for step2
bool public marketsResolvedWithoutErrors = false; // set in step 1. If true, normal payout. If false, return all funds
/// @dev step 2:
bool public step2Complete = false; // must be false for step2, true for complete
/// @dev step 3:
bool public step3Complete = false; // must be false for step2, true for complete
/// @dev complete:
uint256 public daiAvailableToDistribute;
/// STRUCTS
struct purchase {
address owner;
uint256 price;
}
/// MAPPINGS
/// @dev keeps track of all previous owners of a token, including the price, so that if the current owner's deposit runs out,
/// @dev ...ownership can be reverted to a previous owner with the previous price. Index 0 is NOT used, this tells the contract to foreclose.
/// @dev this does NOT keep a reliable list of all owners, if it reverts to a previous owner then the next owner will overwrite the owner that was in that slot.
/// @dev the variable currentOwnerIndex is used to track the location of the current owner.
mapping (uint256 => mapping (uint256 => purchase) ) public ownerTracker;
/// @dev how many seconds each user has held each token for, for determining winnings
mapping (uint256 => mapping (address => uint256) ) public timeHeld;
/// @dev sums all the timeHelds for each token. Not required, but saves on gas when paying out. Should always increment at the same time as timeHeld
mapping (uint256 => uint256) public totalTimeHeld;
/// @dev keeps track of all the deposits for each token, for each owner. Unused deposits are not returned automatically when there is a new buyer.
/// @dev they can be withdrawn manually however. Unused deposits are returned automatically upon resolution of the market
mapping (uint256 => mapping (address => uint256) ) public deposits;
/// @dev keeps track of all the rent paid by each user. So that it can be returned in case of an invalid market outcome. Only required in this instance.
mapping (address => uint256) public collectedPerUser;
////////////// CONSTRUCTOR //////////////
constructor(address _andrewsAddress, address _addressOfToken, address _addressOfCashContract, address[numberOfTokens] memory _addressesOfMarkets, address _addressOfOICashContract, address _addressOfMainAugurContract, uint _marketExpectedResolutionTime) public
{
marketExpectedResolutionTime = _marketExpectedResolutionTime;
andrewsAddress = _andrewsAddress;
marketAddresses = _addressesOfMarkets; // this is to make the market addresses public so users can check the actual augur markets for themselves
// external contract variables:
team = IERC721Full(_addressOfToken);
cash = Cash(_addressOfCashContract);
augur = OICash(_addressOfOICashContract);
// initialise arrays
for (uint i = 0; i < numberOfTokens; i++) {
currentOwnerIndex[i]=0;
market[i] = IMarket(_addressesOfMarkets[i]);
}
// approve Augur contract to transfer this contract's dai
cash.approve(_addressOfMainAugurContract,(2**256)-1);
}
event LogNewRental(address indexed newOwner, uint256 indexed newPrice, uint256 indexed tokenId);
event LogPriceChange(uint256 indexed newPrice, uint256 indexed tokenId);
event LogForeclosure(address indexed prevOwner, uint256 indexed tokenId);
event LogRentCollection(uint256 indexed rentCollected, uint256 indexed tokenId);
event LogReturnToPreviousOwner(uint256 indexed tokenId, address indexed previousOwner);
event LogDepositWithdrawal(uint256 indexed daiWithdrawn, uint256 indexed tokenId, address indexed returnedTo);
event LogDepositIncreased(uint256 indexed daiDeposited, uint256 indexed tokenId, address indexed sentBy);
event LogExit(uint256 indexed tokenId);
event LogStep1Complete(bool indexed didAugurMarketsResolve, uint256 indexed winningOutcome, bool indexed didAugurMarketsResolveCorrectly);
event LogStep2Complete(uint256 indexed daiAvailableToDistribute);
event LogWinningsPaid(address indexed paidTo, uint256 indexed amountPaid);
event LogRentReturned(address indexed returnedTo, uint256 indexed amountReturned);
event LogAndrewPaid(uint256 indexed additionsToWhiskeyFund);
////////////// MODIFIERS //////////////
/// @notice prevents functions from being interacted with after the end of the competition
/// @dev should be on all public/external 'ordinary course of business' functions
modifier notResolved() {
require(marketsResolved == false);
_;
}
/// @notice checks the team exists
modifier tokenExists(uint256 _tokenId) {
require(_tokenId >= 0 && _tokenId < numberOfTokens, "This token does not exist");
_;
}
/// @notice what it says on the tin
modifier amountNotZero(uint256 _dai) {
require(_dai > 0, "Amount must be above zero");
_;
}
////////////// VIEW FUNCTIONS //////////////
/// @dev used in testing only
function getOwnerTrackerPrice(uint256 _tokenId, uint256 _index) public view returns (uint256) {
return (ownerTracker[_tokenId][_index].price);
}
/// @dev used in testing only
function getOwnerTrackerAddress(uint256 _tokenId, uint256 _index) public view returns (address) {
return (ownerTracker[_tokenId][_index].owner);
}
/// @dev called in collectRent function, and various other view functions
function rentOwed(uint256 _tokenId) public view returns (uint256 augurFundsDue) {
return price[_tokenId].mul(now.sub(timeLastCollected[_tokenId])).div(1 days);
}
/// @dev for front end only
/// @return how much the current owner has deposited
function liveDepositAbleToWithdraw(uint256 _tokenId) public view returns (uint256) {
uint256 _rentOwed = rentOwed(_tokenId);
address _currentOwner = team.ownerOf(_tokenId);
if(_rentOwed >= deposits[_tokenId][_currentOwner]) {
return 0;
} else {
return deposits[_tokenId][_currentOwner].sub(_rentOwed);
}
}
/// @dev for front end only
/// @return how much the current user has deposited (note: user not owner)
function userDepositAbleToWithdraw(uint256 _tokenId) public view returns (uint256) {
uint256 _rentOwed = rentOwed(_tokenId);
address _currentOwner = team.ownerOf(_tokenId);
if(_currentOwner == msg.sender) {
if(_rentOwed >= deposits[_tokenId][msg.sender]) {
return 0;
} else {
return deposits[_tokenId][msg.sender].sub(_rentOwed);
}
} else {
return deposits[_tokenId][msg.sender];
}
}
/// @dev for front end only
/// @return estimated rental expiry time
function rentalExpiryTime(uint256 _tokenId) public view returns (uint256) {
uint256 pps;
pps = price[_tokenId].div(1 days);
if (pps == 0) {
return now; //if price is so low that pps = 0 just return current time as a fallback
}
else {
return now + liveDepositAbleToWithdraw(_tokenId).div(pps);
}
}
////////////// AUGUR FUNCTIONS //////////////
// * internal *
/// @notice send the Dai to Augur
function _augurDeposit(uint256 _rentOwed) internal {
augur.deposit(_rentOwed);
}
// * internal *
/// @notice receive the Dai back from Augur
function _augurWithdraw() internal {
augur.withdraw(totalCollected);
}
// * internal *
/// @notice THIS FUNCTION HAS NOT BEEN TESTED ON AUGUR YET
/// @notice checks if all X (x = number of tokens = number of teams) markets have resolved to either yes, no, or invalid
/// @return true if yes, false if no
function _haveAllAugurMarketsResolved() internal view returns(bool) {
uint256 _resolvedOutcomesCount = 0;
for (uint i = 0; i < numberOfTokens; i++) {
// binary market has three outcomes: 0 (invalid), 1 (yes), 2 (no)
if (market[i].getWinningPayoutNumerator(0) > 0 || market[i].getWinningPayoutNumerator(1) > 0 || market[i].getWinningPayoutNumerator(2) > 0 ) {
_resolvedOutcomesCount = _resolvedOutcomesCount.add(1);
}
}
// returns true if all resolved, false otherwise
return (_resolvedOutcomesCount == numberOfTokens);
}
// * internal *
/// @notice THIS FUNCTION HAS NOT BEEN TESTED ON AUGUR YET
/// @notice checks if all markets have resolved without conflicts or errors
/// @return true if yes, false if no
/// @dev this function will also set the winningOutcome variable
function _haveAllAugurMarketsResolvedWithoutErrors() internal returns(bool) {
uint256 _winningOutcomesCount = 0;
uint256 _invalidOutcomesCount = 0;
for (uint i = 0; i < numberOfTokens; i++) {
if (market[i].getWinningPayoutNumerator(0) > 0) {
_invalidOutcomesCount = _invalidOutcomesCount.add(1);
}
if (market[i].getWinningPayoutNumerator(1) > 0) {
winningOutcome = i; // <- the winning outcome (a global variable) is set here
_winningOutcomesCount = _winningOutcomesCount.add(1);
}
}
return (_winningOutcomesCount == 1 && _invalidOutcomesCount == 0);
}
////////////// DAI CONTRACT FUNCTIONS //////////////
// * internal *
/// @notice common function for all outgoing DAI transfers
function _sendCash(address _to, uint256 _amount) internal {
require(cash.transfer(_to,_amount));
}
// * internal *
/// @notice common function for all incoming DAI transfers
function _receiveCash(address _from, uint256 _amount) internal {
require(cash.transferFrom(_from, address(this), _amount));
}
// * internal *
/// @return DAI balance of the contract
/// @dev this is used to know how much exists to payout to winners
function _getContractsCashBalance() internal view returns (uint256) {
return cash.balanceOf(address(this));
}
////////////// MARKET RESOLUTION FUNCTIONS //////////////
/// @notice the first of three functions which must be called, one after the other, to conclude the competition
/// @notice winnings can be paid out (or funds returned) only when these two steps are completed
/// @notice this function checks whether the Augur markets have resolved, and if yes, whether they resolved correct or not
/// @dev they are split into two sections due to the presence of step1BemergencyExit and step1CcircuitBreaker
/// @dev can be called by anyone
/// @dev can be called multiple times, but only once after markets have indeed resolved
/// @dev the two arguments passed are for testing only
function step1checkMarketsResolved() external {
require(marketsResolved == false, "Step1 can only be completed once");
// first check if all X markets have all resolved one way or the other
if (_haveAllAugurMarketsResolved()) {
// do a final rent collection before the contract is locked down
collectRentAllTokens();
// lock everything down
marketsResolved = true;
// now check if they all resolved without errors. It is set to false upon contract initialisation
// this function also sets winningOutcome if there is one
if (_haveAllAugurMarketsResolvedWithoutErrors()) {
marketsResolvedWithoutErrors = true;
}
emit LogStep1Complete(true, winningOutcome, marketsResolvedWithoutErrors);
}
}
/// @notice emergency function in case the augur markets never resolve for whatever reason
/// @notice returns all funds to all users
/// @notice can only be called 6 months after augur markets should have ended
function step1BemergencyExit() external {
require(marketsResolved == false, "Step1 can only be completed once");
require(now > (marketExpectedResolutionTime + 15778800), "Must wait 6 months for Augur Oracle");
collectRentAllTokens();
marketsResolved = true;
emit LogStep1Complete(false, winningOutcome, false);
}
/// @notice Same as above, except that only I can call it, and I can call it whenever
/// @notice to be clear, this only allows me to return all funds. I can not set a winner.
function step1CcircuitBreaker() external {
require(marketsResolved == false, "Step1 can only be completed once");
require(msg.sender == andrewsAddress, "Only owner can call this");
collectRentAllTokens();
marketsResolved = true;
emit LogStep1Complete(false, winningOutcome, false);
}
/// @notice the second of the three functions which must be called, one after the other, to conclude the competition
/// @dev gets funds back from Augur, gets the available funds for distribution
/// @dev can be called by anyone, but only once
function step2withdrawFromAugur() external {
require(marketsResolved == true, "Must wait for market resolution");
require(step2Complete == false, "Step2 should only be run once");
step2Complete = true;
uint256 _balanceBefore = _getContractsCashBalance();
_augurWithdraw();
uint256 _balanceAfter = _getContractsCashBalance();
// daiAvailableToDistribute therefore does not include unused deposits
daiAvailableToDistribute = _balanceAfter.sub(_balanceBefore);
emit LogStep2Complete(daiAvailableToDistribute);
}
/// @notice the final of the three functions which must be called, one after the other, to conclude the competition
/// @notice pays me my 1% if markets resolved correctly. If not I don't deserve shit
/// @dev this was originally included within step3 but it was modifed so that ineraction with Dai contract happened at the end
function step3payAndrew() external {
require(step2Complete == true, "Must wait for market resolution");
require(step3Complete == false, "Step3 should only be run once");
step3Complete = true;
if (marketsResolvedWithoutErrors) {
uint256 _andrewsWellEarntMonies = daiAvailableToDistribute.div(100);
daiAvailableToDistribute = daiAvailableToDistribute.sub(_andrewsWellEarntMonies);
_sendCash(andrewsAddress,_andrewsWellEarntMonies);
emit LogAndrewPaid(_andrewsWellEarntMonies);
}
}
/// @notice the final function of the competition resolution process. Pays out winnings, or returns funds, as necessary
/// @dev users pull dai into their account. Replaces previous push vesion which required looping over unbounded mapping.
function complete() external {
require(step3Complete == true, "Step3 must be completed first");
if (marketsResolvedWithoutErrors) {
_payoutWinnings();
}
else {
_returnRent();
}
}
// * internal *
/// @notice pays winnings to the winners
/// @dev must be internal and only called by complete
function _payoutWinnings() internal {
uint256 _winnersTimeHeld = timeHeld[winningOutcome][msg.sender];
if (_winnersTimeHeld > 0) {
timeHeld[winningOutcome][msg.sender] = 0; // otherwise they can keep paying themselves over and over
uint256 _numerator = daiAvailableToDistribute.mul(_winnersTimeHeld);
uint256 _winningsToTransfer = _numerator.div(totalTimeHeld[winningOutcome]);
_sendCash(msg.sender, _winningsToTransfer);
emit LogWinningsPaid(msg.sender, _winningsToTransfer);
}
}
// * internal *
/// @notice returns all funds to users in case of invalid outcome
/// @dev must be internal and only called by complete
function _returnRent() internal {
uint256 _rentCollected = collectedPerUser[msg.sender];
if (_rentCollected > 0) {
collectedPerUser[msg.sender] = 0; // otherwise they can keep paying themselves over and over
uint256 _numerator = daiAvailableToDistribute.mul(_rentCollected);
uint256 _rentToToReturn = _numerator.div(totalCollected);
_sendCash(msg.sender, _rentToToReturn);
emit LogRentReturned(msg.sender, _rentToToReturn);
}
}
/// @notice withdraw full deposit after markets have resolved
/// @dev the other withdraw deposit functions are locked when markets have resolved so must use this one
/// @dev ... which can only be called if markets have resolved. This function is also different in that it does
/// @dev ... not attempt to collect rent or transfer ownership to a previous owner
function withdrawDepositAfterResolution() external {
require(marketsResolved == true, "step1 must be completed first");
for (uint i = 0; i < numberOfTokens; i++) {
uint256 _depositToReturn = deposits[i][msg.sender];
if (_depositToReturn > 0) {
deposits[i][msg.sender] = 0;
_sendCash(msg.sender, _depositToReturn);
emit LogDepositWithdrawal(_depositToReturn, i, msg.sender);
}
}
}
////////////// ORDINARY COURSE OF BUSINESS FUNCTIONS //////////////
/// @notice collects rent for all tokens
/// @dev makes it easy for me to call whenever I want to keep people paying their rent, thus cannot be internal
/// @dev cannot be external because it is called within the step1 functions, therefore public
function collectRentAllTokens() public notResolved() {
for (uint i = 0; i < numberOfTokens; i++) {
_collectRent(i);
}
}
/// @notice collects rent for a specific token
/// @dev also calculates and updates how long the current user has held the token for
/// @dev called frequently internally, so cant be external.
/// @dev is not a problem if called externally, but making internal to save gas
function _collectRent(uint256 _tokenId) internal notResolved() {
//only collect rent if the token is owned (ie, if owned by the contract this implies unowned)
if (team.ownerOf(_tokenId) != address(this)) {
uint256 _rentOwed = rentOwed(_tokenId);
address _currentOwner = team.ownerOf(_tokenId);
uint256 _timeOfThisCollection;
if (_rentOwed >= deposits[_tokenId][_currentOwner]) {
// run out of deposit. Calculate time it was actually paid for, then revert to previous owner
_timeOfThisCollection = timeLastCollected[_tokenId].add(((now.sub(timeLastCollected[_tokenId])).mul(deposits[_tokenId][_currentOwner]).div(_rentOwed)));
_rentOwed = deposits[_tokenId][_currentOwner]; // take what's left
_revertToPreviousOwner(_tokenId);
} else {
// normal collection
_timeOfThisCollection = now;
}
// decrease deposit by rent owed
deposits[_tokenId][_currentOwner] = deposits[_tokenId][_currentOwner].sub(_rentOwed);
// the 'important bit', where the duration the token has been held by each user is updated
// it is essential that timeHeld and totalTimeHeld are incremented together such that the sum of
// the first is equal to the second
uint256 _timeHeldToIncrement = (_timeOfThisCollection.sub(timeLastCollected[_tokenId])); //just for readability
timeHeld[_tokenId][_currentOwner] = timeHeld[_tokenId][_currentOwner].add(_timeHeldToIncrement);
totalTimeHeld[_tokenId] = totalTimeHeld[_tokenId].add(_timeHeldToIncrement);
// it is also essential that collectedPerUser and totalCollected are all incremented together
// such that the sum of the first two (individually) is equal to the third
collectedPerUser[_currentOwner] = collectedPerUser[_currentOwner].add(_rentOwed);
totalCollected = totalCollected.add(_rentOwed);
_augurDeposit(_rentOwed);
emit LogRentCollection(_rentOwed, _tokenId);
}
// timeLastCollected is updated regardless of whether the token is owned, so that the clock starts ticking
// ... when the first owner buys it, because this function is run before ownership changes upon calling
// ... newRental
timeLastCollected[_tokenId] = now;
}
/// @notice to rent a token
function newRental(uint256 _newPrice, uint256 _tokenId, uint256 _deposit) external tokenExists(_tokenId) amountNotZero(_deposit) notResolved() {
require(_newPrice > price[_tokenId], "Price must be higher than current price");
_collectRent(_tokenId);
// require(1==2, "STFU");
address _currentOwner = team.ownerOf(_tokenId);
if (_currentOwner == msg.sender) {
// bought by current owner (ie, token ownership does not change, so it is as if the current owner
// ... called changePrice and depositDai seperately)
_changePrice(_newPrice, _tokenId);
_depositDai(_deposit, _tokenId);
} else {
// bought by different user (the normal situation)
// deposits are updated via depositDai function if _currentOwner = msg.sender
// therefore deposits only updated inside this else section
deposits[_tokenId][msg.sender] = deposits[_tokenId][msg.sender].add(_deposit);
// update currentOwnerIndex and ownerTracker
currentOwnerIndex[_tokenId] = currentOwnerIndex[_tokenId].add(1);
ownerTracker[_tokenId][currentOwnerIndex[_tokenId]].price = _newPrice;
ownerTracker[_tokenId][currentOwnerIndex[_tokenId]].owner = msg.sender;
// update timeAcquired for the front end
timeAcquired[_tokenId] = now;
_transferTokenTo(_currentOwner, msg.sender, _newPrice, _tokenId);
_receiveCash(msg.sender, _deposit);
emit LogNewRental(msg.sender, _newPrice, _tokenId);
}
}
/// @notice add new dai deposit to an existing rental
/// @dev it is possible a user's deposit could be reduced to zero following _collectRent
/// @dev they would then increase their deposit despite no longer owning it
/// @dev this is ok, they can withdraw via withdrawDeposit.
function depositDai(uint256 _dai, uint256 _tokenId) external amountNotZero(_dai) tokenExists(_tokenId) notResolved() {
_collectRent(_tokenId);
_depositDai(_dai, _tokenId);
}
/// @dev depositDai is split into two, because it needs to be called direct from newRental
/// @dev ... without collecing rent first (otherwise it would be collected twice, possibly causing logic errors)
function _depositDai(uint256 _dai, uint256 _tokenId) internal {
deposits[_tokenId][msg.sender] = deposits[_tokenId][msg.sender].add(_dai);
_receiveCash(msg.sender, _dai);
emit LogDepositIncreased(_dai, _tokenId, msg.sender);
}
/// @notice increase the price of an existing rental
/// @dev can't be external because also called within newRental
function changePrice(uint256 _newPrice, uint256 _tokenId) public tokenExists(_tokenId) notResolved() {
require(_newPrice > price[_tokenId], "New price must be higher than current price");
require(msg.sender == team.ownerOf(_tokenId), "Not owner");
_collectRent(_tokenId);
_changePrice(_newPrice, _tokenId);
}
/// @dev changePrice is split into two, because it needs to be called direct from newRental
/// @dev ... without collecing rent first (otherwise it would be collected twice, possibly causing logic errors)
function _changePrice(uint256 _newPrice, uint256 _tokenId) internal {
// below is the only instance when price is modifed outside of the _transferTokenTo function
price[_tokenId] = _newPrice;
ownerTracker[_tokenId][currentOwnerIndex[_tokenId]].price = _newPrice;
emit LogPriceChange(price[_tokenId], _tokenId);
}
/// @notice withdraw deposit
/// @dev do not need to be the current owner
function withdrawDeposit(uint256 _dai, uint256 _tokenId) external amountNotZero(_dai) tokenExists(_tokenId) notResolved() returns (uint256) {
_collectRent(_tokenId);
// if statement needed because deposit may have just reduced to zero following _collectRent
if (deposits[_tokenId][msg.sender] > 0) {
_withdrawDeposit(_dai, _tokenId);
emit LogDepositWithdrawal(_dai, _tokenId, msg.sender);
}
}
/// @notice withdraw full deposit
/// @dev do not need to be the current owner
function exit(uint256 _tokenId) external tokenExists(_tokenId) notResolved() {
_collectRent(_tokenId);
// if statement needed because deposit may have just reduced to zero following _collectRent modifier
if (deposits[_tokenId][msg.sender] > 0) {
_withdrawDeposit(deposits[_tokenId][msg.sender], _tokenId);
emit LogExit(_tokenId);
}
}
/* internal */
/// @notice actually withdraw the deposit and call _revertToPreviousOwner if necessary
function _withdrawDeposit(uint256 _dai, uint256 _tokenId) internal {
require(deposits[_tokenId][msg.sender] >= _dai, 'Withdrawing too much');
deposits[_tokenId][msg.sender] = deposits[_tokenId][msg.sender].sub(_dai);
address _currentOwner = team.ownerOf(_tokenId);
if(_currentOwner == msg.sender && deposits[_tokenId][msg.sender] == 0) {
_revertToPreviousOwner(_tokenId);
}
_sendCash(msg.sender, _dai);
}
/* internal */
/// @notice if a users deposit runs out, either return to previous owner or foreclose
function _revertToPreviousOwner(uint256 _tokenId) internal {
bool _reverted = false;
bool _toForeclose = false;
uint256 _index;
address _previousOwner;
while (_reverted == false) {
assert(currentOwnerIndex[_tokenId] >=0);
currentOwnerIndex[_tokenId] = currentOwnerIndex[_tokenId].sub(1); // currentOwnerIndex will now point to previous owner
_index = currentOwnerIndex[_tokenId]; // just for readability
_previousOwner = ownerTracker[_tokenId][_index].owner;
//if no previous owners. price -> zero, foreclose
//if previous owner still has a deposit, transfer to them, update the price to what it used to be
if (_index == 0) {
_toForeclose = true;
_reverted = true;
} else if (deposits[_tokenId][_previousOwner] > 0) {
_reverted = true;
}
}
if (_toForeclose) {
_foreclose(_tokenId);
} else {
address _currentOwner = team.ownerOf(_tokenId);
uint256 _oldPrice = ownerTracker[_tokenId][_index].price;
_transferTokenTo(_currentOwner, _previousOwner, _oldPrice, _tokenId);
emit LogReturnToPreviousOwner(_tokenId, _previousOwner);
}
}
/* internal */
/// @notice return token to the contract and return price to zero
function _foreclose(uint256 _tokenId) internal {
address _currentOwner = team.ownerOf(_tokenId);
// third field is price, ie price goes to zero
_transferTokenTo(_currentOwner, address(this), 0, _tokenId);
emit LogForeclosure(_currentOwner, _tokenId);
}
/* internal */
/// @notice transfer ERC 721 between users
/// @dev there is no event emitted as this is handled in ERC721.sol
function _transferTokenTo(address _currentOwner, address _newOwner, uint256 _newPrice, uint256 _tokenId) internal {
require(_currentOwner != address(0) && _newOwner != address(0) , "Cannot send to/from zero address");
team.transferFrom(_currentOwner, _newOwner, _tokenId);
price[_tokenId] = _newPrice;
}
}
| NUMBER OF TOKENS @dev also equals number of markets on augur CONTRACT VARIABLES ERC721: Augur contracts: UINTS, ADDRESSES, BOOLS @dev my whiskey fund, for my 1% cut @dev the addresses of the various Augur binary markets. One market for each token. Initiated in the constructor and does not change. @dev in attodai (so $100 = 100000000000000000000) @dev an easy way to track the above across all tokens. It should always increment at the same time as the above increments. @dev used to determine the rent due. Rent is due for the period (now - timeLastCollected), at which point timeLastCollected is set to now. @dev when a token was bought. used only for front end 'owned since' section. Rent collection only needs timeLastCollected. @dev tracks the position of the current owner in the ownerTracker mapping WINNING OUTCOME VARIABLES @dev start with invalid winning outcome/ @dev so the function to manually set the winner can only be called long after @dev ...it should have resolved via Augur. Must be public so others can verify it is accurate. MARKET RESOLUTION VARIABLES @dev step1: @dev step 2: @dev step 3: @dev complete: STRUCTS | struct purchase {
address owner;
uint256 price;
}
| 15,828,417 | [
1,
9931,
15932,
14275,
55,
225,
2546,
1606,
1300,
434,
2267,
2413,
603,
31350,
295,
8020,
2849,
1268,
22965,
55,
4232,
39,
27,
5340,
30,
432,
637,
295,
20092,
30,
27011,
55,
16,
11689,
7031,
1090,
55,
16,
9784,
1741,
55,
225,
3399,
600,
291,
856,
284,
1074,
16,
364,
3399,
404,
9,
6391,
225,
326,
6138,
434,
326,
11191,
432,
637,
295,
3112,
2267,
2413,
18,
6942,
13667,
364,
1517,
1147,
18,
4378,
10206,
316,
326,
3885,
471,
1552,
486,
2549,
18,
225,
316,
2403,
369,
10658,
261,
2048,
271,
6625,
273,
2130,
12648,
2787,
9449,
13,
225,
392,
12779,
4031,
358,
3298,
326,
5721,
10279,
777,
2430,
18,
2597,
1410,
3712,
5504,
622,
326,
1967,
813,
487,
326,
5721,
17071,
18,
225,
1399,
358,
4199,
326,
283,
496,
6541,
18,
534,
319,
353,
6541,
364,
326,
3879,
261,
3338,
300,
813,
3024,
10808,
329,
3631,
622,
1492,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
565,
1958,
23701,
288,
203,
3639,
1758,
3410,
31,
203,
3639,
2254,
5034,
6205,
31,
203,
565,
289,
203,
377,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x36F7f4C293569C1c070E9Ea8D8ce2589c69Ab676/sources/browser/tests/DoTxGameContractV2.sol | * Elect the winner based on open prices & close prices/Set winner house | function selectWinner(uint256 warIndex) public onlyOwner onlyIfCurrentWarFinished(warIndex) onlyIfPricesFetched(warIndex) {
require(wars[warIndex].winningHouse == 0, "Winner already selected");
int256 precision = int256(selectWinnerPrecision);
int256 firstHousePerf = dotxLib.calculateHousePerf(int256(wars[warIndex].firstHouse.openPrice), int256(wars[warIndex].firstHouse.closePrice), precision);
int256 secondHousePerf = dotxLib.calculateHousePerf(int256(wars[warIndex].secondHouse.openPrice), int256(wars[warIndex].secondHouse.closePrice), precision);
wars[warIndex].winningHouse = (firstHousePerf > secondHousePerf ? wars[warIndex].firstHouse : wars[warIndex].secondHouse).houseTicker;
House memory losingHouse = (firstHousePerf > secondHousePerf ? wars[warIndex].secondHouse : wars[warIndex].firstHouse);
BURN X% OF LOSING HOUSE'S DOTX
uint256 burnValue = calculateBurnStaking(losingHouse, true, warIndex);
dotxToken.transfer(BURN_ADDRESS, burnValue);
SEND X% OF LOSING HOUSE'S DOTX TO STAKING ADDRESSES
uint256 stakingValue = calculateBurnStaking(losingHouse, false, warIndex);
sendToStakingPools(stakingValue, warIndex);
emit StakeBurn(warIndex, burnValue, stakingValue);
| 9,445,964 | [
1,
17817,
326,
5657,
1224,
2511,
603,
1696,
19827,
473,
1746,
19827,
19,
694,
5657,
1224,
23867,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2027,
59,
7872,
12,
11890,
5034,
21983,
1016,
13,
1071,
1338,
5541,
1338,
2047,
3935,
30634,
10577,
12,
905,
1016,
13,
1338,
2047,
31862,
30771,
12,
905,
1016,
13,
288,
203,
3639,
2583,
12,
905,
87,
63,
905,
1016,
8009,
8082,
2093,
44,
3793,
422,
374,
16,
315,
59,
7872,
1818,
3170,
8863,
203,
540,
203,
3639,
509,
5034,
6039,
273,
509,
5034,
12,
4025,
59,
7872,
15410,
1769,
203,
540,
203,
3639,
509,
5034,
1122,
44,
3793,
22016,
273,
225,
3928,
92,
5664,
18,
11162,
44,
3793,
22016,
12,
474,
5034,
12,
905,
87,
63,
905,
1016,
8009,
3645,
44,
3793,
18,
3190,
5147,
3631,
509,
5034,
12,
905,
87,
63,
905,
1016,
8009,
3645,
44,
3793,
18,
4412,
5147,
3631,
6039,
1769,
203,
3639,
509,
5034,
2205,
44,
3793,
22016,
273,
3928,
92,
5664,
18,
11162,
44,
3793,
22016,
12,
474,
5034,
12,
905,
87,
63,
905,
1016,
8009,
8538,
44,
3793,
18,
3190,
5147,
3631,
509,
5034,
12,
905,
87,
63,
905,
1016,
8009,
8538,
44,
3793,
18,
4412,
5147,
3631,
6039,
1769,
203,
540,
203,
3639,
341,
5913,
63,
905,
1016,
8009,
8082,
2093,
44,
3793,
273,
261,
3645,
44,
3793,
22016,
405,
2205,
44,
3793,
22016,
692,
341,
5913,
63,
905,
1016,
8009,
3645,
44,
3793,
294,
341,
5913,
63,
905,
1016,
8009,
8538,
44,
3793,
2934,
13028,
18008,
31,
203,
3639,
670,
3793,
3778,
437,
2470,
44,
3793,
273,
261,
3645,
44,
3793,
22016,
405,
2205,
44,
3793,
22016,
692,
341,
5913,
63,
905,
1016,
8009,
2
] |
./partial_match/100/0x81A194828e3c8e3ac91668E93A8A202dF505ACBa/sources/PriceBettingT1S2.sol | File: @openzeppelin/contracts/GSN/Context.sol | abstract contract Context {
pragma solidity ^0.7.5;
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
}
| 16,649,716 | [
1,
812,
30,
632,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
43,
13653,
19,
1042,
18,
18281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
1772,
288,
203,
683,
9454,
18035,
560,
3602,
20,
18,
27,
18,
25,
31,
203,
565,
445,
389,
3576,
12021,
1435,
2713,
1476,
5024,
1135,
261,
2867,
8843,
429,
13,
288,
203,
3639,
327,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/8453/0x1a920B29eBD437074225cAeE44f78FC700B27a5d/sources/contracts/interfaces/IWETH9.sol | WETH9 specific interface | interface IWETH9 is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
import { IERC20 } from './IERC20.sol';
}
| 11,536,270 | [
1,
59,
1584,
44,
29,
2923,
1560,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
59,
1584,
44,
29,
353,
467,
654,
39,
3462,
288,
203,
565,
445,
443,
1724,
1435,
3903,
8843,
429,
31,
203,
203,
565,
445,
598,
9446,
12,
11890,
5034,
3844,
13,
3903,
31,
203,
203,
5666,
288,
467,
654,
39,
3462,
289,
628,
12871,
45,
654,
39,
3462,
18,
18281,
13506,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x41c42626DfED6576a1a7d4974b39986bA9D1848d/sources/project_/contracts/utils/roles/TokenRoles.sol | * @notice Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner. If the current owner is also the current manager, then the manager address is also updated to be the new owner @param newOwner The address of the new owner/ | function transferOwnership(address newOwner)
public
virtual
override
onlyOwner
{
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
_setOwner(newOwner);
}
| 1,893,082 | [
1,
1429,
18881,
23178,
434,
326,
6835,
358,
279,
394,
2236,
21863,
2704,
5541,
68,
2934,
4480,
1338,
506,
2566,
635,
326,
783,
3410,
18,
971,
326,
783,
3410,
353,
2546,
326,
783,
3301,
16,
1508,
326,
3301,
1758,
353,
2546,
3526,
358,
506,
326,
394,
3410,
225,
394,
5541,
1021,
1758,
434,
326,
394,
3410,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7412,
5460,
12565,
12,
2867,
394,
5541,
13,
203,
3639,
1071,
203,
3639,
5024,
203,
3639,
3849,
203,
3639,
1338,
5541,
203,
565,
288,
203,
3639,
2583,
12,
203,
5411,
394,
5541,
480,
1758,
12,
20,
3631,
203,
5411,
315,
5460,
429,
30,
394,
3410,
353,
326,
3634,
1758,
6,
203,
3639,
11272,
203,
3639,
389,
542,
5541,
12,
2704,
5541,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.13;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "../common/FixidityLib.sol";
import "../common/Initializable.sol";
import "../common/UsingRegistry.sol";
import "../common/interfaces/ICeloVersionedContract.sol";
import "../common/libraries/ReentrancyGuard.sol";
import "../stability/interfaces/IStableToken.sol";
/**
* @title Facilitates large exchanges between CELO stable tokens.
*/
contract GrandaMento is
ICeloVersionedContract,
Ownable,
Initializable,
UsingRegistry,
ReentrancyGuard
{
using FixidityLib for FixidityLib.Fraction;
using SafeMath for uint256;
// Emitted when a new exchange proposal is created.
event ExchangeProposalCreated(
uint256 indexed proposalId,
address indexed exchanger,
string stableTokenRegistryId,
uint256 sellAmount,
uint256 buyAmount,
bool sellCelo
);
// Emitted when an exchange proposal is approved by the approver.
event ExchangeProposalApproved(uint256 indexed proposalId);
// Emitted when an exchange proposal is cancelled.
event ExchangeProposalCancelled(uint256 indexed proposalId);
// Emitted when an exchange proposal is executed.
event ExchangeProposalExecuted(uint256 indexed proposalId);
// Emitted when the approver is set.
event ApproverSet(address approver);
// Emitted when maxApprovalExchangeRateChange is set.
event MaxApprovalExchangeRateChangeSet(uint256 maxApprovalExchangeRateChange);
// Emitted when the spread is set.
event SpreadSet(uint256 spread);
// Emitted when the veto period in seconds is set.
event VetoPeriodSecondsSet(uint256 vetoPeriodSeconds);
// Emitted when the exchange limits for a stable token are set.
event StableTokenExchangeLimitsSet(
string stableTokenRegistryId,
uint256 minExchangeAmount,
uint256 maxExchangeAmount
);
enum ExchangeProposalState { None, Proposed, Approved, Executed, Cancelled }
struct ExchangeLimits {
// The minimum amount of an asset that can be exchanged in a single proposal.
uint256 minExchangeAmount;
// The maximum amount of an asset that can be exchanged in a single proposal.
uint256 maxExchangeAmount;
}
struct ExchangeProposal {
// The exchanger/proposer of the exchange proposal.
address payable exchanger;
// The stable token involved in this proposal. This is stored rather than
// the stable token's registry ID in case the contract address is changed
// after a proposal is created, which could affect refunding or burning the
// stable token.
address stableToken;
// The state of the exchange proposal.
ExchangeProposalState state;
// Whether the exchanger is selling CELO and buying stableToken.
bool sellCelo;
// The amount of the sell token being sold. If a stable token is being sold,
// the amount of stable token in "units" is stored rather than the "value."
// This is because stable tokens may experience demurrage/inflation, where
// the amount of stable token "units" doesn't change with time, but the "value"
// does. This is important to ensure the correct inflation-adjusted amount
// of the stable token is transferred out of this contract when a deposit is
// refunded or an exchange selling the stable token is executed.
// See StableToken.sol for more details on what "units" vs "values" are.
uint256 sellAmount;
// The amount of the buy token being bought. For stable tokens, this is
// kept track of as the value, not units.
uint256 buyAmount;
// The price of CELO quoted in stableToken at the time of the exchange proposal
// creation. This is the price used to calculate the buyAmount. Used for a
// safety check when an approval is being made that the price isn't wildly
// different. Recalculating buyAmount is not sufficient because if a stable token
// is being sold that has demurrage enabled, the original value when the stable
// tokens were deposited cannot be calculated.
uint256 celoStableTokenExchangeRate;
// The veto period in seconds at the time the proposal was created. This is kept
// track of on a per-proposal basis to lock-in the veto period for a proposal so
// that changes to the contract's vetoPeriodSeconds do not affect existing
// proposals.
uint256 vetoPeriodSeconds;
// The timestamp (`block.timestamp`) at which the exchange proposal was approved
// in seconds. If the exchange proposal has not ever been approved, is 0.
uint256 approvalTimestamp;
}
// The address with the authority to approve exchange proposals.
address public approver;
// The maximum allowed change in the CELO/stable token price when an exchange proposal
// is being approved relative to the rate when the exchange proposal was created.
FixidityLib.Fraction public maxApprovalExchangeRateChange;
// The percent fee imposed upon an exchange execution.
FixidityLib.Fraction public spread;
// The period in seconds after an approval during which an exchange proposal can be vetoed.
uint256 public vetoPeriodSeconds;
// The minimum and maximum amount of the stable token that can be minted or
// burned in a single exchange. Indexed by the stable token registry identifier string.
mapping(string => ExchangeLimits) public stableTokenExchangeLimits;
// State for all exchange proposals. Indexed by the exchange proposal ID.
mapping(uint256 => ExchangeProposal) public exchangeProposals;
// An array containing a superset of the IDs of exchange proposals that are currently
// in the Proposed or Approved state. Intended to allow easy viewing of all active
// exchange proposals. It's possible for a proposal ID in this array to no longer be
// active, so filtering is required to find the true set of active proposal IDs.
// A superset is kept because exchange proposal vetoes, intended to be done
// by Governance, effectively go through a multi-day timelock. If the veto
// call was required to provide the index in an array of activeProposalIds to
// remove corresponding to the vetoed exchange proposal, the timelock could result
// in the provided index being stale by the time the veto would be executed.
// Alternative approaches exist, like maintaining a linkedlist of active proposal
// IDs, but this approach was chosen for its low implementation complexity.
uint256[] public activeProposalIdsSuperset;
// Number of exchange proposals that have ever been created. Used for assigning
// an exchange proposal ID to a new proposal.
uint256 public exchangeProposalCount;
/**
* @notice Reverts if the sender is not the approver.
*/
modifier onlyApprover() {
require(msg.sender == approver, "Sender must be approver");
_;
}
/**
* @notice Sets initialized == true on implementation contracts.
* @param test Set to true to skip implementation initialization.
*/
constructor(bool test) public Initializable(test) {}
/**
* @notice Returns the storage, major, minor, and patch version of the contract.
* @return The storage, major, minor, and patch version of the contract.
*/
function getVersionNumber() external pure returns (uint256, uint256, uint256, uint256) {
return (1, 1, 0, 0);
}
/**
* @notice Used in place of the constructor to allow the contract to be upgradable via proxy.
* @param _registry The address of the registry.
* @param _approver The approver that has the ability to approve exchange proposals.
* @param _maxApprovalExchangeRateChange The maximum allowed change in CELO price
* between an exchange proposal's creation and approval.
* @param _spread The spread charged on exchanges.
* @param _vetoPeriodSeconds The length of the veto period in seconds.
*/
function initialize(
address _registry,
address _approver,
uint256 _maxApprovalExchangeRateChange,
uint256 _spread,
uint256 _vetoPeriodSeconds
) external initializer {
_transferOwnership(msg.sender);
setRegistry(_registry);
setApprover(_approver);
setMaxApprovalExchangeRateChange(_maxApprovalExchangeRateChange);
setSpread(_spread);
setVetoPeriodSeconds(_vetoPeriodSeconds);
}
/**
* @notice Creates a new exchange proposal and deposits the tokens being sold.
* @dev Stable token value amounts are used for the sellAmount, not unit amounts.
* @param stableTokenRegistryId The string registry ID for the stable token
* involved in the exchange.
* @param sellAmount The amount of the sell token being sold.
* @param sellCelo Whether CELO is being sold.
* @return The proposal identifier for the newly created exchange proposal.
*/
function createExchangeProposal(
string calldata stableTokenRegistryId,
uint256 sellAmount,
bool sellCelo
) external nonReentrant returns (uint256) {
address stableToken = registry.getAddressForStringOrDie(stableTokenRegistryId);
// Gets the price of CELO quoted in stableToken.
uint256 celoStableTokenExchangeRate = getOracleExchangeRate(stableToken).unwrap();
// Using the current oracle exchange rate, calculate what the buy amount is.
// This takes the spread into consideration.
uint256 buyAmount = getBuyAmount(celoStableTokenExchangeRate, sellAmount, sellCelo);
// Create new scope to prevent a stack too deep error.
{
// Get the minimum and maximum amount of stable token than can be involved
// in the exchange. This reverts if exchange limits for the stable token have
// not been set.
(uint256 minExchangeAmount, uint256 maxExchangeAmount) = getStableTokenExchangeLimits(
stableTokenRegistryId
);
// Ensure that the amount of stableToken being bought or sold is within
// the configurable exchange limits.
uint256 stableTokenExchangeAmount = sellCelo ? buyAmount : sellAmount;
require(
stableTokenExchangeAmount <= maxExchangeAmount &&
stableTokenExchangeAmount >= minExchangeAmount,
"Stable token exchange amount not within limits"
);
}
// Deposit the assets being sold.
IERC20 sellToken = sellCelo ? getGoldToken() : IERC20(stableToken);
require(
sellToken.transferFrom(msg.sender, address(this), sellAmount),
"Transfer in of sell token failed"
);
// Record the proposal.
// Add 1 to the running proposal count, and use the updated proposal count as
// the proposal ID. Proposal IDs intentionally start at 1.
exchangeProposalCount = exchangeProposalCount.add(1);
// For stable tokens, the amount is stored in units to deal with demurrage.
uint256 storedSellAmount = sellCelo
? sellAmount
: IStableToken(stableToken).valueToUnits(sellAmount);
exchangeProposals[exchangeProposalCount] = ExchangeProposal({
exchanger: msg.sender,
stableToken: stableToken,
state: ExchangeProposalState.Proposed,
sellCelo: sellCelo,
sellAmount: storedSellAmount,
buyAmount: buyAmount,
celoStableTokenExchangeRate: celoStableTokenExchangeRate,
vetoPeriodSeconds: vetoPeriodSeconds,
approvalTimestamp: 0 // initial value when not approved yet
});
// StableToken.unitsToValue (called within getSellTokenAndSellAmount) can
// overflow for very large StableToken amounts. Call it here as a sanity
// check, so that the overflow happens here, blocking proposal creation
// rather than when attempting to execute the proposal, which would lock
// funds in this contract.
getSellTokenAndSellAmount(exchangeProposals[exchangeProposalCount]);
// Push it into the array of active proposals.
activeProposalIdsSuperset.push(exchangeProposalCount);
// Even if stable tokens are being sold, the sellAmount emitted is the "value."
emit ExchangeProposalCreated(
exchangeProposalCount,
msg.sender,
stableTokenRegistryId,
sellAmount,
buyAmount,
sellCelo
);
return exchangeProposalCount;
}
/**
* @notice Approves an existing exchange proposal.
* @dev Sender must be the approver. Exchange proposal must be in the Proposed state.
* @param proposalId The identifier of the proposal to approve.
*/
function approveExchangeProposal(uint256 proposalId) external nonReentrant onlyApprover {
ExchangeProposal storage proposal = exchangeProposals[proposalId];
// Ensure the proposal is in the Proposed state.
require(proposal.state == ExchangeProposalState.Proposed, "Proposal must be in Proposed state");
// Ensure the change in the current price of CELO quoted in the stable token
// relative to the value when the proposal was created is within the allowed limit.
FixidityLib.Fraction memory currentRate = getOracleExchangeRate(proposal.stableToken);
FixidityLib.Fraction memory proposalRate = FixidityLib.wrap(
proposal.celoStableTokenExchangeRate
);
(FixidityLib.Fraction memory lesserRate, FixidityLib.Fraction memory greaterRate) = currentRate
.lt(proposalRate)
? (currentRate, proposalRate)
: (proposalRate, currentRate);
FixidityLib.Fraction memory rateChange = greaterRate.subtract(lesserRate).divide(proposalRate);
require(
rateChange.lte(maxApprovalExchangeRateChange),
"CELO exchange rate is too different from the proposed price"
);
// Set the time the approval occurred and change the state.
proposal.approvalTimestamp = block.timestamp;
proposal.state = ExchangeProposalState.Approved;
emit ExchangeProposalApproved(proposalId);
}
/**
* @notice Cancels an exchange proposal.
* @dev Only callable by the exchanger if the proposal is in the Proposed state
* or the owner if the proposal is in the Approved state.
* @param proposalId The identifier of the proposal to cancel.
*/
function cancelExchangeProposal(uint256 proposalId) external nonReentrant {
ExchangeProposal storage proposal = exchangeProposals[proposalId];
// Require the appropriate state and sender.
// This will also revert if a proposalId is given that does not correspond
// to a previously created exchange proposal.
if (proposal.state == ExchangeProposalState.Proposed) {
require(proposal.exchanger == msg.sender, "Sender must be exchanger");
} else if (proposal.state == ExchangeProposalState.Approved) {
require(isOwner(), "Sender must be owner");
} else {
revert("Proposal must be in Proposed or Approved state");
}
// Mark the proposal as cancelled. Do so prior to refunding as a measure against reentrancy.
proposal.state = ExchangeProposalState.Cancelled;
// Get the token and amount that will be refunded to the proposer.
(IERC20 refundToken, uint256 refundAmount) = getSellTokenAndSellAmount(proposal);
// Finally, transfer out the deposited funds.
require(
refundToken.transfer(proposal.exchanger, refundAmount),
"Transfer out of refund token failed"
);
emit ExchangeProposalCancelled(proposalId);
}
/**
* @notice Executes an exchange proposal that's been approved and not vetoed.
* @dev Callable by anyone. Reverts if the proposal is not in the Approved state
* or proposal.vetoPeriodSeconds has not elapsed since approval.
* @param proposalId The identifier of the proposal to execute.
*/
function executeExchangeProposal(uint256 proposalId) external nonReentrant {
ExchangeProposal storage proposal = exchangeProposals[proposalId];
// Require that the proposal is in the Approved state.
require(proposal.state == ExchangeProposalState.Approved, "Proposal must be in Approved state");
// Require that the veto period has elapsed since the approval time.
require(
proposal.approvalTimestamp.add(proposal.vetoPeriodSeconds) <= block.timestamp,
"Veto period not elapsed"
);
// Mark the proposal as executed. Do so prior to exchanging as a measure against reentrancy.
proposal.state = ExchangeProposalState.Executed;
// Perform the exchange.
(IERC20 sellToken, uint256 sellAmount) = getSellTokenAndSellAmount(proposal);
// If the exchange sells CELO, the CELO is sent to the Reserve from this contract
// and stable token is minted to the exchanger.
if (proposal.sellCelo) {
// Send the CELO from this contract to the reserve.
require(
sellToken.transfer(address(getReserve()), sellAmount),
"Transfer out of CELO to Reserve failed"
);
// Mint stable token to the exchanger.
require(
IStableToken(proposal.stableToken).mint(proposal.exchanger, proposal.buyAmount),
"Stable token mint failed"
);
} else {
// If the exchange is selling stable token, the stable token is burned from
// this contract and CELO is transferred from the Reserve to the exchanger.
// Burn the stable token from this contract.
require(IStableToken(proposal.stableToken).burn(sellAmount), "Stable token burn failed");
// Transfer the CELO from the Reserve to the exchanger.
require(
getReserve().transferExchangeGold(proposal.exchanger, proposal.buyAmount),
"Transfer out of CELO from Reserve failed"
);
}
emit ExchangeProposalExecuted(proposalId);
}
/**
* @notice Gets the sell token and the sell amount for a proposal.
* @dev For stable token sell amounts that are stored as units, the value
* is returned. Ensures sell amount is not greater than this contract's balance.
* @param proposal The proposal to get the sell token and sell amount for.
* @return (the IERC20 sell token, the value sell amount).
*/
function getSellTokenAndSellAmount(ExchangeProposal memory proposal)
private
view
returns (IERC20, uint256)
{
IERC20 sellToken;
uint256 sellAmount;
if (proposal.sellCelo) {
sellToken = getGoldToken();
sellAmount = proposal.sellAmount;
} else {
address stableToken = proposal.stableToken;
sellToken = IERC20(stableToken);
// When selling stableToken, the sell amount is stored in units.
// Units must be converted to value when refunding.
sellAmount = IStableToken(stableToken).unitsToValue(proposal.sellAmount);
}
// In the event a precision issue from the unit <-> value calculations results
// in sellAmount being greater than this contract's balance, set the sellAmount
// to the entire balance.
// This check should not be necessary for CELO, but is done so regardless
// for extra certainty that cancelling an exchange proposal can never fail
// if for some reason the CELO balance of this contract is less than the
// recorded sell amount.
uint256 totalBalance = sellToken.balanceOf(address(this));
if (totalBalance < sellAmount) {
sellAmount = totalBalance;
}
return (sellToken, sellAmount);
}
/**
* @notice Using the oracle price, charges the spread and calculates the amount of
* the asset being bought.
* @dev Stable token value amounts are used for the sellAmount, not unit amounts.
* Assumes both CELO and the stable token have 18 decimals.
* @param celoStableTokenExchangeRate The unwrapped fraction exchange rate of CELO
* quoted in the stable token.
* @param sellAmount The amount of the sell token being sold.
* @param sellCelo Whether CELO is being sold.
* @return The amount of the asset being bought.
*/
function getBuyAmount(uint256 celoStableTokenExchangeRate, uint256 sellAmount, bool sellCelo)
public
view
returns (uint256)
{
FixidityLib.Fraction memory exchangeRate = FixidityLib.wrap(celoStableTokenExchangeRate);
// If stableToken is being sold, instead use the price of stableToken
// quoted in CELO.
if (!sellCelo) {
exchangeRate = exchangeRate.reciprocal();
}
// The sell amount taking the spread into account, ie:
// (1 - spread) * sellAmount
FixidityLib.Fraction memory adjustedSellAmount = FixidityLib.fixed1().subtract(spread).multiply(
FixidityLib.newFixed(sellAmount)
);
// Calculate the buy amount:
// exchangeRate * adjustedSellAmount
return exchangeRate.multiply(adjustedSellAmount).fromFixed();
}
/**
* @notice Removes the proposal ID found at the provided index of activeProposalIdsSuperset
* if the exchange proposal is not active.
* @dev Anyone can call. Reverts if the exchange proposal is active.
* @param index The index of the proposal ID to remove from activeProposalIdsSuperset.
*/
function removeFromActiveProposalIdsSuperset(uint256 index) external {
require(index < activeProposalIdsSuperset.length, "Index out of bounds");
uint256 proposalId = activeProposalIdsSuperset[index];
// Require the exchange proposal to be inactive.
require(
exchangeProposals[proposalId].state != ExchangeProposalState.Proposed &&
exchangeProposals[proposalId].state != ExchangeProposalState.Approved,
"Exchange proposal not inactive"
);
// If not removing the last element, overwrite the index with the value of
// the last element.
uint256 lastIndex = activeProposalIdsSuperset.length.sub(1);
if (index < lastIndex) {
activeProposalIdsSuperset[index] = activeProposalIdsSuperset[lastIndex];
}
// Delete the last element.
activeProposalIdsSuperset.length--;
}
/**
* @notice Gets the proposal identifiers of exchange proposals in the
* Proposed or Approved state. Returns a version of activeProposalIdsSuperset
* with inactive proposal IDs set as 0.
* @dev Elements with a proposal ID of 0 should be filtered out by the consumer.
* @return An array of active exchange proposals IDs.
*/
function getActiveProposalIds() external view returns (uint256[] memory) {
// Solidity doesn't play well with dynamically sized memory arrays.
// Instead, this array is created with the same length as activeProposalIdsSuperset,
// and will replace elements that are inactive proposal IDs with the value 0.
uint256[] memory activeProposalIds = new uint256[](activeProposalIdsSuperset.length);
for (uint256 i = 0; i < activeProposalIdsSuperset.length; i = i.add(1)) {
uint256 proposalId = activeProposalIdsSuperset[i];
if (
exchangeProposals[proposalId].state == ExchangeProposalState.Proposed ||
exchangeProposals[proposalId].state == ExchangeProposalState.Approved
) {
activeProposalIds[i] = proposalId;
}
}
return activeProposalIds;
}
/**
* @notice Gets the oracle CELO price quoted in the stable token.
* @dev Reverts if there is not a rate for the provided stable token.
* @param stableToken The stable token to get the oracle price for.
* @return The oracle CELO price quoted in the stable token.
*/
function getOracleExchangeRate(address stableToken)
private
view
returns (FixidityLib.Fraction memory)
{
uint256 rateNumerator;
uint256 rateDenominator;
(rateNumerator, rateDenominator) = getSortedOracles().medianRate(stableToken);
// When rateDenominator is 0, it means there are no rates known to SortedOracles.
require(rateDenominator > 0, "No oracle rates present for token");
return FixidityLib.wrap(rateNumerator).divide(FixidityLib.wrap(rateDenominator));
}
/**
* @notice Gets the minimum and maximum amount of a stable token that can be
* involved in a single exchange.
* @dev Reverts if there is no explicit exchange limit for the stable token.
* @param stableTokenRegistryId The string registry ID for the stable token.
* @return (minimum exchange amount, maximum exchange amount).
*/
function getStableTokenExchangeLimits(string memory stableTokenRegistryId)
public
view
returns (uint256, uint256)
{
ExchangeLimits memory exchangeLimits = stableTokenExchangeLimits[stableTokenRegistryId];
// Require the configurable stableToken max exchange amount to be > 0.
// This covers the case where a stableToken has never been explicitly permitted.
require(
exchangeLimits.maxExchangeAmount > 0,
"Max stable token exchange amount must be defined"
);
return (exchangeLimits.minExchangeAmount, exchangeLimits.maxExchangeAmount);
}
/**
* @notice Sets the approver.
* @dev Sender must be owner. New approver is allowed to be address(0).
* @param newApprover The new value for the approver.
*/
function setApprover(address newApprover) public onlyOwner {
approver = newApprover;
emit ApproverSet(newApprover);
}
/**
* @notice Sets the maximum allowed change in the CELO/stable token price when
* an exchange proposal is being approved relative to the price when the proposal
* was created.
* @dev Sender must be owner.
* @param newMaxApprovalExchangeRateChange The new value for maxApprovalExchangeRateChange
* to be wrapped.
*/
function setMaxApprovalExchangeRateChange(uint256 newMaxApprovalExchangeRateChange)
public
onlyOwner
{
maxApprovalExchangeRateChange = FixidityLib.wrap(newMaxApprovalExchangeRateChange);
emit MaxApprovalExchangeRateChangeSet(newMaxApprovalExchangeRateChange);
}
/**
* @notice Sets the spread.
* @dev Sender must be owner.
* @param newSpread The new value for the spread to be wrapped. Must be <= fixed 1.
*/
function setSpread(uint256 newSpread) public onlyOwner {
require(newSpread <= FixidityLib.fixed1().unwrap(), "Spread must be smaller than 1");
spread = FixidityLib.wrap(newSpread);
emit SpreadSet(newSpread);
}
/**
* @notice Sets the minimum and maximum amount of the stable token an exchange can involve.
* @dev Sender must be owner. Setting the maxExchangeAmount to 0 effectively disables new
* exchange proposals for the token.
* @param stableTokenRegistryId The registry ID string for the stable token to set limits for.
* @param minExchangeAmount The new minimum exchange amount for the stable token.
* @param maxExchangeAmount The new maximum exchange amount for the stable token.
*/
function setStableTokenExchangeLimits(
string calldata stableTokenRegistryId,
uint256 minExchangeAmount,
uint256 maxExchangeAmount
) external onlyOwner {
require(
minExchangeAmount <= maxExchangeAmount,
"Min exchange amount must not be greater than max"
);
stableTokenExchangeLimits[stableTokenRegistryId] = ExchangeLimits({
minExchangeAmount: minExchangeAmount,
maxExchangeAmount: maxExchangeAmount
});
emit StableTokenExchangeLimitsSet(stableTokenRegistryId, minExchangeAmount, maxExchangeAmount);
}
/**
* @notice Sets the veto period in seconds.
* @dev Sender must be owner.
* @param newVetoPeriodSeconds The new value for the veto period in seconds.
*/
function setVetoPeriodSeconds(uint256 newVetoPeriodSeconds) public onlyOwner {
// Hardcode a max of 4 weeks.
// A minimum is not enforced for flexibility. A case of interest is if
// Governance were to be set as the `approver`, it would be desirable to
// set the veto period to 0 seconds.
require(newVetoPeriodSeconds <= 4 weeks, "Veto period cannot exceed 4 weeks");
vetoPeriodSeconds = newVetoPeriodSeconds;
emit VetoPeriodSecondsSet(newVetoPeriodSeconds);
}
}
| Calculate the buy amount: exchangeRate * adjustedSellAmount | return exchangeRate.multiply(adjustedSellAmount).fromFixed();
| 2,543,972 | [
1,
8695,
326,
30143,
3844,
30,
7829,
4727,
225,
13940,
55,
1165,
6275,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
327,
7829,
4727,
18,
7027,
1283,
12,
13362,
329,
55,
1165,
6275,
2934,
2080,
7505,
5621,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.18;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require (msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
/**
* @title Authorizable
* @dev Allows to authorize access to certain function calls
*
* ABI
* [{"constant":true,"inputs":[{"name":"authorizerIndex","type":"uint256"}],"name":"getAuthorizer","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_addr","type":"address"}],"name":"addAuthorized","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_addr","type":"address"}],"name":"isAuthorized","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"}]
*/
contract Authorizable {
address[] authorizers;
mapping(address => uint) authorizerIndex;
/**
* @dev Throws if called by any account tat is not authorized.
*/
modifier onlyAuthorized {
require(isAuthorized(msg.sender));
_;
}
/**
* @dev Contructor that authorizes the msg.sender.
*/
function Authorizable() public {
authorizers.length = 2;
authorizers[1] = msg.sender;
authorizerIndex[msg.sender] = 1;
}
/**
* @dev Function to get a specific authorizer
* @param authorizerIndex index of the authorizer to be retrieved.
* @return The address of the authorizer.
*/
function getAuthorizer(uint authorizerIndex) external constant returns(address) {
return address(authorizers[authorizerIndex + 1]);
}
/**
* @dev Function to check if an address is authorized
* @param _addr the address to check if it is authorized.
* @return boolean flag if address is authorized.
*/
function isAuthorized(address _addr) public constant returns(bool) {
return authorizerIndex[_addr] > 0;
}
/**
* @dev Function to add a new authorizer
* @param _addr the address to add as a new authorizer.
*/
function addAuthorized(address _addr) external onlyAuthorized {
authorizerIndex[_addr] = authorizers.length;
authorizers.length++;
authorizers[authorizers.length - 1] = _addr;
}
}
/**
* @title ExchangeRate
* @dev Allows updating and retrieveing of Conversion Rates for PAY tokens
*
* ABI
* [{"constant":false,"inputs":[{"name":"_symbol","type":"string"},{"name":"_rate","type":"uint256"}],"name":"updateRate","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"data","type":"uint256[]"}],"name":"updateRates","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_symbol","type":"string"}],"name":"getRate","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"bytes32"}],"name":"rates","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"timestamp","type":"uint256"},{"indexed":false,"name":"symbol","type":"bytes32"},{"indexed":false,"name":"rate","type":"uint256"}],"name":"RateUpdated","type":"event"}]
*/
contract ExchangeRate is Ownable {
event RateUpdated(uint timestamp, bytes32 symbol, uint rate);
mapping(bytes32 => uint) public rates;
/**
* @dev Allows the current owner to update a single rate.
* @param _symbol The symbol to be updated.
* @param _rate the rate for the symbol.
*/
function updateRate(string _symbol, uint _rate) public onlyOwner {
rates[keccak256(_symbol)] = _rate;
RateUpdated(now, keccak256(_symbol), _rate);
}
/**
* @dev Allows the current owner to update multiple rates.
* @param data an array that alternates keccak256 hashes of the symbol and the corresponding rate .
*/
function updateRates(uint[] data) public onlyOwner {
require (data.length % 2 <= 0);
uint i = 0;
while (i < data.length / 2) {
bytes32 symbol = bytes32(data[i * 2]);
uint rate = data[i * 2 + 1];
rates[symbol] = rate;
RateUpdated(now, symbol, rate);
i++;
}
}
/**
* @dev Allows the anyone to read the current rate.
* @param _symbol the symbol to be retrieved.
*/
function getRate(string _symbol) public constant returns(uint) {
return rates[keccak256(_symbol)];
}
}
/**
* Math operations with safety checks
*/
library SafeMath {
function mul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal returns (uint) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
function assert(bool assertion) internal {
require(assertion);
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Basic {
uint public totalSupply;
function balanceOf(address who) public constant returns (uint);
function transfer(address to, uint value) public;
event Transfer(address indexed from, address indexed to, uint value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint);
function transferFrom(address from, address to, uint value);
function approve(address spender, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint;
mapping(address => uint) balances;
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
require (size + 4 <= msg.data.length);
_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implemantation of the basic standart token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// if (_value > _allowance) throw;
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on beahlf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint _value) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw;
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
/**
* @dev Function to check the amount of tokens than an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint value);
event MintFinished();
event Burn(address indexed burner, uint256 value);
bool public mintingFinished = false;
uint public totalSupply = 0;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will recieve the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint _amount) onlyOwner canMint returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(address _who, uint256 _value) onlyOwner public {
_burn(_who, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(_who, _value);
Transfer(_who, address(0), _value);
}
}
/**
* @title CBCToken
* @dev The main CBC token contract
*
* ABI
* [{"constant":true,"inputs":[],"name":"mintingFinished","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"startTrading","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_amount","type":"uint256"}],"name":"mint","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"tradingStarted","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"finishMinting","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"type":"function"},{"anonymous":false,"inputs":[{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[],"name":"MintFinished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}]
*/
contract CBCToken is MintableToken {
string public name = "Crypto Boss Coin";
string public symbol = "CBC";
uint public decimals = 18;
bool public tradingStarted = false;
/**
* @dev modifier that throws if trading has not started yet
*/
modifier hasStartedTrading() {
require(tradingStarted);
_;
}
/**
* @dev Allows the owner to enable the trading. This can not be undone
*/
function startTrading() onlyOwner {
tradingStarted = true;
}
/**
* @dev Allows anyone to transfer the PAY tokens once trading has started
* @param _to the recipient address of the tokens.
* @param _value number of tokens to be transfered.
*/
function transfer(address _to, uint _value) hasStartedTrading {
super.transfer(_to, _value);
}
/**
* @dev Allows anyone to transfer the CBC tokens once trading has started
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint _value) hasStartedTrading {
super.transferFrom(_from, _to, _value);
}
}
/**
* @title MainSale
* @dev The main CBC token sale contract
*
* ABI
* [{"constant":false,"inputs":[{"name":"_multisigVault","type":"address"}],"name":"setMultisigVault","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"authorizerIndex","type":"uint256"}],"name":"getAuthorizer","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"exchangeRate","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"altDeposits","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"recipient","type":"address"},{"name":"tokens","type":"uint256"}],"name":"authorizedCreateTokens","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"finishMinting","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_exchangeRate","type":"address"}],"name":"setExchangeRate","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_token","type":"address"}],"name":"retrieveTokens","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"totalAltDeposits","type":"uint256"}],"name":"setAltDeposit","outputs":[],"payable":false,"type":"function"},{"constant":!1,"inputs":[{"name":"victim","type":"address"},{"name":"amount","type":"uint256"}],"name":"burnTokens","outputs":[],"payable":!1,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"start","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"recipient","type":"address"}],"name":"createTokens","outputs":[],"payable":true,"type":"function"},{"constant":false,"inputs":[{"name":"_addr","type":"address"}],"name":"addAuthorized","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"multisigVault","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_hardcap","type":"uint256"}],"name":"setHardCap","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_start","type":"uint256"}],"name":"setStart","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"token","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_addr","type":"address"}],"name":"isAuthorized","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"payable":true,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"recipient","type":"address"},{"indexed":false,"name":"ether_amount","type":"uint256"},{"indexed":false,"name":"pay_amount","type":"uint256"},{"indexed":false,"name":"exchangerate","type":"uint256"}],"name":"TokenSold","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"recipient","type":"address"},{"indexed":false,"name":"pay_amount","type":"uint256"}],"name":"AuthorizedCreate","type":"event"},{"anonymous":false,"inputs":[],"name":"MainSaleClosed","type":"event"}]
*/
contract MainSale is Ownable, Authorizable {
using SafeMath for uint;
event TokenSold(address recipient, uint ether_amount, uint pay_amount, uint exchangerate);
event AuthorizedCreate(address recipient, uint pay_amount);
event AuthorizedBurn(address receiver, uint value);
event AuthorizedStartTrading();
event MainSaleClosed();
CBCToken public token = new CBCToken();
address public multisigVault;
uint hardcap = 100000000000000 ether;
ExchangeRate public exchangeRate;
uint public altDeposits = 0;
uint public start = 1525996800;
/**
* @dev modifier to allow token creation only when the sale IS ON
*/
modifier saleIsOn() {
require(now > start && now < start + 28 days);
_;
}
/**
* @dev modifier to allow token creation only when the hardcap has not been reached
*/
modifier isUnderHardCap() {
require(multisigVault.balance + altDeposits <= hardcap);
_;
}
/**
* @dev Allows anyone to create tokens by depositing ether.
* @param recipient the recipient to receive tokens.
*/
function createTokens(address recipient) public isUnderHardCap saleIsOn payable {
uint rate = exchangeRate.getRate("ETH");
uint tokens = rate.mul(msg.value).div(1 ether);
token.mint(recipient, tokens);
require(multisigVault.send(msg.value));
TokenSold(recipient, msg.value, tokens, rate);
}
/**
* @dev Allows to set the toal alt deposit measured in ETH to make sure the hardcap includes other deposits
* @param totalAltDeposits total amount ETH equivalent
*/
function setAltDeposit(uint totalAltDeposits) public onlyOwner {
altDeposits = totalAltDeposits;
}
/**
* @dev Allows authorized acces to create tokens. This is used for Bitcoin and ERC20 deposits
* @param recipient the recipient to receive tokens.
* @param tokens number of tokens to be created.
*/
function authorizedCreateTokens(address recipient, uint tokens) public onlyAuthorized {
token.mint(recipient, tokens);
AuthorizedCreate(recipient, tokens);
}
function authorizedStartTrading() public onlyAuthorized {
token.startTrading();
AuthorizedStartTrading();
}
/**
* @dev Allows authorized acces to burn tokens.
* @param receiver the receiver to receive tokens.
* @param value number of tokens to be created.
*/
function authorizedBurnTokens(address receiver, uint value) public onlyAuthorized {
token.burn(receiver, value);
AuthorizedBurn(receiver, value);
}
/**
* @dev Allows the owner to set the hardcap.
* @param _hardcap the new hardcap
*/
function setHardCap(uint _hardcap) public onlyOwner {
hardcap = _hardcap;
}
/**
* @dev Allows the owner to set the starting time.
* @param _start the new _start
*/
function setStart(uint _start) public onlyOwner {
start = _start;
}
/**
* @dev Allows the owner to set the multisig contract.
* @param _multisigVault the multisig contract address
*/
function setMultisigVault(address _multisigVault) public onlyOwner {
if (_multisigVault != address(0)) {
multisigVault = _multisigVault;
}
}
/**
* @dev Allows the owner to set the exchangerate contract.
* @param _exchangeRate the exchangerate address
*/
function setExchangeRate(address _exchangeRate) public onlyOwner {
exchangeRate = ExchangeRate(_exchangeRate);
}
/**
* @dev Allows the owner to finish the minting. This will create the
* restricted tokens and then close the minting.
* Then the ownership of the PAY token contract is transfered
* to this owner.
*/
function finishMinting() public onlyOwner {
uint issuedTokenSupply = token.totalSupply();
uint restrictedTokens = issuedTokenSupply.mul(49).div(51);
token.mint(multisigVault, restrictedTokens);
token.finishMinting();
token.transferOwnership(owner);
MainSaleClosed();
}
/**
* @dev Allows the owner to transfer ERC20 tokens to the multi sig vault
* @param _token the contract address of the ERC20 contract
*/
function retrieveTokens(address _token) public onlyOwner {
ERC20 token = ERC20(_token);
token.transfer(multisigVault, token.balanceOf(this));
}
/**
* @dev Fallback function which receives ether and created the appropriate number of tokens for the
* msg.sender.
*/
function() external payable {
createTokens(msg.sender);
}
} | * @title ExchangeRate @dev Allows updating and retrieveing of Conversion Rates for PAY tokens ABI [{"constant":false,"inputs":[{"name":"_symbol","type":"string"},{"name":"_rate","type":"uint256"}],"name":"updateRate","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"data","type":"uint256[]"}],"name":"updateRates","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_symbol","type":"string"}],"name":"getRate","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"bytes32"}],"name":"rates","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"timestamp","type":"uint256"},{"indexed":false,"name":"symbol","type":"bytes32"},{"indexed":false,"name":"rate","type":"uint256"}],"name":"RateUpdated","type":"event"}]/ | contract ExchangeRate is Ownable {
event RateUpdated(uint timestamp, bytes32 symbol, uint rate);
mapping(bytes32 => uint) public rates;
function updateRate(string _symbol, uint _rate) public onlyOwner {
rates[keccak256(_symbol)] = _rate;
RateUpdated(now, keccak256(_symbol), _rate);
}
function updateRates(uint[] data) public onlyOwner {
require (data.length % 2 <= 0);
uint i = 0;
while (i < data.length / 2) {
bytes32 symbol = bytes32(data[i * 2]);
uint rate = data[i * 2 + 1];
rates[symbol] = rate;
RateUpdated(now, symbol, rate);
i++;
}
}
function updateRates(uint[] data) public onlyOwner {
require (data.length % 2 <= 0);
uint i = 0;
while (i < data.length / 2) {
bytes32 symbol = bytes32(data[i * 2]);
uint rate = data[i * 2 + 1];
rates[symbol] = rate;
RateUpdated(now, symbol, rate);
i++;
}
}
function getRate(string _symbol) public constant returns(uint) {
return rates[keccak256(_symbol)];
}
}
| 6,683,968 | [
1,
11688,
4727,
225,
25619,
9702,
471,
4614,
310,
434,
16401,
534,
815,
364,
25095,
2430,
10336,
45,
306,
16711,
14384,
6877,
5743,
10837,
10029,
6877,
63,
16711,
529,
15563,
67,
7175,
15937,
723,
15563,
1080,
6,
5779,
16711,
529,
15563,
67,
5141,
15937,
723,
15563,
11890,
5034,
6,
97,
6487,
6,
529,
15563,
2725,
4727,
15937,
12295,
6877,
63,
6487,
6,
10239,
429,
6877,
5743,
10837,
723,
15563,
915,
6,
5779,
16711,
14384,
6877,
5743,
10837,
10029,
6877,
63,
16711,
529,
15563,
892,
15937,
723,
15563,
11890,
5034,
63,
4279,
97,
6487,
6,
529,
15563,
2725,
20836,
15937,
12295,
6877,
63,
6487,
6,
10239,
429,
6877,
5743,
10837,
723,
15563,
915,
6,
5779,
16711,
14384,
6877,
3767,
10837,
10029,
6877,
63,
16711,
529,
15563,
67,
7175,
15937,
723,
15563,
1080,
6,
97,
6487,
6,
529,
15563,
588,
4727,
15937,
12295,
6877,
63,
16711,
529,
15563,
15937,
723,
15563,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
18903,
4727,
353,
14223,
6914,
288,
203,
7010,
225,
871,
13025,
7381,
12,
11890,
2858,
16,
1731,
1578,
3273,
16,
2254,
4993,
1769,
203,
203,
225,
2874,
12,
3890,
1578,
516,
2254,
13,
1071,
17544,
31,
203,
203,
225,
445,
1089,
4727,
12,
1080,
389,
7175,
16,
2254,
389,
5141,
13,
1071,
1338,
5541,
288,
203,
565,
17544,
63,
79,
24410,
581,
5034,
24899,
7175,
25887,
273,
389,
5141,
31,
203,
565,
13025,
7381,
12,
3338,
16,
417,
24410,
581,
5034,
24899,
7175,
3631,
389,
5141,
1769,
203,
225,
289,
203,
203,
225,
445,
1089,
20836,
12,
11890,
8526,
501,
13,
1071,
1338,
5541,
288,
203,
565,
2583,
261,
892,
18,
2469,
738,
576,
1648,
374,
1769,
203,
565,
2254,
277,
273,
374,
31,
203,
565,
1323,
261,
77,
411,
501,
18,
2469,
342,
576,
13,
288,
203,
1377,
1731,
1578,
3273,
273,
1731,
1578,
12,
892,
63,
77,
380,
576,
19226,
203,
1377,
2254,
4993,
273,
501,
63,
77,
380,
576,
397,
404,
15533,
203,
1377,
17544,
63,
7175,
65,
273,
4993,
31,
203,
1377,
13025,
7381,
12,
3338,
16,
3273,
16,
4993,
1769,
203,
1377,
277,
9904,
31,
203,
565,
289,
203,
225,
289,
203,
203,
225,
445,
1089,
20836,
12,
11890,
8526,
501,
13,
1071,
1338,
5541,
288,
203,
565,
2583,
261,
892,
18,
2469,
738,
576,
1648,
374,
1769,
203,
565,
2254,
277,
273,
374,
31,
203,
565,
1323,
261,
77,
411,
501,
18,
2469,
342,
576,
13,
288,
203,
1377,
1731,
1578,
3273,
273,
1731,
1578,
12,
892,
2
] |
./partial_match/1/0x10eC0D497824e342bCB0EDcE00959142aAa766dD/sources/IdleToken.sol | * Used to get `_clientProtocolAmounts` for `rebalance` method This should be used only for a call not an actual tx NOTE: this method can be paused @param _newAmount : amount of underlying tokens that needs to be minted with this rebalance @return : address[] array with all token addresses used, eg [cTokenAddress, iTokenAddress] @return : uint256[] array with all amounts for each protocol in order, eg [amountCompoundInUnderlying, amountFulcrumInUnderlying]/ | function getParamsForRebalance(uint256 _newAmount)
external whenNotPaused whenITokenPriceHasNotDecreased
returns (address[] memory, uint256[] memory) {
rebalance(_newAmount, new uint256[](0));
return _getCurrentAllocations();
}
| 4,112,240 | [
1,
6668,
358,
336,
1375,
67,
2625,
5752,
6275,
87,
68,
364,
1375,
266,
12296,
68,
707,
1220,
1410,
506,
1399,
1338,
364,
279,
745,
486,
392,
3214,
2229,
5219,
30,
333,
707,
848,
506,
17781,
225,
389,
2704,
6275,
294,
3844,
434,
6808,
2430,
716,
4260,
358,
506,
312,
474,
329,
598,
333,
283,
12296,
327,
294,
1758,
8526,
526,
598,
777,
1147,
6138,
1399,
16,
12900,
9130,
306,
71,
1345,
1887,
16,
277,
1345,
1887,
65,
327,
294,
2254,
5034,
8526,
526,
598,
777,
30980,
364,
1517,
1771,
316,
1353,
16,
10402,
9130,
306,
8949,
16835,
382,
14655,
6291,
16,
3844,
23747,
3353,
379,
382,
14655,
6291,
18537,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
13281,
1290,
426,
12296,
12,
11890,
5034,
389,
2704,
6275,
13,
203,
565,
3903,
1347,
1248,
28590,
1347,
1285,
969,
5147,
5582,
1248,
23326,
8905,
203,
565,
1135,
261,
2867,
8526,
3778,
16,
2254,
5034,
8526,
3778,
13,
288,
203,
1377,
283,
12296,
24899,
2704,
6275,
16,
394,
2254,
5034,
8526,
12,
20,
10019,
203,
1377,
327,
389,
588,
3935,
8763,
1012,
5621,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.5;
import "hardhat/console.sol";
contract MultiSig {
uint256 public required;
struct Safe {
address[3] signers;
bool confirmed;
mapping(address => bool) signStatus;
}
Safe[] public safes;
Safe private safe;
bool private safeLock = true;
event Staffed(
address indexed _borrower,
address _lender,
uint256 indexed _safeId
);
event Signed(address indexed _signer, bool _confirmedStatus);
event Unsigned(address indexed _signer, bool _confirmedStatus);
event Confirmed(address indexed _contract, bool indexed _confirmedStatus);
address contractOwner;
constructor(uint256 _required) {
required = _required;
contractOwner = msg.sender;
// Lock out first safe.
safes.push();
for (uint256 i; i < required; i++) {
safes[0].signers[i] = address(0);
}
}
function getSafesLength() external view returns (uint256) {
return safes.length;
}
function getSafesSigner(uint256 _safeId, uint256 i)
external
view
returns (address)
{
return safes[_safeId].signers[i];
}
function getSigner(uint256 _safeId, uint256 _position)
public
view
returns (address)
{
address _signer = safes[_safeId].signers[_position];
return _signer;
}
function _getSignStatus(uint256 _safeId, address _signer)
public
view
returns (bool)
{
bool _status = safes[_safeId].signStatus[_signer];
return _status;
}
function _isSigner() internal view returns (bool _isSigner_) {
_isSigner_ = true;
_isSigner_ = safe.signers[0] == msg.sender ? true : _isSigner_;
_isSigner_ = safe.signers[1] == msg.sender ? true : _isSigner_;
_isSigner_ = safe.signers[2] == msg.sender ? true : _isSigner_;
}
function _createSafe(address borrower) public onlyOwnerOrContract {
uint256 _safeId = safes.length;
safes.push();
safes[_safeId].signers[0] = borrower;
}
function _sign(uint256 _safeId, address signer)
public
safeKey(_safeId)
onlySigner(signer)
returns (bool _isSigned)
{
console.log("who is signer?", signer);
require(safe.signers[0] != address(0), "Borrower must be set.");
safe.signStatus[signer] = true;
emit Signed(signer, safe.confirmed);
console.log("status confirmed to:", safe.signStatus[signer]);
_isSigned = safe.signStatus[signer];
}
function _removeSignature(uint256 _safeId, address _signer)
public
safeKey(_safeId)
onlySigner(_signer)
onlyOwnerOrContract
{
safe.signStatus[_signer] = false;
__setConfirmedStatus();
emit Unsigned(msg.sender, safe.confirmed);
}
function _setSigner(
uint256 _safeId,
address _signer,
uint256 _position
) public safeKey(_safeId) onlyOwnerOrContract {
// Either _position is safe creator,
// or creator is not equal to _signer
require(
_position == 0 || safe.signers[0] != _signer,
"Signer 0 must be unique."
);
safe.signers[_position] = _signer;
safe.signStatus[_signer] = false;
uint256 _counter;
for (uint256 i; i < required; i++) {
_counter = safe.signers[i] != address(0) ? _counter + 1 : _counter;
}
if (_counter >= required)
emit Staffed(safe.signers[0], safe.signers[1], _safeId);
}
function _setConfirmedStatus(uint256 _safeId)
public
safeKey(_safeId)
onlyOwnerOrContract
{
__setConfirmedStatus();
}
function __setConfirmedStatus() private {
uint8 _signCount = 0;
if (!safe.confirmed) {
bool _borrowerSignStatus = safe.signStatus[safe.signers[0]];
bool _lenderSignStatus = safe.signStatus[safe.signers[1]];
bool _arbiterSignStatus = safe.signStatus[safe.signers[2]];
_signCount = _borrowerSignStatus ? _signCount + 1 : _signCount;
_signCount = _lenderSignStatus ? _signCount + 1 : _signCount;
_signCount = _arbiterSignStatus ? _signCount + 1 : _signCount;
safe.confirmed = _signCount >= required;
if (safe.confirmed) {
emit Confirmed(address(this), safe.confirmed);
}
}
}
function __setSafe(uint256 _safeId) private {
require(safeLock == false, "This safe is locked.");
safe.signers = safes[_safeId].signers;
safe.confirmed = safes[_safeId].confirmed;
address _borrower = safe.signers[0];
address _lender = safe.signers[1];
address _arbiter = safe.signers[2];
safe.signStatus[_borrower] = safes[_safeId].signStatus[_borrower];
safe.signStatus[_lender] = safes[_safeId].signStatus[_lender];
safe.signStatus[_arbiter] = safes[_safeId].signStatus[_arbiter];
}
function __updateSafe(uint256 _safeId) private {
require(safeLock == false, "This safe is locked.");
safes[_safeId].signers = safe.signers;
safes[_safeId].confirmed = safe.confirmed;
address _borrower = safes[_safeId].signers[0];
address _lender = safes[_safeId].signers[1];
address _arbiter = safes[_safeId].signers[2];
safes[_safeId].signStatus[_borrower] = safe.signStatus[_borrower];
safes[_safeId].signStatus[_lender] = safe.signStatus[_lender];
safes[_safeId].signStatus[_arbiter] = safe.signStatus[_arbiter];
}
modifier safeKey(uint256 _safeId) {
console.log("runs here", msg.sender);
safeLock = false;
__setSafe(_safeId);
_;
__updateSafe(_safeId);
__setSafe(0);
safeLock = true;
}
modifier onlySigner(address _signer) {
console.log(msg.sender, _signer);
require(_signer != address(0), "Address 0 is invalid.");
require(_isSigner() == true, "You are not a valid signer.");
_;
}
modifier onlyOwnerOrContract() {
require(msg.sender == contractOwner || msg.sender == address(this));
_;
}
}
| Either _position is safe creator, or creator is not equal to _signer | function _setSigner(
uint256 _safeId,
address _signer,
uint256 _position
) public safeKey(_safeId) onlyOwnerOrContract {
require(
_position == 0 || safe.signers[0] != _signer,
"Signer 0 must be unique."
);
safe.signers[_position] = _signer;
safe.signStatus[_signer] = false;
uint256 _counter;
for (uint256 i; i < required; i++) {
_counter = safe.signers[i] != address(0) ? _counter + 1 : _counter;
}
if (_counter >= required)
emit Staffed(safe.signers[0], safe.signers[1], _safeId);
}
| 12,936,665 | [
1,
26091,
389,
3276,
353,
4183,
11784,
16,
578,
11784,
353,
486,
3959,
358,
389,
2977,
264,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
542,
15647,
12,
203,
3639,
2254,
5034,
389,
4626,
548,
16,
203,
3639,
1758,
389,
2977,
264,
16,
203,
3639,
2254,
5034,
389,
3276,
203,
565,
262,
1071,
4183,
653,
24899,
4626,
548,
13,
1338,
5541,
1162,
8924,
288,
203,
3639,
2583,
12,
203,
5411,
389,
3276,
422,
374,
747,
4183,
18,
2977,
414,
63,
20,
65,
480,
389,
2977,
264,
16,
203,
5411,
315,
15647,
374,
1297,
506,
3089,
1199,
203,
3639,
11272,
203,
203,
3639,
4183,
18,
2977,
414,
63,
67,
3276,
65,
273,
389,
2977,
264,
31,
203,
3639,
4183,
18,
2977,
1482,
63,
67,
2977,
264,
65,
273,
629,
31,
203,
203,
3639,
2254,
5034,
389,
7476,
31,
203,
3639,
364,
261,
11890,
5034,
277,
31,
277,
411,
1931,
31,
277,
27245,
288,
203,
5411,
389,
7476,
273,
4183,
18,
2977,
414,
63,
77,
65,
480,
1758,
12,
20,
13,
692,
389,
7476,
397,
404,
294,
389,
7476,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
67,
7476,
1545,
1931,
13,
203,
5411,
3626,
934,
7329,
329,
12,
4626,
18,
2977,
414,
63,
20,
6487,
4183,
18,
2977,
414,
63,
21,
6487,
389,
4626,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.6;
// Part: IBetaBank
interface IBetaBank {
/// @dev Returns the address of BToken of the given underlying token, or 0 if not exists.
function bTokens(address _underlying) external view returns (address);
/// @dev Returns the address of the underlying of the given BToken, or 0 if not exists.
function underlyings(address _bToken) external view returns (address);
/// @dev Returns the address of the oracle contract.
function oracle() external view returns (address);
/// @dev Returns the address of the config contract.
function config() external view returns (address);
/// @dev Returns the interest rate model smart contract.
function interestModel() external view returns (address);
/// @dev Returns the position's collateral token and AmToken.
function getPositionTokens(address _owner, uint _pid)
external
view
returns (address _collateral, address _bToken);
/// @dev Returns the debt of the given position. Can't be view as it needs to call accrue.
function fetchPositionDebt(address _owner, uint _pid) external returns (uint);
/// @dev Returns the LTV of the given position. Can't be view as it needs to call accrue.
function fetchPositionLTV(address _owner, uint _pid) external returns (uint);
/// @dev Opens a new position in the Beta smart contract.
function open(
address _owner,
address _underlying,
address _collateral
) external returns (uint pid);
/// @dev Borrows tokens on the given position.
function borrow(
address _owner,
uint _pid,
uint _amount
) external;
/// @dev Repays tokens on the given position.
function repay(
address _owner,
uint _pid,
uint _amount
) external;
/// @dev Puts more collateral to the given position.
function put(
address _owner,
uint _pid,
uint _amount
) external;
/// @dev Takes some collateral out of the position.
function take(
address _owner,
uint _pid,
uint _amount
) external;
/// @dev Liquidates the given position.
function liquidate(
address _owner,
uint _pid,
uint _amount
) external;
}
// Part: IBetaConfig
interface IBetaConfig {
/// @dev Returns the risk level for the given asset.
function getRiskLevel(address token) external view returns (uint);
/// @dev Returns the rate of interest collected to be distributed to the protocol reserve.
function reserveRate() external view returns (uint);
/// @dev Returns the beneficiary to receive a portion interest rate for the protocol.
function reserveBeneficiary() external view returns (address);
/// @dev Returns the ratio of which the given token consider for collateral value.
function getCollFactor(address token) external view returns (uint);
/// @dev Returns the max amount of collateral to accept globally.
function getCollMaxAmount(address token) external view returns (uint);
/// @dev Returns max ltv of collateral / debt to allow a new position.
function getSafetyLTV(address token) external view returns (uint);
/// @dev Returns max ltv of collateral / debt to liquidate a position of the given token.
function getLiquidationLTV(address token) external view returns (uint);
/// @dev Returns the bonus incentive reward factor for liquidators.
function getKillBountyRate(address token) external view returns (uint);
}
// Part: IBetaInterestModel
interface IBetaInterestModel {
/// @dev Returns the initial interest rate per year (times 1e18).
function initialRate() external view returns (uint);
/// @dev Returns the next interest rate for the market.
/// @param prevRate The current interest rate.
/// @param totalAvailable The current available liquidity.
/// @param totalLoan The current outstanding loan.
/// @param timePast The time past since last interest rate rebase in seconds.
function getNextInterestRate(
uint prevRate,
uint totalAvailable,
uint totalLoan,
uint timePast
) external view returns (uint);
}
// Part: IWETH
interface IWETH {
function deposit() external payable;
function withdraw(uint wad) external;
function approve(address guy, uint wad) external returns (bool);
}
// Part: OpenZeppelin/[email protected]/Address
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Part: OpenZeppelin/[email protected]/Context
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// Part: OpenZeppelin/[email protected]/Counters
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// Part: OpenZeppelin/[email protected]/ECDSA
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return recover(hash, r, vs);
} else {
revert("ECDSA: invalid signature length");
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`, `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(
uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
"ECDSA: invalid signature 's' value"
);
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Part: OpenZeppelin/[email protected]/IERC20Permit
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// Part: OpenZeppelin/[email protected]/Math
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute.
return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2);
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// Part: OpenZeppelin/[email protected]/ReentrancyGuard
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// Part: OpenZeppelin/[email protected]/EIP712
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// Part: OpenZeppelin/[email protected]/IERC20Metadata
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// Part: OpenZeppelin/[email protected]/Pausable
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// Part: OpenZeppelin/[email protected]/SafeERC20
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// Part: OpenZeppelin/[email protected]/ERC20
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// Part: OpenZeppelin/[email protected]/ERC20Permit
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
constructor(string memory name) EIP712(name, "1") {}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}
// Part: BToken
contract BToken is ERC20Permit, ReentrancyGuard {
using SafeERC20 for IERC20;
event Accrue(uint interest);
event Mint(address indexed caller, address indexed to, uint amount, uint credit);
event Burn(address indexed caller, address indexed to, uint amount, uint credit);
uint public constant MINIMUM_LIQUIDITY = 10**6; // minimum liquidity to be locked in the pool when first mint occurs
address public immutable betaBank; // BetaBank address
address public immutable underlying; // the underlying token
uint public interestRate; // current interest rate
uint public lastAccrueTime; // last interest accrual timestamp
uint public totalLoanable; // total asset amount available to be borrowed
uint public totalLoan; // total amount of loan
uint public totalDebtShare; // total amount of debt share
/// @dev Initializes the BToken contract.
/// @param _betaBank BetaBank address.
/// @param _underlying The underlying token address for the bToken.
constructor(address _betaBank, address _underlying)
ERC20Permit('B Token')
ERC20('B Token', 'bTOKEN')
{
require(_betaBank != address(0), 'constructor/betabank-zero-address');
require(_underlying != address(0), 'constructor/underlying-zero-address');
betaBank = _betaBank;
underlying = _underlying;
interestRate = IBetaInterestModel(IBetaBank(_betaBank).interestModel()).initialRate();
lastAccrueTime = block.timestamp;
}
/// @dev Returns the name of the token.
function name() public view override returns (string memory) {
try IERC20Metadata(underlying).name() returns (string memory data) {
return string(abi.encodePacked('B ', data));
} catch (bytes memory) {
return ERC20.name();
}
}
/// @dev Returns the symbol of the token.
function symbol() public view override returns (string memory) {
try IERC20Metadata(underlying).symbol() returns (string memory data) {
return string(abi.encodePacked('b', data));
} catch (bytes memory) {
return ERC20.symbol();
}
}
/// @dev Returns the decimal places of the token.
function decimals() public view override returns (uint8) {
try IERC20Metadata(underlying).decimals() returns (uint8 data) {
return data;
} catch (bytes memory) {
return ERC20.decimals();
}
}
/// @dev Accrues interest rate and adjusts the rate. Can be called by anyone at any time.
function accrue() public {
// 1. Check time past condition
uint timePassed = block.timestamp - lastAccrueTime;
if (timePassed == 0) return;
lastAccrueTime = block.timestamp;
// 2. Check bank pause condition
require(!Pausable(betaBank).paused(), 'BetaBank/paused');
// 3. Compute the accrued interest value over the past time
(uint totalLoan_, uint totalLoanable_, uint interestRate_) = (
totalLoan,
totalLoanable,
interestRate
); // gas saving by avoiding multiple SLOADs
IBetaConfig config = IBetaConfig(IBetaBank(betaBank).config());
IBetaInterestModel model = IBetaInterestModel(IBetaBank(betaBank).interestModel());
uint interest = (interestRate_ * totalLoan_ * timePassed) / (365 days) / 1e18;
// 4. Update total loan and next interest rate
totalLoan_ += interest;
totalLoan = totalLoan_;
interestRate = model.getNextInterestRate(interestRate_, totalLoanable_, totalLoan_, timePassed);
// 5. Send a portion of collected interest to the beneficiary
if (interest > 0) {
uint reserveRate = config.reserveRate();
if (reserveRate > 0) {
uint toReserve = (interest * reserveRate) / 1e18;
_mint(
config.reserveBeneficiary(),
(toReserve * totalSupply()) / (totalLoan_ + totalLoanable_ - toReserve)
);
}
emit Accrue(interest);
}
}
/// @dev Returns the debt value for the given debt share. Automatically calls accrue.
function fetchDebtShareValue(uint _debtShare) external returns (uint) {
accrue();
if (_debtShare == 0) {
return 0;
}
return Math.ceilDiv(_debtShare * totalLoan, totalDebtShare); // round up
}
/// @dev Mints new bToken to the given address.
/// @param _to The address to mint new bToken for.
/// @param _amount The amount of underlying tokens to deposit via `transferFrom`.
/// @return credit The amount of bToken minted.
function mint(address _to, uint _amount) external nonReentrant returns (uint credit) {
accrue();
uint amount;
{
uint balBefore = IERC20(underlying).balanceOf(address(this));
IERC20(underlying).safeTransferFrom(msg.sender, address(this), _amount);
uint balAfter = IERC20(underlying).balanceOf(address(this));
amount = balAfter - balBefore;
}
uint supply = totalSupply();
if (supply == 0) {
credit = amount - MINIMUM_LIQUIDITY;
// Permanently lock the first MINIMUM_LIQUIDITY tokens
totalLoanable += credit;
totalLoan += MINIMUM_LIQUIDITY;
totalDebtShare += MINIMUM_LIQUIDITY;
_mint(address(1), MINIMUM_LIQUIDITY); // OpenZeppelin ERC20 does not allow minting to 0
} else {
credit = (amount * supply) / (totalLoanable + totalLoan);
totalLoanable += amount;
}
require(credit > 0, 'mint/no-credit-minted');
_mint(_to, credit);
emit Mint(msg.sender, _to, _amount, credit);
}
/// @dev Burns the given bToken for the proportional amount of underlying tokens.
/// @param _to The address to send the underlying tokens to.
/// @param _credit The amount of bToken to burn.
/// @return amount The amount of underlying tokens getting transferred out.
function burn(address _to, uint _credit) external nonReentrant returns (uint amount) {
accrue();
uint supply = totalSupply();
amount = (_credit * (totalLoanable + totalLoan)) / supply;
require(amount > 0, 'burn/no-amount-returned');
totalLoanable -= amount;
_burn(msg.sender, _credit);
IERC20(underlying).safeTransfer(_to, amount);
emit Burn(msg.sender, _to, amount, _credit);
}
/// @dev Borrows the funds for the given address. Must only be called by BetaBank.
/// @param _to The address to borrow the funds for.
/// @param _amount The amount to borrow.
/// @return debtShare The amount of new debt share minted.
function borrow(address _to, uint _amount) external nonReentrant returns (uint debtShare) {
require(msg.sender == betaBank, 'borrow/not-BetaBank');
accrue();
IERC20(underlying).safeTransfer(_to, _amount);
debtShare = Math.ceilDiv(_amount * totalDebtShare, totalLoan); // round up
totalLoanable -= _amount;
totalLoan += _amount;
totalDebtShare += debtShare;
}
/// @dev Repays the debt using funds from the given address. Must only be called by BetaBank.
/// @param _from The address to drain the funds to repay.
/// @param _amount The amount of funds to call via `transferFrom`.
/// @return debtShare The amount of debt share repaid.
function repay(address _from, uint _amount) external nonReentrant returns (uint debtShare) {
require(msg.sender == betaBank, 'repay/not-BetaBank');
accrue();
uint amount;
{
uint balBefore = IERC20(underlying).balanceOf(address(this));
IERC20(underlying).safeTransferFrom(_from, address(this), _amount);
uint balAfter = IERC20(underlying).balanceOf(address(this));
amount = balAfter - balBefore;
}
require(amount <= totalLoan, 'repay/amount-too-high');
debtShare = (amount * totalDebtShare) / totalLoan; // round down
totalLoanable += amount;
totalLoan -= amount;
totalDebtShare -= debtShare;
require(totalDebtShare >= MINIMUM_LIQUIDITY, 'repay/too-low-sum-debt-share');
}
/// @dev Recovers tokens in this contract. EMERGENCY ONLY. Full trust in BetaBank.
/// @param _token The token to recover, can even be underlying so please be careful.
/// @param _to The address to recover tokens to.
/// @param _amount The amount of tokens to recover, or MAX_UINT256 if whole balance.
function recover(
address _token,
address _to,
uint _amount
) external nonReentrant {
require(msg.sender == betaBank, 'recover/not-BetaBank');
if (_amount == type(uint).max) {
_amount = IERC20(_token).balanceOf(address(this));
}
IERC20(_token).safeTransfer(_to, _amount);
}
}
// File: WETHGateway.sol
contract WETHGateway {
using SafeERC20 for IERC20;
address public immutable bweth;
address public immutable weth;
/// @dev Initializes the BWETH contract
/// @param _bweth BWETH token address
constructor(address _bweth) {
address _weth = BToken(_bweth).underlying();
IERC20(_weth).safeApprove(_bweth, type(uint).max);
bweth = _bweth;
weth = _weth;
}
/// @dev Wraps the given ETH to WETH and calls mint action on BWETH for the caller.
/// @param _to The address to receive BToken.
/// @return credit The BWETH amount minted to the caller.
function mint(address _to) external payable returns (uint credit) {
IWETH(weth).deposit{value: msg.value}();
credit = BToken(bweth).mint(_to, msg.value);
}
/// @dev Performs burn action on BWETH and unwraps WETH back to ETH for the caller.
/// @param _to The address to send ETH to.
/// @param _credit The amount of BToken to burn.
/// @return amount The amount of ETH to be received.
function burn(address _to, uint _credit) public returns (uint amount) {
IERC20(bweth).safeTransferFrom(msg.sender, address(this), _credit);
amount = BToken(bweth).burn(address(this), _credit);
IWETH(weth).withdraw(amount);
(bool success, ) = _to.call{value: amount}(new bytes(0));
require(success, 'burn/eth-transfer-failed');
}
/// @dev Similar to burn function, but with an additional call to BToken's EIP712 permit.
function burnWithPermit(
address _to,
uint _credit,
uint _approve,
uint _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external returns (uint amount) {
BToken(bweth).permit(msg.sender, address(this), _approve, _deadline, _v, _r, _s);
amount = burn(_to, _credit);
}
receive() external payable {
require(msg.sender == weth, '!weth');
}
}
| @dev Wraps the given ETH to WETH and calls mint action on BWETH for the caller. @param _to The address to receive BToken. @return credit The BWETH amount minted to the caller. | function mint(address _to) external payable returns (uint credit) {
credit = BToken(bweth).mint(_to, msg.value);
}
| 5,890,114 | [
1,
20785,
326,
864,
512,
2455,
358,
678,
1584,
44,
471,
4097,
312,
474,
1301,
603,
605,
59,
1584,
44,
364,
326,
4894,
18,
225,
389,
869,
1021,
1758,
358,
6798,
605,
1345,
18,
327,
12896,
1021,
605,
59,
1584,
44,
3844,
312,
474,
329,
358,
326,
4894,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
312,
474,
12,
2867,
389,
869,
13,
3903,
8843,
429,
1135,
261,
11890,
12896,
13,
288,
203,
565,
12896,
273,
605,
1345,
12,
70,
91,
546,
2934,
81,
474,
24899,
869,
16,
1234,
18,
1132,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
// Creator: base64.tech
pragma solidity ^0.8.13;
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "./IERC721NES.sol";
/**
* SamuRise Staking controller
*/
contract SamuRiseStakingControllerV2 is OwnableUpgradeable, UUPSUpgradeable {
// Address of the ERC721 token contract
address tokenContract;
// For each token, this map stores the the block.number
// of the block they started staking in.
// if token is mapped to 0, it is currently unstaked.
mapping(uint256 => uint256) public tokenToWhenStaked;
// For each token, this map stores the total duration staked
// measured by block.number
mapping(uint256 => uint256) public tokenToTotalDurationStaked;
// Lock down of staking actions for launching boat to L2
bool stakingPaused;
// tracks whether contract has been initialized
bool private initialized;
/**
* @dev constructor
*/
function initialize(address _tokenContract) public initializer {
require(!initialized, "Contract instance has already been initialized");
initialized = true;
tokenContract = _tokenContract;
__UUPSUpgradeable_init();
__Ownable_init();
}
/**
* @dev returns the additional balance between when token was staked until now
*/
function getCurrentAdditionalBalance(uint256 tokenId)
public
view
returns (uint256)
{
if (tokenToWhenStaked[tokenId] > 0) {
return block.number - tokenToWhenStaked[tokenId];
} else {
return 0;
}
}
/**
* @dev returns total duration the token has been staked.
*/
function getCumulativeDurationStaked(uint256 tokenId)
public
view
returns (uint256)
{
return tokenToTotalDurationStaked[tokenId] + getCurrentAdditionalBalance(tokenId);
}
/**
* @dev Returns the amount of tokens rewarded up until this point.
*/
function getStakingRewards(uint256 tokenId) public view returns (uint256) {
return getCumulativeDurationStaked(tokenId);
}
/**
* @dev Returns the amount of tokens rewarded up until this point.
*/
function stakeFromTokenContract(uint256 tokenId, address originator) public {
require(
msg.sender == tokenContract,
"Function can only be called from token contract"
);
require(
IERC721NES(tokenContract).ownerOf(tokenId) == originator,
"Originator is not the owner of this token"
);
tokenToWhenStaked[tokenId] = block.number;
IERC721NES(tokenContract).stakeFromController(tokenId, originator);
}
/**
* @dev Stakes a token and records the start block number or time stamp.
*/
function stake(uint256 tokenId) public {
require(
IERC721NES(tokenContract).ownerOf(tokenId) == msg.sender,
"You are not the owner of this token"
);
require(
IERC721NES(tokenContract).isStaked(tokenId) == false,
"Token is already staked"
);
require(!stakingPaused, "Staking is currently paused");
tokenToWhenStaked[tokenId] = block.number;
IERC721NES(tokenContract).stakeFromController(tokenId, msg.sender);
}
/**
* @dev Unstakes a token and records the start block number or time stamp.
*/
function unstake(uint256 tokenId) public {
require(
IERC721NES(tokenContract).ownerOf(tokenId) == msg.sender,
"You are not the owner of this token"
);
require(
IERC721NES(tokenContract).isStaked(tokenId) == true,
"Token is not staked"
);
require(!stakingPaused, "Unstaking is currently paused");
tokenToTotalDurationStaked[tokenId] += getCurrentAdditionalBalance(
tokenId
);
tokenToWhenStaked[tokenId] = 0;
IERC721NES(tokenContract).unstakeFromController(tokenId, msg.sender);
}
/**
* @dev Stakes multiple tokens
*/
function stakeTokens(uint256[] memory _tokenIds) public {
for (uint256 i = 0; i < _tokenIds.length; i++) {
stake(_tokenIds[i]);
}
}
/**
* @dev Unstakes multiple tokens
*/
function unstakeTokens(uint256[] memory _tokenIds) public {
for (uint256 i = 0; i < _tokenIds.length; i++) {
unstake(_tokenIds[i]);
}
}
/* owner functions */
function _authorizeUpgrade(address) internal override onlyOwner {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
_;
}
/**
* @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate that the this implementation remains valid after an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual override notDelegated returns (bytes32) {
return _IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// Creator: base64.tech
pragma solidity ^0.8.13;
/*
* Interface for ERC721NES for use in SamuRiseStakingController
*/
interface IERC721NES {
function stakeFromController(uint256 tokenId, address originator) external;
function unstakeFromController(uint256 tokenId, address originator) external;
function ownerOf(uint256 tokenId) external returns (address);
function isStaked(uint256 tokenId) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822ProxiableUpgradeable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal onlyInitializing {
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallUUPS(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
// Upgrades from old implementations will perform a rollback test. This test requires the new
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
// this special case will break upgrade paths from old UUPS implementation to new ones.
if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) {
require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
} | * @dev Unstakes multiple tokens/ | function unstakeTokens(uint256[] memory _tokenIds) public {
for (uint256 i = 0; i < _tokenIds.length; i++) {
unstake(_tokenIds[i]);
}
}
| 1,441,382 | [
1,
984,
334,
3223,
3229,
2430,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
640,
334,
911,
5157,
12,
11890,
5034,
8526,
3778,
389,
2316,
2673,
13,
1071,
288,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
389,
2316,
2673,
18,
2469,
31,
277,
27245,
288,
203,
5411,
640,
334,
911,
24899,
2316,
2673,
63,
77,
19226,
203,
3639,
289,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-07-08
*/
// File: contracts/IERC165.sol
pragma solidity ^0.5.11;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: contracts/IERC721.sol
pragma solidity ^0.5.11;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed tokenOwner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed tokenOwner, address indexed operator, bool approved);
/**
* @dev Returns the number of NFTs in `owner`'s account.
*/
function balanceOf(address tokenOwner) public view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) public view returns (address tokenOwner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(address from, address to, uint256 tokenId) public;
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address tokenOwner, address operator) public view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
// File: contracts/IERC721Receiver.sol
pragma solidity ^0.5.11;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public returns (bytes4);
}
// File: contracts/SafeMath.sol
pragma solidity ^0.5.11;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/Address.sol
pragma solidity ^0.5.11;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* IMPORTANT: It is unsafe to assume that an address for which this
* function returns false is an externally-owned account (EOA) and not a
* contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
}
// File: contracts/Counters.sol
pragma solidity ^0.5.11;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// File: contracts/ERC165.sol
pragma solidity ^0.5.11;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view returns (bool) { //inject PUBLIC FUNC TO EXTERNAL
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: contracts/ERC721.sol
pragma solidity ^0.5.11;
pragma experimental ABIEncoderV2;
/**
* @title ERC721 Customized for Microsponsors from:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721MetadataMintable.sol
*/
/**
* @title Deployed Microsponsors Registry smart contract interface.
* @dev We just use the signatures of the parts we need to interact with:
*/
contract DeployedRegistry {
function isContentIdRegisteredToCaller(uint32 federationId, string memory contentId) public view returns(bool);
function isMinter(uint32 federationId, address account) public view returns (bool);
function isAuthorizedTransferFrom(uint32 federationId, address from, address to, uint256 tokenId, address minter, address owner) public view returns(bool);
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
/*** Contract data ***/
/// @dev owner1, owner2 Admins of this contract.
address public owner1;
address public owner2;
/// @dev paused Admin only. Set to `true` to stop token minting and transfers.
bool public paused = false;
/// @dev mintFee Admin only. Set minting fee; default fee is below (in wei).
uint256 public mintFee = 100000000000000;
/// @dev DeployedRegistry The Microsponsors Registry Contract that verifies participants.
/// Admin can update the contract address here to upgrade Registry.
DeployedRegistry public registry;
/// @title _tokenIds All Token IDs minted, incremented starting at 1
Counters.Counter _tokenIds;
/// @dev _tokenOwner mapping from Token ID to Token Owner
mapping (uint256 => address) private _tokenOwner;
/// @dev _ownedTokensCount mapping from Token Owner to # of owned tokens
mapping (address => Counters.Counter) private _ownedTokensCount;
/// @dev _mintedTokensCount mapping from Token Minter to # of minted tokens
mapping (address => Counters.Counter) private _mintedTokensCount;
/// @dev tokenToFederationId see notes on path to federation in Microsponsors Registry contract
mapping (uint256 => uint32) public tokenToFederationId;
/// @dev TimeSlot metadata struct for each token
/// TimeSlots timestamps are stored as uint48:
/// https://medium.com/@novablitz/storing-structs-is-costing-you-gas-774da988895e
struct TimeSlot {
address minter; // the address of the user who mint()'ed this time slot
string contentId; // the users' registered contentId containing the Property
string propertyName; // describes the Property within the contentId that is tokenized into time slots
uint48 startTime; // min timestamp (when time slot begins)
uint48 endTime; // max timestamp (when time slot ends)
uint48 auctionEndTime; // max timestamp (when auction for time slot ends)
uint16 category; // integer that represents the category (see Microsponsors utils.js)
bool isSecondaryTradingEnabled; // if true, first buyer can trade to others
}
/// @dev _tokenToTimeSlot mapping from Token ID to TimeSlot struct
/// Use tokenTimeSlot() public method to read
mapping(uint256 => TimeSlot) private _tokenToTimeSlot;
/// @dev PropertyNameStruct: name of the time slot
struct PropertyNameStruct {
string propertyName;
}
/// @dev _tokenMinterToPropertyName mapping from Minter => Content ID => array of Property Names
/// Used to display all tokenized Time Slots on a given Property.
/// Using struct because there is no mapping to a dynamic array of bytes32 in Solidity at this time.
mapping(address => mapping(string => PropertyNameStruct[])) private _tokenMinterToPropertyNames;
/// @dev ContentIdStruct The registered Content ID, verified by Registry contract
struct ContentIdStruct {
string contentId;
}
/// @dev _tokenMinterToContentIds Mapping from Token Minter to array of Content IDs
/// that they have *ever* minted tokens for
mapping(address => ContentIdStruct[]) private _tokenMinterToContentIds;
/// @dev _tokenURIs Mapping from Token ID to Token URIs
mapping(uint256 => string) private _tokenURIs;
/// @dev _tokenApprovals Mapping from Token ID to Approved Address
mapping (uint256 => address) private _tokenApprovals;
/// @dev _operatorApprovals Mapping from Token Owner to Operator Approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
// @dev Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
constructor () public {
// Register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
// Set the contract owners to msg.sender by default
owner1 = _msgSender();
owner2 = _msgSender();
}
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they not should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*/
function _msgSender() internal view returns (address) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode -
// see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
/*** Owner (Administrator) functions ***/
/**
* @dev Sets the contract's owner (administrator)
* Based on 0x's Ownable, but modified here
*/
modifier onlyOwner() {
require(
(_msgSender() == owner1) || (_msgSender() == owner2),
"ONLY_CONTRACT_OWNER"
);
_;
}
/**
* @dev Transfer owner (admin) functions to another address
* @param newOwner Address of new owner/ admin of contract
*/
function transferOwnership1(address newOwner)
public
onlyOwner
{
if (newOwner != address(0)) {
owner1 = newOwner;
}
}
function transferOwnership2(address newOwner)
public
onlyOwner
{
if (newOwner != address(0)) {
owner2 = newOwner;
}
}
/**
* @dev Update contract address for Microsponsors Registry contract
* @param newAddress where the Registry contract lives
*/
function updateRegistryAddress(address newAddress)
public
onlyOwner
{
registry = DeployedRegistry(newAddress);
}
/**
* @dev Update the fee (in wei) charged for minting a single token
*/
function updateMintFee(uint256 val)
public
onlyOwner
{
mintFee = val;
}
/// @dev Pausable (adapted from OpenZeppelin via Cryptokitties)
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by contract owner to pause minting and transfers.
function pause() public onlyOwner whenNotPaused {
paused = true;
}
/// @dev Called by contract owner to unpause minting and transfers.
function unpause() public onlyOwner whenPaused {
paused = false;
}
/// @dev Admin withdraws entire balance from contract.
function withdrawBalance() public onlyOwner { //inject PUBLIC FUNC TO EXTERNAL
// Ref: https://diligence.consensys.net/blog/2019/09/stop-using-soliditys-transfer-now/
uint balance = address(this).balance;
(bool success, ) = msg.sender.call.value(balance)("");
require(success, "WITHDRAW_FAILED");
}
/*** Minting tokens ***/
/**
* @dev Function to mint tokens.
* @return tokenId
*/
function mint(
string memory contentId,
string memory propertyName,
uint48 startTime,
uint48 endTime,
uint48 auctionEndTime,
uint16 category,
bool isSecondaryTradingEnabled,
uint32 federationId
)
public
payable
whenNotPaused
returns (uint256)
{
require(msg.value >= mintFee);
require(federationId > 0, "INVALID_FEDERATION_ID");
require(
registry.isMinter(federationId, _msgSender()),
"CALLER_NOT_AUTHORIZED_FOR_MINTER_ROLE"
);
require(
_isValidTimeSlot(contentId, startTime, endTime, auctionEndTime, federationId),
"INVALID_TIME_SLOT"
);
uint256 tokenId = _mint(_msgSender());
_setTokenTimeSlot(tokenId, contentId, propertyName, startTime, endTime, auctionEndTime, category, isSecondaryTradingEnabled);
tokenToFederationId[tokenId] = federationId;
return tokenId;
}
/**
* @dev Function to mint tokens.
* @param tokenURI The token URI of the minted token.
* @return tokenId
*/
function mintWithTokenURI(
string memory contentId,
string memory propertyName,
uint48 startTime,
uint48 endTime,
uint48 auctionEndTime,
uint16 category,
bool isSecondaryTradingEnabled,
uint32 federationId,
string memory tokenURI
)
public
payable
whenNotPaused
returns (uint256)
{
require(msg.value >= mintFee);
require(federationId > 0, "INVALID_FEDERATION_ID");
require(
registry.isMinter(federationId, _msgSender()),
"CALLER_NOT_AUTHORIZED_FOR_MINTER_ROLE"
);
require(
_isValidTimeSlot(contentId, startTime, endTime, auctionEndTime, federationId),
"INVALID_TIME_SLOT"
);
uint256 tokenId = _mint(_msgSender());
_setTokenTimeSlot(tokenId, contentId, propertyName, startTime, endTime, auctionEndTime, category, isSecondaryTradingEnabled);
_setTokenURI(tokenId, tokenURI);
tokenToFederationId[tokenId] = federationId;
return tokenId;
}
/**
* @dev Function to safely mint tokens.
* @return tokenId
*/
function safeMint(
string memory contentId,
string memory propertyName,
uint48 startTime,
uint48 endTime,
uint48 auctionEndTime,
uint16 category,
bool isSecondaryTradingEnabled,
uint32 federationId
)
public
payable
whenNotPaused
returns (uint256)
{
require(msg.value >= mintFee);
require(federationId > 0, "INVALID_FEDERATION_ID");
require(
registry.isMinter(federationId, _msgSender()),
"CALLER_NOT_AUTHORIZED_FOR_MINTER_ROLE"
);
require(
_isValidTimeSlot(contentId, startTime, endTime, auctionEndTime, federationId),
"INVALID_TIME_SLOT"
);
uint256 tokenId = _safeMint(_msgSender());
_setTokenTimeSlot(tokenId, contentId, propertyName, startTime, endTime, auctionEndTime, category, isSecondaryTradingEnabled);
tokenToFederationId[tokenId] = federationId;
return tokenId;
}
/**
* @dev Function to safely mint tokens.
* @param data bytes data to send along with a safe transfer check.
* @return tokenId
*/
function safeMint(
string memory contentId,
string memory propertyName,
uint48 startTime,
uint48 endTime,
uint48 auctionEndTime,
uint16 category,
bool isSecondaryTradingEnabled,
uint32 federationId,
bytes memory data
)
public
payable
whenNotPaused
returns (uint256)
{
require(msg.value >= mintFee);
require(federationId > 0, "INVALID_FEDERATION_ID");
require(
registry.isMinter(federationId, _msgSender()),
"CALLER_NOT_AUTHORIZED_FOR_MINTER_ROLE"
);
require(
_isValidTimeSlot(contentId, startTime, endTime, auctionEndTime, federationId),
"INVALID_TIME_SLOT"
);
uint256 tokenId = _safeMint(_msgSender(), data);
_setTokenTimeSlot(tokenId, contentId, propertyName, startTime, endTime, auctionEndTime, category, isSecondaryTradingEnabled);
tokenToFederationId[tokenId] = federationId;
return tokenId;
}
/**
* @param tokenURI The token URI of the minted token.
* @return tokenId
*/
function safeMintWithTokenURI(
string memory contentId,
string memory propertyName,
uint48 startTime,
uint48 endTime,
uint48 auctionEndTime,
uint16 category,
bool isSecondaryTradingEnabled,
uint32 federationId,
string memory tokenURI
)
public
payable
whenNotPaused
returns (uint256)
{
require(msg.value >= mintFee);
require(federationId > 0, "INVALID_FEDERATION_ID");
require(
registry.isMinter(federationId, _msgSender()),
"CALLER_NOT_AUTHORIZED_FOR_MINTER_ROLE"
);
require(
_isValidTimeSlot(contentId, startTime, endTime, auctionEndTime, federationId),
"INVALID_TIME_SLOT"
);
uint256 tokenId = _safeMint(_msgSender());
_setTokenTimeSlot(tokenId, contentId, propertyName, startTime, endTime, auctionEndTime, category, isSecondaryTradingEnabled);
_setTokenURI(tokenId, tokenURI);
tokenToFederationId[tokenId] = federationId;
return tokenId;
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @return tokenId
*/
function _safeMint(address to) internal returns (uint256) {
uint256 tokenId = _safeMint(to, "");
return tokenId;
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param data bytes data to send along with a safe transfer check
* @return tokenId
*/
function _safeMint(address to, bytes memory data) internal returns (uint256) {
uint256 tokenId = _mint(to);
require(
_checkOnERC721Received(address(0), to, tokenId, data),
"TRANSFER_TO_NON_ERC721RECEIVER_IMPLEMENTER"
);
return tokenId;
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
*/
function _mint(address to) internal returns (uint256) {
require(to != address(0), "MINT_TO_ZERO_ADDRESS");
_tokenIds.increment();
uint256 tokenId = _tokenIds.current();
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
_mintedTokensCount[to].increment();
emit Transfer(address(0), to, tokenId);
return tokenId;
}
/*** Token URIs ***/
/**
* @dev Internal function to set the token URI for a given token.
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
require(
_exists(tokenId),
"NON_EXISTENT_TOKEN"
);
_tokenURIs[tokenId] = uri;
}
/**
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
* @return URI for a given token ID.
*/
function tokenURI(uint256 tokenId) public view returns (string memory) { //inject PUBLIC FUNC TO EXTERNAL
require(
_exists(tokenId),
"NON_EXISTENT_TOKEN"
);
return _tokenURIs[tokenId];
}
/*** Token TimeSlot data and metadata ***/
function _isValidTimeSlot(
string memory contentId,
uint48 startTime,
uint48 endTime,
uint48 auctionEndTime,
uint32 federationId
) internal view returns (bool) {
require(
registry.isContentIdRegisteredToCaller(federationId, contentId),
"CONTENT_ID_NOT_REGISTERED_TO_CALLER"
);
require(
startTime > auctionEndTime,
"START_TIME_AFTER_AUCTION_END_TIME"
);
require(
endTime > startTime,
"START_TIME_AFTER_END_TIME"
);
return true;
}
function _isContentIdMappedToMinter(
string memory contentId
) internal view returns (bool) {
ContentIdStruct[] memory a = _tokenMinterToContentIds[msg.sender];
bool foundMatch = false;
for (uint i = 0; i < a.length; i++) {
if (stringsMatch(contentId, a[i].contentId)) {
foundMatch = true;
}
}
return foundMatch;
}
function _isPropertyNameMappedToMinter(
string memory contentId,
string memory propertyName
) internal view returns (bool) {
PropertyNameStruct[] memory a = _tokenMinterToPropertyNames[msg.sender][contentId];
bool foundMatch = false;
for (uint i = 0; i < a.length; i++) {
if (stringsMatch(propertyName, a[i].propertyName)) {
foundMatch = true;
}
}
return foundMatch;
}
function _setTokenTimeSlot(
uint256 tokenId,
string memory contentId,
string memory propertyName,
uint48 startTime,
uint48 endTime,
uint48 auctionEndTime,
uint16 category,
bool isSecondaryTradingEnabled
) internal {
require(
_exists(tokenId),
"NON_EXISTENT_TOKEN"
);
TimeSlot memory _timeSlot = TimeSlot({
minter: address(_msgSender()),
contentId: string(contentId),
propertyName: string(propertyName),
startTime: uint48(startTime),
endTime: uint48(endTime),
auctionEndTime: uint48(auctionEndTime),
category: uint16(category),
isSecondaryTradingEnabled: bool(isSecondaryTradingEnabled)
});
_tokenToTimeSlot[tokenId] = _timeSlot;
if (!_isContentIdMappedToMinter(contentId)) {
_tokenMinterToContentIds[_msgSender()].push( ContentIdStruct(contentId) );
}
if (!_isPropertyNameMappedToMinter(contentId, propertyName)) {
_tokenMinterToPropertyNames[_msgSender()][contentId].push( PropertyNameStruct(propertyName) );
}
}
function tokenTimeSlot(uint256 tokenId) public view returns (
address minter,
address owner,
string memory contentId,
string memory propertyName,
uint48 startTime,
uint48 endTime,
uint48 auctionEndTime,
uint16 category,
bool isSecondaryTradingEnabled,
uint32 federationId
) {
require(
_exists(tokenId),
"NON_EXISTENT_TOKEN"
);
TimeSlot memory _timeSlot = _tokenToTimeSlot[tokenId];
uint32 _federationId = tokenToFederationId[tokenId];
return (
_timeSlot.minter,
ownerOf(tokenId),
_timeSlot.contentId,
_timeSlot.propertyName,
_timeSlot.startTime,
_timeSlot.endTime,
_timeSlot.auctionEndTime,
_timeSlot.category,
_timeSlot.isSecondaryTradingEnabled,
_federationId
);
}
/*** Token minter queries ***/
/// @dev Look up all Content IDs a Minter has tokenized TimeSlots for.
/// We're not getting this from the Registry because we want to keep
/// a separate record here of all Content ID's the acct has *ever*
/// minted tokens for. The registry is for keeping track of their
/// current (not necessarily past) Content ID registrations.
function tokenMinterContentIds(address minter) public view returns (string[] memory) { //inject PUBLIC FUNC TO EXTERNAL
ContentIdStruct[] memory m = _tokenMinterToContentIds[minter];
string[] memory r = new string[](m.length);
for (uint i = 0; i < m.length; i++) {
r[i] = m[i].contentId;
}
return r;
}
/// @dev Look up all Property Names a Minter has created Time Slots for
/// with a particular Content ID
function tokenMinterPropertyNames(
address minter,
string calldata contentId
) external view returns (string[] memory) {
PropertyNameStruct[] memory m = _tokenMinterToPropertyNames[minter][contentId];
string[] memory r = new string[](m.length);
for (uint i = 0; i < m.length; i++) {
r[i] = m[i].propertyName;
}
return r;
}
/**
* Return all the Token IDs minted by a given account.
* @dev This method MUST NEVER be called by smart contract code. First, it's fairly
* expensive (it walks the entire _tokenIds array looking for tokens belonging to minter),
* but it also returns a dynamic array, which is only supported for web3 calls, and
* not contract-to-contract calls (at this time).
*/
function tokensMintedBy(address minter) public view returns (uint256[] memory) { //inject PUBLIC FUNC TO EXTERNAL
require(
minter != address(0),
"CANNOT_QUERY_ZERO_ADDRESS"
);
uint256 tokenCount = _mintedTokensCount[minter].current();
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalTokens = totalSupply();
uint256 resultIndex = 0;
// All Tokens have IDs starting at 1 and increase
// sequentially up to the total supply count.
uint256 tokenId;
for (tokenId = 1; tokenId <= totalTokens; tokenId++) {
if (_tokenToTimeSlot[tokenId].minter == minter) {
result[resultIndex] = tokenId;
resultIndex++;
}
}
return result;
}
}
/*** Token balance and ownership queries ***/
/**
* @dev Gets the total number of tokens ever minted.
*/
function totalSupply() public view returns (uint256) {
return _tokenIds.current();
}
/**
* @dev Gets the balance of the specified address.
* @param tokenOwner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address tokenOwner) public view returns (uint256) {
require(
tokenOwner != address(0),
"CANNOT_QUERY_ZERO_ADDRESS"
);
return _ownedTokensCount[tokenOwner].current();
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address tokenOwner = _tokenOwner[tokenId];
return tokenOwner;
}
/**
* @param tokenOwner The owner whose tokens we are interested in.
* @dev This method MUST NEVER be called by smart contract code. First, it's fairly
* expensive (it walks the entire _tokenIds array looking for tokens belonging to owner),
* but it also returns a dynamic array, which is only supported for web3 calls, and
* not contract-to-contract calls (at this time).
*/
function tokensOfOwner(address tokenOwner) public view returns(uint256[] memory) { //inject PUBLIC FUNC TO EXTERNAL
uint256 tokenCount = balanceOf(tokenOwner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalTokens = totalSupply();
uint256 resultIndex = 0;
// All Tokens have IDs starting at 1 and increase
// sequentially up to the total count.
uint256 tokenId;
for (tokenId = 1; tokenId <= totalTokens; tokenId++) {
if (_tokenOwner[tokenId] == tokenOwner) {
result[resultIndex] = tokenId;
resultIndex++;
}
}
return result;
}
}
/*** Approvals & Transfers ***/
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId)
public
whenNotPaused
{
address tokenOwner = ownerOf(tokenId);
require(
to != tokenOwner,
"APPROVAL_IS_REDUNDANT"
);
require(
_msgSender() == tokenOwner || isApprovedForAll(tokenOwner, _msgSender()),
"CALLER_NOT_AUTHORIZED"
);
_tokenApprovals[tokenId] = to;
emit Approval(tokenOwner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(
_exists(tokenId),
"NON_EXISTENT_TOKEN"
);
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf.
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved)
public
whenNotPaused
{
require(to != _msgSender(), "CALLER_CANNOT_APPROVE_SELF");
_operatorApprovals[_msgSender()][to] = approved;
emit ApprovalForAll(_msgSender(), to, approved);
}
/**
* @dev Tells whether an operator is approved by a given token owner.
* @param tokenOwner token owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the token owner
*/
function isApprovedForAll(address tokenOwner, address operator)
public
view
returns (bool)
{
return _operatorApprovals[tokenOwner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* Requires the msg.sender to be the owner, approved, or operator.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, uint256 tokenId)
public
whenNotPaused
{
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"UNAUTHORIZED_TRANSFER"
);
address minter = _tokenToTimeSlot[tokenId].minter;
address owner = ownerOf(tokenId);
uint32 federationId = tokenToFederationId[tokenId];
if (_tokenToTimeSlot[tokenId].isSecondaryTradingEnabled == false) {
require(
isSecondaryTrade(from, to, tokenId) == false,
"SECONDARY_TRADING_DISABLED"
);
}
require(
registry.isAuthorizedTransferFrom(federationId, from, to, tokenId, minter, owner),
"UNAUTHORIZED_TRANSFER"
);
_transferFrom(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the _msgSender() to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data)
public
whenNotPaused
{
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"UNAUTHORIZED_TRANSFER"
);
address minter = _tokenToTimeSlot[tokenId].minter;
address owner = ownerOf(tokenId);
uint32 federationId = tokenToFederationId[tokenId];
if (_tokenToTimeSlot[tokenId].isSecondaryTradingEnabled == false) {
require(
isSecondaryTrade(from, to, tokenId) == false,
"SECONDARY_TRADING_DISABLED"
);
}
require(
registry.isAuthorizedTransferFrom(federationId, from, to, tokenId, minter, owner),
"UNAUTHORIZED_TRANSFER"
);
_safeTransferFrom(from, to, tokenId, data);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param data bytes data to send along with a safe transfer check
*/
function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data)
internal
{
_transferFrom(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, data),
"TRANSFER_TO_NON_ERC721RECEIVER_IMPLEMENTER"
);
}
/**
* @dev Returns whether the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address tokenOwner = _tokenOwner[tokenId];
return tokenOwner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
returns (bool)
{
require(
_exists(tokenId),
"NON_EXISTENT_TOKEN"
);
address tokenOwner = ownerOf(tokenId);
return (spender == tokenOwner || getApproved(tokenId) == spender || isApprovedForAll(tokenOwner, spender));
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal {
require(
ownerOf(tokenId) == from,
"UNAUTHORIZED_TRANSFER"
);
require(
to != address(0),
"TRANSFER_TO_ZERO_ADDRESS"
);
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* This function is deprecated.
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory data)
internal
returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data);
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Private function to clear current approval of a given token ID.
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
/*** Burn Tokens ***/
// solhint-disable
/**
* @dev Customized for Microsponsors
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721Burnable.sol * @dev Burns a specific ERC721 token.
* @param tokenId uint256 id of the ERC721 token to be burned
*/
// solhint-enable
function burn(uint256 tokenId) public whenNotPaused {
address minter = _tokenToTimeSlot[tokenId].minter;
address tokenOwner = ownerOf(tokenId);
uint32 federationId = tokenToFederationId[tokenId];
if (tokenOwner == minter) {
require(
registry.isMinter(federationId, _msgSender()),
"UNAUTHORIZED_BURN"
);
}
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"UNAUTHORIZED_BURN"
);
_burn(tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {_burn} instead.
* @param tokenOwner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address tokenOwner, uint256 tokenId) internal {
require(
ownerOf(tokenId) == tokenOwner,
"UNAUTHORIZED_BURN"
);
_clearApproval(tokenId);
_ownedTokensCount[tokenOwner].decrement();
_tokenOwner[tokenId] = address(0);
// Clear token URIs (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
// Clear time slot data
delete _tokenToTimeSlot[tokenId];
emit Transfer(tokenOwner, address(0), tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* @param tokenId uint256 ID of the token being burned
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/*** Helper fns ***/
function stringsMatch (
string memory a,
string memory b
)
private
pure
returns (bool)
{
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))) );
}
function isSecondaryTrade (
address from,
address to,
uint256 tokenId
)
internal
view
returns (bool)
{
address minter = _tokenToTimeSlot[tokenId].minter;
if (from == minter || to == minter) {
return false;
} else {
return true;
}
}
}
// File: contracts/Microsponsors.sol
/**
* Customized for Microsponsors
* from Open Zeppelin's ERC721Metadata contract, which is MIT Licensed:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721Metadata.sol
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
contract Microsponsors is ERC721 {
// Token name
string private _name;
// Token symbol
string private _symbol;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/**
* @dev Constructor function
*/
constructor (string memory name, string memory symbol, address registryAddress) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
super.updateRegistryAddress(registryAddress);
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() public view returns (string memory) { //inject PUBLIC FUNC TO EXTERNAL
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() public view returns (string memory) { //inject PUBLIC FUNC TO EXTERNAL
return _symbol;
}
} | solhint-disable* @dev Customized for Microsponsors @param tokenId uint256 id of the ERC721 token to be burned/ solhint-enable | function burn(uint256 tokenId) public whenNotPaused {
address minter = _tokenToTimeSlot[tokenId].minter;
address tokenOwner = ownerOf(tokenId);
uint32 federationId = tokenToFederationId[tokenId];
if (tokenOwner == minter) {
require(
registry.isMinter(federationId, _msgSender()),
"UNAUTHORIZED_BURN"
);
}
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"UNAUTHORIZED_BURN"
);
_burn(tokenId);
}
| 922,049 | [
1,
18281,
11317,
17,
8394,
225,
6082,
1235,
364,
18284,
87,
500,
87,
1383,
225,
1147,
548,
2254,
5034,
612,
434,
326,
4232,
39,
27,
5340,
1147,
358,
506,
18305,
329,
19,
3704,
11317,
17,
7589,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
18305,
12,
11890,
5034,
1147,
548,
13,
1071,
1347,
1248,
28590,
288,
203,
203,
3639,
1758,
1131,
387,
273,
389,
2316,
774,
950,
8764,
63,
2316,
548,
8009,
1154,
387,
31,
203,
3639,
1758,
1147,
5541,
273,
3410,
951,
12,
2316,
548,
1769,
203,
3639,
2254,
1578,
22572,
7067,
548,
273,
1147,
774,
21503,
7067,
548,
63,
2316,
548,
15533,
203,
203,
203,
3639,
309,
261,
2316,
5541,
422,
1131,
387,
13,
288,
203,
5411,
2583,
12,
203,
7734,
4023,
18,
291,
49,
2761,
12,
31835,
7067,
548,
16,
389,
3576,
12021,
1435,
3631,
203,
7734,
315,
2124,
28383,
67,
38,
8521,
6,
203,
5411,
11272,
203,
3639,
289,
203,
203,
3639,
2583,
12,
203,
5411,
389,
291,
31639,
1162,
5541,
24899,
3576,
12021,
9334,
1147,
548,
3631,
203,
5411,
315,
2124,
28383,
67,
38,
8521,
6,
203,
3639,
11272,
203,
203,
3639,
389,
70,
321,
12,
2316,
548,
1769,
203,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x80FBdCf20Af77D7DCB21d7104FadDBC5D8bD83eb/sources/project:/contracts/reserve/DistributionHelper.sol | previously anyGoodDollar_unused; kept for storage layout upgrades
| FeeSettings public feeSettings; | 3,702,824 | [
1,
11515,
715,
1281,
18195,
40,
25442,
67,
14375,
31,
16555,
364,
2502,
3511,
28844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
14667,
2628,
1071,
14036,
2628,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.8;
import 'openzeppelin-solidity/contracts/ownership/Ownable.sol';
import 'openzeppelin-solidity/contracts/lifecycle/Pausable.sol';
/*
* @title OnlineMarket
*
* @dev This contract allows the addition and removal of admins and storefront owners
*
*/
contract OnlineMarket is Ownable, Pausable{
//Owner
//address owner;
// Admin mapping
mapping(address => bool) private admins;
//Mapping of StoreOwner approved or not by Admin
mapping(address => bool) private storeOwnerApprovalMapping;
// Hold the requested Store Owners
address[] private requestedStoreOwners;
// Hold the requested Store Owners index against store owner Ids
mapping(address => uint) private requestedStoreOwnersIndex;
// Hold the approved Store Owners
address[] private approvedStoreOwners;
// Hold the approved Store Owners index against store owner Ids
mapping(address => uint) private approvedStoreOwnersIndex;
//Events which are emitted at various points
event LogAdminAdded(address adminAddress);
event LogAdminRemoved(address adminAddress);
event LogStoreOwnersApproved(address storeOwner);
event LogStoreOwnerRemoved(address storeOwner);
event LogStoreOwnerAdded(address storeOwner);
// Modifier to restrict function calls to only admin
modifier onlyAdmin(){
require(admins[msg.sender] == true);
_;
}
/** @dev The account that deploys contract is made admin.
*/
constructor() public{
admins[msg.sender] = true;
}
/** @dev Function is to add an Admin. Admins can add more admins.
* @param adminAddress Address of the Admin
*/
function addAdmin(address adminAddress) public onlyAdmin whenNotPaused{
admins[adminAddress] = true;
emit LogAdminAdded(adminAddress);
}
/** @dev Function is to remove an Admin. OnlyOwner can remove admins
* @param adminAddress Address of the Admin
*/
function removeAdmin(address adminAddress) public onlyOwner whenNotPaused{
require(admins[adminAddress] == true);
admins[adminAddress] = false;
emit LogAdminRemoved(adminAddress);
}
/** @dev Function is to check if an address is Admin or not.
* @param adminAddress Address of the Admin
* @return true if address is admin otherwise false
*/
function checkAdmin(address adminAddress) public view returns(bool){
return admins[adminAddress];
}
/** @dev Function is to view a requested StoreOwner at a particular index
* @param index requested store owner index
* @return address of requestedStoreOwner at the requested index
*/
function viewRequestedStoreOwner(uint index) public view onlyAdmin returns (address){
return requestedStoreOwners[index];
}
/** @dev Function is to view all requested StoreOwners
* @return addresses of all the requestedStoreOwner
*/
function viewRequestedStoreOwners() public view onlyAdmin returns (address[] memory){
return requestedStoreOwners;
}
/** @dev Function is to view an approved StoreOwners at requested index
* @return addresses of the approvedStoreOwner
*/
function viewApprovedStoreOwner(uint index) public view onlyAdmin returns (address){
return approvedStoreOwners[index];
}
/** @dev Function is to view all approved StoreOwners
* @return addresseses of all the approved StoreOwner
*/
function viewApprovedStoreOwners() public view onlyAdmin returns (address[] memory){
return approvedStoreOwners;
}
/** @dev Function is to approve the Stores
* @param storeOwner address
*/
function approveStoreOwners(address storeOwner) public onlyAdmin whenNotPaused{
//Updated mapping with status of approval
storeOwnerApprovalMapping[storeOwner] = true;
// remove it from requested store owners
removeRequestedStoreOwner(storeOwner);
// Add it to approved store owners
approvedStoreOwners.push(storeOwner);
approvedStoreOwnersIndex[storeOwner] = approvedStoreOwners.length-1;
emit LogStoreOwnersApproved(storeOwner);
}
/** @dev Function is to remove the approved storeOwner
* @param storeOwner address
* @return true if store is removed otherwise false
*/
function removeStoreOwner(address storeOwner) public onlyAdmin whenNotPaused returns(bool){
//Updated mapping with false
storeOwnerApprovalMapping[storeOwner] = false;
// remove it from approved store owners
removeApprovedStoreOwner(storeOwner);
emit LogStoreOwnerRemoved(storeOwner);
return true;
}
/** @dev Function is to check the status of the store owner
* @param storeOwner address
* @return true if store is approved otherwise false
*/
function checkStoreOwnerStatus(address storeOwner) public view returns(bool){
return storeOwnerApprovalMapping[storeOwner];
}
/** @dev Function is to add store owner
* @return true if store is added otherwise false
*/
function addStoreOwner() public whenNotPaused returns(bool){
require(storeOwnerApprovalMapping[msg.sender] == false);
requestedStoreOwners.push(msg.sender);
requestedStoreOwnersIndex[msg.sender] = requestedStoreOwners.length-1;
emit LogStoreOwnerAdded(msg.sender);
return true;
}
/** @dev Function is to get requested store owners length
* @return length of requestedStoreOwners
*/
function getRequestedStoreOwnersLength() public view returns(uint){
return requestedStoreOwners.length;
}
/** @dev Function is to get approved store owners length
* @return length of approvedStoreOwners
*/
function getApprovedStoreOwnersLength() public view returns(uint){
return approvedStoreOwners.length;
}
/** @dev Function is to remove the requestedStoreOwner
* @param storeOwner address
*/
function removeRequestedStoreOwner(address storeOwner) private onlyAdmin whenNotPaused {
uint index = requestedStoreOwnersIndex[storeOwner];
if (requestedStoreOwners.length > 1) {
requestedStoreOwners[index] = requestedStoreOwners[requestedStoreOwners.length-1];
}
requestedStoreOwners.length--;
}
/** @dev Function is to remove approvedStoreOwner
* @param storeOwner address
*/
function removeApprovedStoreOwner(address storeOwner) private onlyAdmin whenNotPaused{
uint index = approvedStoreOwnersIndex[storeOwner];
if (approvedStoreOwners.length > 1) {
approvedStoreOwners[index] = approvedStoreOwners[approvedStoreOwners.length-1];
}
approvedStoreOwners.length--;
}
} | * @dev Function is to view all approved StoreOwners @return addresseses of all the approved StoreOwner/ | function viewApprovedStoreOwners() public view onlyAdmin returns (address[] memory){
return approvedStoreOwners;
}
| 14,123,464 | [
1,
2083,
353,
358,
1476,
777,
20412,
4994,
5460,
414,
327,
6138,
281,
434,
777,
326,
20412,
4994,
5541,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1476,
31639,
2257,
5460,
414,
1435,
1071,
1476,
1338,
4446,
1135,
261,
2867,
8526,
3778,
15329,
203,
3639,
327,
20412,
2257,
5460,
414,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.18;
/// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution.
/// @author Stefan George - <[email protected]>
contract MultiSigWallet {
uint constant public MAX_OWNER_COUNT = 50;
event Confirmation(address indexed sender, uint indexed transactionId);
event Revocation(address indexed sender, uint indexed transactionId);
event Submission(uint indexed transactionId);
event Execution(uint indexed transactionId);
event ExecutionFailure(uint indexed transactionId);
event Deposit(address indexed sender, uint value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint required);
mapping (uint => Transaction) public transactions;
mapping (uint => mapping (address => bool)) public confirmations;
mapping (address => bool) public isOwner;
address[] public owners;
uint public required;
uint public transactionCount;
struct Transaction {
address destination;
uint value;
bytes data;
bool executed;
}
modifier onlyWallet() {
require (msg.sender == address(this));
_;
}
modifier ownerDoesNotExist(address owner) {
require (!isOwner[owner]);
_;
}
modifier ownerExists(address owner) {
require (isOwner[owner]);
_;
}
modifier transactionExists(uint transactionId) {
require (transactions[transactionId].destination != 0);
_;
}
modifier confirmed(uint transactionId, address owner) {
require (confirmations[transactionId][owner]);
_;
}
modifier notConfirmed(uint transactionId, address owner) {
require (!confirmations[transactionId][owner]);
_;
}
modifier notExecuted(uint transactionId) {
require (!transactions[transactionId].executed);
_;
}
modifier notNull(address _address) {
require (_address != 0);
_;
}
modifier validRequirement(uint ownerCount, uint _required) {
require (ownerCount <= MAX_OWNER_COUNT);
require (_required <= ownerCount);
require (_required != 0);
require (ownerCount != 0);
_;
}
/// @dev Fallback function allows to deposit ether.
function()
payable
{
if (msg.value > 0)
Deposit(msg.sender, msg.value);
}
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
function MultiSigWallet(address[] _owners, uint _required)
public
validRequirement(_owners.length, _required)
{
for (uint i=0; i<_owners.length; i++) {
require ( !isOwner[_owners[i]]);
require (_owners[i] != 0);
isOwner[_owners[i]] = true;
}
owners = _owners;
required = _required;
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param owner Address of new owner.
function addOwner(address owner)
public
onlyWallet
ownerDoesNotExist(owner)
notNull(owner)
validRequirement(owners.length + 1, required)
{
isOwner[owner] = true;
owners.push(owner);
OwnerAddition(owner);
}
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param owner Address of owner.
function removeOwner(address owner)
public
onlyWallet
ownerExists(owner)
{
isOwner[owner] = false;
for (uint i=0; i<owners.length - 1; i++)
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1];
break;
}
owners.length -= 1;
if (required > owners.length)
changeRequirement(owners.length);
OwnerRemoval(owner);
}
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param owner Address of owner to be replaced.
/// @param owner Address of new owner.
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint i=0; i<owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
isOwner[newOwner] = true;
OwnerRemoval(owner);
OwnerAddition(newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
function changeRequirement(uint _required)
public
onlyWallet
validRequirement(owners.length, _required)
{
required = _required;
RequirementChange(_required);
}
/// @dev Allows an owner to submit and confirm a transaction.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function submitTransaction(address destination, uint value, bytes data)
public
returns (uint transactionId)
{
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param transactionId Transaction ID.
function revokeConfirmation(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
Revocation(msg.sender, transactionId);
}
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint transactionId)
public
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txn = transactions[transactionId];
txn.executed = true;
if (txn.destination.call.value(txn.value)(txn.data))
Execution(transactionId);
else {
ExecutionFailure(transactionId);
txn.executed = false;
}
}
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return Confirmation status.
function isConfirmed(uint transactionId)
public
constant
returns (bool)
{
uint count = 0;
for (uint i=0; i<owners.length; i++) {
if (confirmations[transactionId][owners[i]])
count += 1;
if (count == required)
return true;
}
}
/*
* Internal functions
*/
/// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function addTransaction(address destination, uint value, bytes data)
internal
notNull(destination)
returns (uint transactionId)
{
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false
});
transactionCount += 1;
Submission(transactionId);
}
/*
* Web3 call functions
*/
/// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return Number of confirmations.
function getConfirmationCount(uint transactionId)
public
constant
returns (uint count)
{
for (uint i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]])
count += 1;
}
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed)
public
constant
returns (uint count)
{
for (uint i=0; i<transactionCount; i++)
if ( pending && !transactions[i].executed
|| executed && transactions[i].executed)
count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners()
public
constant
returns (address[])
{
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param transactionId Transaction ID.
/// @return Returns array of owner addresses.
function getConfirmations(uint transactionId)
public
constant
returns (address[] _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint count = 0;
uint i;
for (i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i=0; i<count; i++)
_confirmations[i] = confirmationsTemp[i];
}
/// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Returns array of transaction IDs.
function getTransactionIds(uint from, uint to, bool pending, bool executed)
public
constant
returns (uint[] _transactionIds)
{
uint[] memory transactionIdsTemp = new uint[](transactionCount);
uint count = 0;
uint i;
for (i=0; i<transactionCount; i++)
if ( pending && !transactions[i].executed
|| executed && transactions[i].executed)
{
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint[](to - from);
for (i=from; i<to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
}
/// @title Multisignature wallet with daily limit - Allows an owner to withdraw a daily limit without multisig.
/// @author Stefan George - <[email protected]>
contract MultiSigWalletWithDailyLimit is MultiSigWallet {
event DailyLimitChange(uint dailyLimit);
uint public dailyLimit;
uint public lastDay;
uint public spentToday;
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners, required number of confirmations and daily withdraw limit.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
/// @param _dailyLimit Amount in wei, which can be withdrawn without confirmations on a daily basis.
function MultiSigWalletWithDailyLimit(address[] _owners, uint _required, uint _dailyLimit)
public
MultiSigWallet(_owners, _required)
{
dailyLimit = _dailyLimit;
}
/// @dev Allows to change the daily limit. Transaction has to be sent by wallet.
/// @param _dailyLimit Amount in wei.
function changeDailyLimit(uint _dailyLimit)
public
onlyWallet
{
dailyLimit = _dailyLimit;
DailyLimitChange(_dailyLimit);
}
/// @dev Allows anyone to execute a confirmed transaction or ether withdraws until daily limit is reached.
/// @param transactionId Transaction ID.
function executeTransaction(uint transactionId)
public
notExecuted(transactionId)
{
Transaction storage txn = transactions[transactionId];
bool confirmed = isConfirmed(transactionId);
if (confirmed || txn.data.length == 0 && isUnderLimit(txn.value)) {
txn.executed = true;
if (!confirmed)
spentToday += txn.value;
if (txn.destination.call.value(txn.value)(txn.data))
Execution(transactionId);
else {
ExecutionFailure(transactionId);
txn.executed = false;
if (!confirmed)
spentToday -= txn.value;
}
}
}
/*
* Internal functions
*/
/// @dev Returns if amount is within daily limit and resets spentToday after one day.
/// @param amount Amount to withdraw.
/// @return Returns if amount is under daily limit.
function isUnderLimit(uint amount)
internal
returns (bool)
{
if (now > lastDay + 24 hours) {
lastDay = now;
spentToday = 0;
}
if (spentToday + amount > dailyLimit || spentToday + amount < spentToday)
return false;
return true;
}
/*
* Web3 call functions
*/
/// @dev Returns maximum withdraw amount.
/// @return Returns amount.
function calcMaxWithdraw()
public
constant
returns (uint)
{
if (now > lastDay + 24 hours)
return dailyLimit;
if (dailyLimit < spentToday)
return 0;
return dailyLimit - spentToday;
}
} | @dev Returns list of transaction IDs in defined range. @param from Index start position of transaction array. @param to Index end position of transaction array. @param pending Include pending transactions. @param executed Include executed transactions. @return Returns array of transaction IDs. | function getTransactionIds(uint from, uint to, bool pending, bool executed)
public
constant
returns (uint[] _transactionIds)
{
uint[] memory transactionIdsTemp = new uint[](transactionCount);
uint count = 0;
uint i;
for (i=0; i<transactionCount; i++)
if ( pending && !transactions[i].executed
|| executed && transactions[i].executed)
{
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint[](to - from);
for (i=from; i<to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
| 39,663 | [
1,
1356,
666,
434,
2492,
7115,
316,
2553,
1048,
18,
225,
628,
3340,
787,
1754,
434,
2492,
526,
18,
225,
358,
3340,
679,
1754,
434,
2492,
526,
18,
225,
4634,
12672,
4634,
8938,
18,
225,
7120,
12672,
7120,
8938,
18,
327,
2860,
526,
434,
2492,
7115,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
15674,
2673,
12,
11890,
628,
16,
2254,
358,
16,
1426,
4634,
16,
1426,
7120,
13,
203,
3639,
1071,
203,
3639,
5381,
203,
3639,
1135,
261,
11890,
8526,
389,
7958,
2673,
13,
203,
565,
288,
203,
3639,
2254,
8526,
3778,
2492,
2673,
7185,
273,
394,
2254,
8526,
12,
7958,
1380,
1769,
203,
3639,
2254,
1056,
273,
374,
31,
203,
3639,
2254,
277,
31,
203,
3639,
364,
261,
77,
33,
20,
31,
277,
32,
7958,
1380,
31,
277,
27245,
203,
5411,
309,
261,
282,
4634,
597,
401,
20376,
63,
77,
8009,
4177,
4817,
203,
7734,
747,
7120,
597,
8938,
63,
77,
8009,
4177,
4817,
13,
203,
5411,
288,
203,
7734,
2492,
2673,
7185,
63,
1883,
65,
273,
277,
31,
203,
7734,
1056,
1011,
404,
31,
203,
5411,
289,
203,
3639,
389,
7958,
2673,
273,
394,
2254,
8526,
12,
869,
300,
628,
1769,
203,
3639,
364,
261,
77,
33,
2080,
31,
277,
32,
869,
31,
277,
27245,
203,
5411,
389,
7958,
2673,
63,
77,
300,
628,
65,
273,
2492,
2673,
7185,
63,
77,
15533,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/44787/0x26dc26D62716d1356327C521E836EB8d2DFFA87E/sources/contracts/cross-chain/ToucanCrosschainMessenger.sol | ============ Constants ============ ============ Events ============ ============ Constructor ============ | contract ToucanCrosschainMessenger is ToucanCrosschainMessengerStorage, Router {
string public constant VERSION = '0.1.0';
bytes32 public immutable DOMAIN_SEPARATOR;
event BridgeRequestReceived(
uint32 indexed originDomain,
uint32 toDomain,
address indexed bridger,
address indexed token,
uint256 amount,
bytes32 requesthash
);
event BridgeRequestSent(
uint32 originDomain,
uint32 indexed toDomain,
address indexed bridger,
address indexed token,
uint256 amount,
uint256 nonce,
bytes32 requesthash
);
pragma solidity ^0.8.0;
import {XAppConnectionClient} from './optics/xapp-contracts/XAppConnectionClient.sol';
import {Router} from './optics/xapp-contracts/Router.sol';
constructor(address _xAppConnectionManager) {
__XAppConnectionClient_initialize(_xAppConnectionManager);
uint256 chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256(
'EIP712Domain(string name,string version,uint256 chainId)'
),
'ToucanCrosschainMessenger',
VERSION,
chainId
)
);
}
constructor(address _xAppConnectionManager) {
__XAppConnectionClient_initialize(_xAppConnectionManager);
uint256 chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256(
'EIP712Domain(string name,string version,uint256 chainId)'
),
'ToucanCrosschainMessenger',
VERSION,
chainId
)
);
}
function addTokenPair(
address _homeToken,
address _remoteToken,
uint32 _domain
) external onlyOwner {
require(_homeToken != address(0), 'Tokens cannot be zero address');
remoteTokens[_homeToken][_domain] = _remoteToken;
}
function handle(
uint32 _origin,
bytes32 _sender,
bytes calldata _message
) external override onlyReplica onlyRemoteRouter(_origin, _sender) {
(
address receiver,
address token,
uint256 amount,
uint32 toDomain,
bytes32 requestHash
) = abi.decode(_message, (address, address, uint256, uint32, bytes32));
require(
requests[requestHash].requestType ==
BridgeRequestType.NOT_REGISTERED,
'Bridge Request Executed'
);
requests[requestHash] = BridgeRequest(
false,
BridgeRequestType.RECEIVED
);
TestToken(token).mint(receiver, amount);
emit BridgeRequestReceived(
_origin,
toDomain,
receiver,
token,
amount,
requestHash
);
}
function mintTokens(address _token) external {
TestToken(_token).mint(msg.sender, 100_000_000);
}
function sendMessage(
uint32 _destinationDomain,
address _token,
uint256 _amount
) external {
require(
remoteTokens[_token][_destinationDomain] != address(0),
'not mapped to remote token'
);
bytes32 _remoteRouterAddress = _mustHaveRemote(_destinationDomain);
uint256 currentNonce = nonce[msg.sender];
unchecked {
++currentNonce;
}
nonce[msg.sender] = currentNonce;
bytes32 requestHash = _generateRequestHash(
msg.sender,
_token,
_amount,
_destinationDomain,
currentNonce
);
requests[requestHash] = BridgeRequest(false, BridgeRequestType.SENT);
bytes memory _outboundMessage = abi.encode(
msg.sender,
remoteToken,
_amount,
_destinationDomain,
requestHash
);
_destinationDomain,
_remoteRouterAddress,
_outboundMessage
);
TestToken(_token).burn(msg.sender, _amount);
emit BridgeRequestSent(
_localDomain(),
_destinationDomain,
msg.sender,
_token,
_amount,
currentNonce,
requestHash
);
}
function sendMessage(
uint32 _destinationDomain,
address _token,
uint256 _amount
) external {
require(
remoteTokens[_token][_destinationDomain] != address(0),
'not mapped to remote token'
);
bytes32 _remoteRouterAddress = _mustHaveRemote(_destinationDomain);
uint256 currentNonce = nonce[msg.sender];
unchecked {
++currentNonce;
}
nonce[msg.sender] = currentNonce;
bytes32 requestHash = _generateRequestHash(
msg.sender,
_token,
_amount,
_destinationDomain,
currentNonce
);
requests[requestHash] = BridgeRequest(false, BridgeRequestType.SENT);
bytes memory _outboundMessage = abi.encode(
msg.sender,
remoteToken,
_amount,
_destinationDomain,
requestHash
);
_destinationDomain,
_remoteRouterAddress,
_outboundMessage
);
TestToken(_token).burn(msg.sender, _amount);
emit BridgeRequestSent(
_localDomain(),
_destinationDomain,
msg.sender,
_token,
_amount,
currentNonce,
requestHash
);
}
address remoteToken = remoteTokens[_token][_destinationDomain];
_home().dispatch(
function _generateRequestHash(
address _receiver,
address _token,
uint256 _amount,
uint32 _destinationDomain,
uint256 _nonce
) internal view returns (bytes32 _requestHash) {
return
keccak256(
abi.encodePacked(
DOMAIN_SEPARATOR,
_receiver,
_token,
_amount,
_destinationDomain,
_nonce
)
);
}
}
| 13,267,834 | [
1,
14468,
5245,
422,
1432,
631,
422,
1432,
631,
9043,
422,
1432,
631,
422,
1432,
631,
11417,
422,
1432,
631,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
399,
1395,
4169,
13941,
5639,
29329,
353,
399,
1395,
4169,
13941,
5639,
29329,
3245,
16,
9703,
288,
203,
203,
565,
533,
1071,
5381,
8456,
273,
296,
20,
18,
21,
18,
20,
13506,
203,
565,
1731,
1578,
1071,
11732,
27025,
67,
4550,
31,
203,
203,
203,
565,
871,
24219,
691,
8872,
12,
203,
3639,
2254,
1578,
8808,
4026,
3748,
16,
203,
3639,
2254,
1578,
358,
3748,
16,
203,
3639,
1758,
8808,
324,
1691,
693,
16,
203,
3639,
1758,
8808,
1147,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
1731,
1578,
590,
2816,
203,
565,
11272,
203,
565,
871,
24219,
691,
7828,
12,
203,
3639,
2254,
1578,
4026,
3748,
16,
203,
3639,
2254,
1578,
8808,
358,
3748,
16,
203,
3639,
1758,
8808,
324,
1691,
693,
16,
203,
3639,
1758,
8808,
1147,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
2254,
5034,
7448,
16,
203,
3639,
1731,
1578,
590,
2816,
203,
565,
11272,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
5666,
288,
60,
3371,
1952,
1227,
97,
628,
12871,
3838,
2102,
19,
92,
2910,
17,
16351,
87,
19,
60,
3371,
1952,
1227,
18,
18281,
13506,
203,
5666,
288,
8259,
97,
628,
12871,
3838,
2102,
19,
92,
2910,
17,
16351,
87,
19,
8259,
18,
18281,
13506,
203,
565,
3885,
12,
2867,
389,
92,
3371,
1952,
1318,
13,
288,
203,
3639,
1001,
60,
3371,
1952,
1227,
67,
11160,
24899,
92,
3371,
1952,
1318,
1769,
203,
203,
3639,
2254,
5034,
2687,
548,
31,
203,
3639,
19931,
288,
203,
5411,
2
] |
./full_match/3/0x59546491a51Da50F2A4F0AbA7921Ad59b7Fb8024/sources/contracts/BuyCoin.sol | hold all the winning transactions | WinningCoinDetails[] private winningTransactions;
| 14,241,366 | [
1,
21056,
777,
326,
5657,
2093,
8938,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
21628,
2093,
27055,
3790,
8526,
3238,
5657,
2093,
14186,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.5.17;
interface IERC20 {
function TOTALSUPPLY419() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF996(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER376(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE696(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE263(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM581(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER351(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL946(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD509(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB882(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB882(a, b, "SafeMath: subtraction overflow");
}
function SUB882(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL339(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV809(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV809(a, b, "SafeMath: division by zero");
}
function DIV809(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD891(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD891(a, b, "SafeMath: modulo by zero");
}
function MOD891(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT313(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function TOPAYABLE45(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE473(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER885(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.TRANSFER376.selector, to, value));
}
function SAFETRANSFERFROM553(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.TRANSFERFROM581.selector, from, to, value));
}
function SAFEAPPROVE341(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.ALLOWANCE696(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.APPROVE263.selector, spender, value));
}
function SAFEINCREASEALLOWANCE60(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE696(address(this), spender).ADD509(value);
CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.APPROVE263.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE623(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE696(address(this), spender).SUB882(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.APPROVE263.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN246(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).ISCONTRACT313(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
//
interface IController {
function WITHDRAW936(address, uint256) external; //inject NONSTANDARD NAMING
function BALANCEOF996(address) external view returns (uint256); //inject NONSTANDARD NAMING
function EARN112(address, uint256) external; //inject NONSTANDARD NAMING
function WANT318(address) external view returns (address); //inject NONSTANDARD NAMING
function REWARDS351() external view returns (address); //inject NONSTANDARD NAMING
function VAULTS378(address) external view returns (address); //inject NONSTANDARD NAMING
function STRATEGIES650(address) external view returns (address); //inject NONSTANDARD NAMING
}
//
interface Gauge {
function DEPOSIT828(uint256) external; //inject NONSTANDARD NAMING
function BALANCEOF996(address) external view returns (uint256); //inject NONSTANDARD NAMING
function WITHDRAW936(uint256) external; //inject NONSTANDARD NAMING
}
//
interface Mintr {
function MINT422(address) external; //inject NONSTANDARD NAMING
}
//
interface Uni {
function SWAPEXACTTOKENSFORTOKENS240( //inject NONSTANDARD NAMING
uint256,
uint256,
address[] calldata,
address,
uint256
) external;
}
//
interface ICurveFi {
function GET_VIRTUAL_PRICE800() external view returns (uint256); //inject NONSTANDARD NAMING
function ADD_LIQUIDITY808( //inject NONSTANDARD NAMING
// sBTC pool
uint256[3] calldata amounts,
uint256 min_mint_amount
) external;
function ADD_LIQUIDITY808( //inject NONSTANDARD NAMING
// bUSD pool
uint256[4] calldata amounts,
uint256 min_mint_amount
) external;
function REMOVE_LIQUIDITY_IMBALANCE228(uint256[4] calldata amounts, uint256 max_burn_amount) external; //inject NONSTANDARD NAMING
function REMOVE_LIQUIDITY138(uint256 _amount, uint256[4] calldata amounts) external; //inject NONSTANDARD NAMING
function EXCHANGE730( //inject NONSTANDARD NAMING
int128 from,
int128 to,
uint256 _from_amount,
uint256 _min_to_amount
) external;
}
interface Zap {
function REMOVE_LIQUIDITY_ONE_COIN571( //inject NONSTANDARD NAMING
uint256,
int128,
uint256
) external;
}
//
// NOTE: Basically an alias for Vaults
interface yERC20 {
function DEPOSIT828(uint256 _amount) external; //inject NONSTANDARD NAMING
function WITHDRAW936(uint256 _amount) external; //inject NONSTANDARD NAMING
function GETPRICEPERFULLSHARE410() external view returns (uint256); //inject NONSTANDARD NAMING
}
//
interface VoterProxy {
function WITHDRAW936( //inject NONSTANDARD NAMING
address _gauge,
address _token,
uint256 _amount
) external returns (uint256);
function BALANCEOF996(address _gauge) external view returns (uint256); //inject NONSTANDARD NAMING
function WITHDRAWALL4(address _gauge, address _token) external returns (uint256); //inject NONSTANDARD NAMING
function DEPOSIT828(address _gauge, address _token) external; //inject NONSTANDARD NAMING
function HARVEST862(address _gauge) external; //inject NONSTANDARD NAMING
function LOCK494() external; //inject NONSTANDARD NAMING
}
//
contract StrategyCurveBUSDVoterProxy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant want963 = address(0x3B3Ac5386837Dc563660FB6a0937DFAa5924333B); //inject NONSTANDARD NAMING
address public constant crv787 = address(0xD533a949740bb3306d119CC777fa900bA034cd52); //inject NONSTANDARD NAMING
address public constant uni793 = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //inject NONSTANDARD NAMING
address public constant weth737 = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //inject NONSTANDARD NAMING
address public constant dai668 = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); //inject NONSTANDARD NAMING
address public constant ydai985 = address(0xa3Aa4a71dBb17EBF2108A75b0BB7eFd9955463EF);//itoken //inject NONSTANDARD NAMING
address public constant curve489 = address(0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27); //inject NONSTANDARD NAMING
address public constant gauge170 = address(0x69Fb7c45726cfE2baDeE8317005d3F94bE838840); //inject NONSTANDARD NAMING
address public constant voter494 = address(0x07443C1cdb3653746727D595D2c1e5B438e0535A);//CurveYCRVVoter //inject NONSTANDARD NAMING
uint256 public keepCRV = 1000;
uint256 public constant keepcrvmax536 = 10000; //inject NONSTANDARD NAMING
uint256 public performanceFee = 3000;
uint256 public constant performancemax55 = 10000; //inject NONSTANDARD NAMING
uint256 public withdrawalFee = 50;
uint256 public constant withdrawalmax744 = 10000; //inject NONSTANDARD NAMING
address public proxy;
address public governance;
address public controller;
address public strategist;
constructor(address _controller) public {
governance = msg.sender;
strategist = msg.sender;
controller = _controller;
}
function GETNAME315() external pure returns (string memory) { //inject NONSTANDARD NAMING
return "StrategyCurveBUSDVoterProxy";
}
function SETSTRATEGIST730(address _strategist) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
strategist = _strategist;
}
function SETKEEPCRV658(uint256 _keepCRV) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
keepCRV = _keepCRV;
}
function SETWITHDRAWALFEE696(uint256 _withdrawalFee) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
withdrawalFee = _withdrawalFee;
}
function SETPERFORMANCEFEE960(uint256 _performanceFee) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
performanceFee = _performanceFee;
}
function SETPROXY105(address _proxy) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
proxy = _proxy;
}
function DEPOSIT828() public { //inject NONSTANDARD NAMING
uint256 _want = IERC20(want963).BALANCEOF996(address(this));
if (_want > 0) {
IERC20(want963).SAFETRANSFER885(proxy, _want);
VoterProxy(proxy).DEPOSIT828(gauge170, want963);
}
}
// Controller only function for creating additional rewards from dust
function WITHDRAW936(IERC20 _asset) external returns (uint256 balance) { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
require(want963 != address(_asset), "want");
require(crv787 != address(_asset), "crv");
require(ydai985 != address(_asset), "ydai");
require(dai668 != address(_asset), "dai");
balance = _asset.BALANCEOF996(address(this));
_asset.SAFETRANSFER885(controller, balance);
}
// Withdraw partial funds, normally used with a vault withdrawal
function WITHDRAW936(uint256 _amount) external { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
uint256 _balance = IERC20(want963).BALANCEOF996(address(this));
if (_balance < _amount) {
_amount = _WITHDRAWSOME256(_amount.SUB882(_balance));
_amount = _amount.ADD509(_balance);
}
uint256 _fee = _amount.MUL339(withdrawalFee).DIV809(withdrawalmax744);
IERC20(want963).SAFETRANSFER885(IController(controller).REWARDS351(), _fee);
address _vault = IController(controller).VAULTS378(address(want963));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want963).SAFETRANSFER885(_vault, _amount.SUB882(_fee));
}
// Withdraw all funds, normally used when migrating strategies
function WITHDRAWALL4() external returns (uint256 balance) { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
_WITHDRAWALL830();
balance = IERC20(want963).BALANCEOF996(address(this));
address _vault = IController(controller).VAULTS378(address(want963));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want963).SAFETRANSFER885(_vault, balance);
}
function _WITHDRAWALL830() internal { //inject NONSTANDARD NAMING
VoterProxy(proxy).WITHDRAWALL4(gauge170, want963);
}
function HARVEST862() public { //inject NONSTANDARD NAMING
require(msg.sender == strategist || msg.sender == governance, "!authorized");
VoterProxy(proxy).HARVEST862(gauge170);
uint256 _crv = IERC20(crv787).BALANCEOF996(address(this));
if (_crv > 0) {
uint256 _keepCRV = _crv.MUL339(keepCRV).DIV809(keepcrvmax536);
IERC20(crv787).SAFETRANSFER885(voter494, _keepCRV);
_crv = _crv.SUB882(_keepCRV);
IERC20(crv787).SAFEAPPROVE341(uni793, 0);
IERC20(crv787).SAFEAPPROVE341(uni793, _crv);
address[] memory path = new address[](3);
path[0] = crv787;
path[1] = weth737;
path[2] = dai668;
Uni(uni793).SWAPEXACTTOKENSFORTOKENS240(_crv, uint256(0), path, address(this), now.ADD509(1800));
}
uint256 _dai = IERC20(dai668).BALANCEOF996(address(this));
if (_dai > 0) {
IERC20(dai668).SAFEAPPROVE341(ydai985, 0);
IERC20(dai668).SAFEAPPROVE341(ydai985, _dai);
yERC20(ydai985).DEPOSIT828(_dai);
}
uint256 _ydai = IERC20(ydai985).BALANCEOF996(address(this));
if (_ydai > 0) {
IERC20(ydai985).SAFEAPPROVE341(curve489, 0);
IERC20(ydai985).SAFEAPPROVE341(curve489, _ydai);
ICurveFi(curve489).ADD_LIQUIDITY808([_ydai, 0, 0, 0], 0);
}
uint256 _want = IERC20(want963).BALANCEOF996(address(this));
if (_want > 0) {
uint256 _fee = _want.MUL339(performanceFee).DIV809(performancemax55);
IERC20(want963).SAFETRANSFER885(IController(controller).REWARDS351(), _fee);
DEPOSIT828();
}
VoterProxy(proxy).LOCK494();
}
function _WITHDRAWSOME256(uint256 _amount) internal returns (uint256) { //inject NONSTANDARD NAMING
return VoterProxy(proxy).WITHDRAW936(gauge170, want963, _amount);
}
function BALANCEOFWANT761() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(want963).BALANCEOF996(address(this));
}
function BALANCEOFPOOL660() public view returns (uint256) { //inject NONSTANDARD NAMING
return VoterProxy(proxy).BALANCEOF996(gauge170);
}
function BALANCEOF996() public view returns (uint256) { //inject NONSTANDARD NAMING
return BALANCEOFWANT761().ADD509(BALANCEOFPOOL660());
}
function SETGOVERNANCE812(address _governance) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
governance = _governance;
}
function SETCONTROLLER990(address _controller) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
controller = _controller;
}
} | inject NONSTANDARD NAMING
| function TOPAYABLE45(address account) internal pure returns (address payable) { | 12,870,903 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
18680,
5255,
2782,
7950,
12,
2867,
2236,
13,
2713,
16618,
1135,
261,
2867,
8843,
429,
13,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/8453/0x2f3551110c0e58dC0e85a4Fb81B659B598783BD8/sources/CBSwapToken.sol | Anti-bot and anti-whale mappings and variables exlcude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount | contract CBSwapToken is ERC20, Ownable {
uint256 public maxBuyAmount;
uint256 public maxSellAmount;
uint256 public maxWalletAmount;
IDexRouter public cbswapV2Router;
address public cbswapV2Pair;
bool private swapping;
uint256 public swapTokensAtAmount;
address public sustainabilityAddress;
address public treasuryAddress;
address public liquidityAddress;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buySustainabilityFee;
uint256 public buyLiquidityFee;
uint256 public buyTreasuryFee;
uint256 public sellTotalFees;
uint256 public sellSustainabilityFee;
uint256 public sellLiquidityFee;
uint256 public sellTreasuryFee;
uint256 public tokensForSustainability;
uint256 public tokensForLiquidity;
uint256 public tokensForTreasury;
uint256 public lpWithdrawRequestTimestamp;
uint256 public lpWithdrawRequestDuration = 7 days;
bool public lpWithdrawRequestPending;
uint256 public lpPercToWithDraw;
mapping(address => bool) private _isExcludedFromFees;
mapping(address => bool) public _isExcludedMaxTransactionAmount;
mapping(address => bool) public automatedMarketMakerPairs;
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event EnabledTrading();
event RemovedLimits();
event ExcludeFromFees(address indexed account, bool isExcluded);
event UpdatedMaxBuyAmount(uint256 newAmount);
event UpdatedMaxSellAmount(uint256 newAmount);
event UpdatedMaxWalletAmount(uint256 newAmount);
event UpdatedSustainabilityAddress(address indexed newWallet);
event UpdatedTreasuryAddress(address indexed newWallet);
event UpdatedLiquidityAddress(address indexed newWallet);
event MaxTransactionExclusion(address _address, bool excluded);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event TransferForeignToken(address token, uint256 amount);
event RequestedLPWithdraw();
event WithdrewLPForMigration();
event CanceledLpWithdrawRequest();
constructor() ERC20("CBSWAP.IO", "COINS") {
uint256 totalSupply = 1 * 1e9 * 1e18;
maxBuyAmount = (totalSupply * 10) / 1000;
maxSellAmount = (totalSupply * 10) / 1000;
maxWalletAmount = (totalSupply * 10) / 1000;
buySustainabilityFee = 500;
buyLiquidityFee = 0;
buyTreasuryFee = 0;
buyTotalFees = buySustainabilityFee + buyLiquidityFee + buyTreasuryFee;
sellSustainabilityFee = 500;
sellLiquidityFee = 0;
sellTreasuryFee = 0;
sellTotalFees =
sellSustainabilityFee +
sellLiquidityFee +
sellTreasuryFee;
_excludeFromMaxTransaction(newOwner, true);
_excludeFromMaxTransaction(address(this), true);
_excludeFromMaxTransaction(address(0xdead), true);
excludeFromFees(newOwner, true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
sustainabilityAddress = address(newOwner);
treasuryAddress = address(newOwner);
liquidityAddress = address(newOwner);
_createInitialSupply(newOwner, totalSupply);
transferOwnership(newOwner);
}
receive() external payable {}
function enableTrading(address _router) external onlyOwner {
require(!tradingActive, "Cannot reenable trading");
cbswapV2Router = IDexRouter(_router);
_excludeFromMaxTransaction(address(cbswapV2Router), true);
cbswapV2Pair = IDexFactory(cbswapV2Router.factory()).createPair(
address(this),
cbswapV2Router.WETH()
);
_setAutomatedMarketMakerPair(address(cbswapV2Pair), true);
tradingActive = true;
swapEnabled = true;
tradingActiveBlock = block.number;
emit EnabledTrading();
}
function removeLimits() external onlyOwner {
limitsInEffect = false;
transferDelayEnabled = false;
emit RemovedLimits();
}
function disableTransferDelay() external onlyOwner {
transferDelayEnabled = false;
}
function updateMaxBuyAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 1) / 1000) / 1e18,
"Cannot set max buy amount lower than 0.1%"
);
maxBuyAmount = newNum * (10**18);
emit UpdatedMaxBuyAmount(maxBuyAmount);
}
function updateMaxSellAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 1) / 1000) / 1e18,
"Cannot set max sell amount lower than 0.1%"
);
maxSellAmount = newNum * (10**18);
emit UpdatedMaxSellAmount(maxSellAmount);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 5) / 1000) / 1e18,
"Cannot set max wallet amount lower than 0.5%"
);
maxWalletAmount = newNum * (10**18);
emit UpdatedMaxWalletAmount(maxWalletAmount);
}
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner {
require(
newAmount >= (totalSupply() * 1) / 100000,
"Swap amount cannot be lower than 0.001% total supply."
);
require(
newAmount <= (totalSupply() * 1) / 1000,
"Swap amount cannot be higher than 0.1% total supply."
);
swapTokensAtAmount = newAmount;
}
function _excludeFromMaxTransaction(address updAds, bool isExcluded)
private
{
_isExcludedMaxTransactionAmount[updAds] = isExcluded;
emit MaxTransactionExclusion(updAds, isExcluded);
}
function airdropToWallets(
address[] memory wallets,
uint256[] memory amountsInTokens
) external onlyOwner {
require(
wallets.length == amountsInTokens.length,
"arrays must be the same length"
);
require(
wallets.length < 200,
"Can only airdrop 200 wallets per txn due to gas limits"
for (uint256 i = 0; i < wallets.length; i++) {
address wallet = wallets[i];
uint256 amount = amountsInTokens[i] * 1e18;
_transfer(msg.sender, wallet, amount);
}
}
function airdropToWallets(
address[] memory wallets,
uint256[] memory amountsInTokens
) external onlyOwner {
require(
wallets.length == amountsInTokens.length,
"arrays must be the same length"
);
require(
wallets.length < 200,
"Can only airdrop 200 wallets per txn due to gas limits"
for (uint256 i = 0; i < wallets.length; i++) {
address wallet = wallets[i];
uint256 amount = amountsInTokens[i] * 1e18;
_transfer(msg.sender, wallet, amount);
}
}
function excludeFromMaxTransaction(address updAds, bool isEx)
external
onlyOwner
{
if (!isEx) {
require(
updAds != cbswapV2Pair,
"Cannot remove cbswap pair from max txn"
);
}
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
function excludeFromMaxTransaction(address updAds, bool isEx)
external
onlyOwner
{
if (!isEx) {
require(
updAds != cbswapV2Pair,
"Cannot remove cbswap pair from max txn"
);
}
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
function setAutomatedMarketMakerPair(address pair, bool value)
external
onlyOwner
{
require(
pair != cbswapV2Pair,
"The pair cannot be removed from automatedMarketMakerPairs"
);
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
_excludeFromMaxTransaction(pair, value);
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateBuyFees(
uint256 _sustainabilityFee,
uint256 _liquidityFee,
uint256 _treasuryFee
) external onlyOwner {
buySustainabilityFee = _sustainabilityFee;
buyLiquidityFee = _liquidityFee;
buyTreasuryFee = _treasuryFee;
buyTotalFees = buySustainabilityFee + buyLiquidityFee + buyTreasuryFee;
require(buyTotalFees <= 1000, "Must keep fees at 10% or less");
}
function updateSellFees(
uint256 _sustainabilityFee,
uint256 _liquidityFee,
uint256 _treasuryFee
) external onlyOwner {
sellSustainabilityFee = _sustainabilityFee;
sellLiquidityFee = _liquidityFee;
sellTreasuryFee = _treasuryFee;
sellTotalFees =
sellSustainabilityFee +
sellLiquidityFee +
sellTreasuryFee;
require(sellTotalFees <= 1000, "Must keep fees at 10% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead)
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != address(cbswapV2Router) &&
to != address(cbswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number - 4 &&
_holderLastTransferTimestamp[to] <
block.number - 4,
"_transfer:: Transfer Delay enabled. Try again later."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxBuyAmount,
"Buy transfer amount exceeds the max buy."
);
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxSellAmount,
"Sell transfer amount exceeds the max sell."
);
} else if (
!_isExcludedMaxTransactionAmount[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
uint256 penaltyAmount = 0;
if (takeFee) {
if (
tradingActiveBlock >= block.number + 1 &&
automatedMarketMakerPairs[from]
) {
penaltyAmount = (amount * 99) / 100;
super._transfer(from, sustainabilityAddress, penaltyAmount);
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = (amount * sellTotalFees) / 10000;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForSustainability +=
(fees * sellSustainabilityFee) /
sellTotalFees;
tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = (amount * buyTotalFees) / 10000;
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForSustainability +=
(fees * buySustainabilityFee) /
buyTotalFees;
tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees + penaltyAmount;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead)
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != address(cbswapV2Router) &&
to != address(cbswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number - 4 &&
_holderLastTransferTimestamp[to] <
block.number - 4,
"_transfer:: Transfer Delay enabled. Try again later."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxBuyAmount,
"Buy transfer amount exceeds the max buy."
);
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxSellAmount,
"Sell transfer amount exceeds the max sell."
);
} else if (
!_isExcludedMaxTransactionAmount[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
uint256 penaltyAmount = 0;
if (takeFee) {
if (
tradingActiveBlock >= block.number + 1 &&
automatedMarketMakerPairs[from]
) {
penaltyAmount = (amount * 99) / 100;
super._transfer(from, sustainabilityAddress, penaltyAmount);
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = (amount * sellTotalFees) / 10000;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForSustainability +=
(fees * sellSustainabilityFee) /
sellTotalFees;
tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = (amount * buyTotalFees) / 10000;
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForSustainability +=
(fees * buySustainabilityFee) /
buyTotalFees;
tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees + penaltyAmount;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead)
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != address(cbswapV2Router) &&
to != address(cbswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number - 4 &&
_holderLastTransferTimestamp[to] <
block.number - 4,
"_transfer:: Transfer Delay enabled. Try again later."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxBuyAmount,
"Buy transfer amount exceeds the max buy."
);
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxSellAmount,
"Sell transfer amount exceeds the max sell."
);
} else if (
!_isExcludedMaxTransactionAmount[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
uint256 penaltyAmount = 0;
if (takeFee) {
if (
tradingActiveBlock >= block.number + 1 &&
automatedMarketMakerPairs[from]
) {
penaltyAmount = (amount * 99) / 100;
super._transfer(from, sustainabilityAddress, penaltyAmount);
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = (amount * sellTotalFees) / 10000;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForSustainability +=
(fees * sellSustainabilityFee) /
sellTotalFees;
tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = (amount * buyTotalFees) / 10000;
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForSustainability +=
(fees * buySustainabilityFee) /
buyTotalFees;
tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees + penaltyAmount;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead)
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != address(cbswapV2Router) &&
to != address(cbswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number - 4 &&
_holderLastTransferTimestamp[to] <
block.number - 4,
"_transfer:: Transfer Delay enabled. Try again later."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxBuyAmount,
"Buy transfer amount exceeds the max buy."
);
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxSellAmount,
"Sell transfer amount exceeds the max sell."
);
} else if (
!_isExcludedMaxTransactionAmount[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
uint256 penaltyAmount = 0;
if (takeFee) {
if (
tradingActiveBlock >= block.number + 1 &&
automatedMarketMakerPairs[from]
) {
penaltyAmount = (amount * 99) / 100;
super._transfer(from, sustainabilityAddress, penaltyAmount);
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = (amount * sellTotalFees) / 10000;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForSustainability +=
(fees * sellSustainabilityFee) /
sellTotalFees;
tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = (amount * buyTotalFees) / 10000;
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForSustainability +=
(fees * buySustainabilityFee) /
buyTotalFees;
tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees + penaltyAmount;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead)
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != address(cbswapV2Router) &&
to != address(cbswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number - 4 &&
_holderLastTransferTimestamp[to] <
block.number - 4,
"_transfer:: Transfer Delay enabled. Try again later."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxBuyAmount,
"Buy transfer amount exceeds the max buy."
);
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxSellAmount,
"Sell transfer amount exceeds the max sell."
);
} else if (
!_isExcludedMaxTransactionAmount[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
uint256 penaltyAmount = 0;
if (takeFee) {
if (
tradingActiveBlock >= block.number + 1 &&
automatedMarketMakerPairs[from]
) {
penaltyAmount = (amount * 99) / 100;
super._transfer(from, sustainabilityAddress, penaltyAmount);
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = (amount * sellTotalFees) / 10000;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForSustainability +=
(fees * sellSustainabilityFee) /
sellTotalFees;
tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = (amount * buyTotalFees) / 10000;
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForSustainability +=
(fees * buySustainabilityFee) /
buyTotalFees;
tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees + penaltyAmount;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead)
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != address(cbswapV2Router) &&
to != address(cbswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number - 4 &&
_holderLastTransferTimestamp[to] <
block.number - 4,
"_transfer:: Transfer Delay enabled. Try again later."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxBuyAmount,
"Buy transfer amount exceeds the max buy."
);
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxSellAmount,
"Sell transfer amount exceeds the max sell."
);
} else if (
!_isExcludedMaxTransactionAmount[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
uint256 penaltyAmount = 0;
if (takeFee) {
if (
tradingActiveBlock >= block.number + 1 &&
automatedMarketMakerPairs[from]
) {
penaltyAmount = (amount * 99) / 100;
super._transfer(from, sustainabilityAddress, penaltyAmount);
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = (amount * sellTotalFees) / 10000;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForSustainability +=
(fees * sellSustainabilityFee) /
sellTotalFees;
tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = (amount * buyTotalFees) / 10000;
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForSustainability +=
(fees * buySustainabilityFee) /
buyTotalFees;
tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees + penaltyAmount;
}
super._transfer(from, to, amount);
}
if (
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead)
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != address(cbswapV2Router) &&
to != address(cbswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number - 4 &&
_holderLastTransferTimestamp[to] <
block.number - 4,
"_transfer:: Transfer Delay enabled. Try again later."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxBuyAmount,
"Buy transfer amount exceeds the max buy."
);
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxSellAmount,
"Sell transfer amount exceeds the max sell."
);
} else if (
!_isExcludedMaxTransactionAmount[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
uint256 penaltyAmount = 0;
if (takeFee) {
if (
tradingActiveBlock >= block.number + 1 &&
automatedMarketMakerPairs[from]
) {
penaltyAmount = (amount * 99) / 100;
super._transfer(from, sustainabilityAddress, penaltyAmount);
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = (amount * sellTotalFees) / 10000;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForSustainability +=
(fees * sellSustainabilityFee) /
sellTotalFees;
tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = (amount * buyTotalFees) / 10000;
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForSustainability +=
(fees * buySustainabilityFee) /
buyTotalFees;
tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees + penaltyAmount;
}
super._transfer(from, to, amount);
}
else if (
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead)
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != address(cbswapV2Router) &&
to != address(cbswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number - 4 &&
_holderLastTransferTimestamp[to] <
block.number - 4,
"_transfer:: Transfer Delay enabled. Try again later."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxBuyAmount,
"Buy transfer amount exceeds the max buy."
);
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxSellAmount,
"Sell transfer amount exceeds the max sell."
);
} else if (
!_isExcludedMaxTransactionAmount[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
uint256 penaltyAmount = 0;
if (takeFee) {
if (
tradingActiveBlock >= block.number + 1 &&
automatedMarketMakerPairs[from]
) {
penaltyAmount = (amount * 99) / 100;
super._transfer(from, sustainabilityAddress, penaltyAmount);
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = (amount * sellTotalFees) / 10000;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForSustainability +=
(fees * sellSustainabilityFee) /
sellTotalFees;
tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = (amount * buyTotalFees) / 10000;
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForSustainability +=
(fees * buySustainabilityFee) /
buyTotalFees;
tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees + penaltyAmount;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead)
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != address(cbswapV2Router) &&
to != address(cbswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number - 4 &&
_holderLastTransferTimestamp[to] <
block.number - 4,
"_transfer:: Transfer Delay enabled. Try again later."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxBuyAmount,
"Buy transfer amount exceeds the max buy."
);
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxSellAmount,
"Sell transfer amount exceeds the max sell."
);
} else if (
!_isExcludedMaxTransactionAmount[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
uint256 penaltyAmount = 0;
if (takeFee) {
if (
tradingActiveBlock >= block.number + 1 &&
automatedMarketMakerPairs[from]
) {
penaltyAmount = (amount * 99) / 100;
super._transfer(from, sustainabilityAddress, penaltyAmount);
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = (amount * sellTotalFees) / 10000;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForSustainability +=
(fees * sellSustainabilityFee) /
sellTotalFees;
tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = (amount * buyTotalFees) / 10000;
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForSustainability +=
(fees * buySustainabilityFee) /
buyTotalFees;
tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees + penaltyAmount;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead)
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != address(cbswapV2Router) &&
to != address(cbswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number - 4 &&
_holderLastTransferTimestamp[to] <
block.number - 4,
"_transfer:: Transfer Delay enabled. Try again later."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxBuyAmount,
"Buy transfer amount exceeds the max buy."
);
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxSellAmount,
"Sell transfer amount exceeds the max sell."
);
} else if (
!_isExcludedMaxTransactionAmount[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
uint256 penaltyAmount = 0;
if (takeFee) {
if (
tradingActiveBlock >= block.number + 1 &&
automatedMarketMakerPairs[from]
) {
penaltyAmount = (amount * 99) / 100;
super._transfer(from, sustainabilityAddress, penaltyAmount);
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = (amount * sellTotalFees) / 10000;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForSustainability +=
(fees * sellSustainabilityFee) /
sellTotalFees;
tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = (amount * buyTotalFees) / 10000;
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForSustainability +=
(fees * buySustainabilityFee) /
buyTotalFees;
tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees + penaltyAmount;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead)
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != address(cbswapV2Router) &&
to != address(cbswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number - 4 &&
_holderLastTransferTimestamp[to] <
block.number - 4,
"_transfer:: Transfer Delay enabled. Try again later."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxBuyAmount,
"Buy transfer amount exceeds the max buy."
);
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxSellAmount,
"Sell transfer amount exceeds the max sell."
);
} else if (
!_isExcludedMaxTransactionAmount[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
uint256 penaltyAmount = 0;
if (takeFee) {
if (
tradingActiveBlock >= block.number + 1 &&
automatedMarketMakerPairs[from]
) {
penaltyAmount = (amount * 99) / 100;
super._transfer(from, sustainabilityAddress, penaltyAmount);
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = (amount * sellTotalFees) / 10000;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForSustainability +=
(fees * sellSustainabilityFee) /
sellTotalFees;
tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = (amount * buyTotalFees) / 10000;
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForSustainability +=
(fees * buySustainabilityFee) /
buyTotalFees;
tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees + penaltyAmount;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead)
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != address(cbswapV2Router) &&
to != address(cbswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number - 4 &&
_holderLastTransferTimestamp[to] <
block.number - 4,
"_transfer:: Transfer Delay enabled. Try again later."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxBuyAmount,
"Buy transfer amount exceeds the max buy."
);
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxSellAmount,
"Sell transfer amount exceeds the max sell."
);
} else if (
!_isExcludedMaxTransactionAmount[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
uint256 penaltyAmount = 0;
if (takeFee) {
if (
tradingActiveBlock >= block.number + 1 &&
automatedMarketMakerPairs[from]
) {
penaltyAmount = (amount * 99) / 100;
super._transfer(from, sustainabilityAddress, penaltyAmount);
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = (amount * sellTotalFees) / 10000;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForSustainability +=
(fees * sellSustainabilityFee) /
sellTotalFees;
tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = (amount * buyTotalFees) / 10000;
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForSustainability +=
(fees * buySustainabilityFee) /
buyTotalFees;
tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees + penaltyAmount;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead)
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != address(cbswapV2Router) &&
to != address(cbswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number - 4 &&
_holderLastTransferTimestamp[to] <
block.number - 4,
"_transfer:: Transfer Delay enabled. Try again later."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxBuyAmount,
"Buy transfer amount exceeds the max buy."
);
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxSellAmount,
"Sell transfer amount exceeds the max sell."
);
} else if (
!_isExcludedMaxTransactionAmount[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
uint256 penaltyAmount = 0;
if (takeFee) {
if (
tradingActiveBlock >= block.number + 1 &&
automatedMarketMakerPairs[from]
) {
penaltyAmount = (amount * 99) / 100;
super._transfer(from, sustainabilityAddress, penaltyAmount);
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = (amount * sellTotalFees) / 10000;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForSustainability +=
(fees * sellSustainabilityFee) /
sellTotalFees;
tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = (amount * buyTotalFees) / 10000;
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForSustainability +=
(fees * buySustainabilityFee) /
buyTotalFees;
tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees + penaltyAmount;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead)
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != address(cbswapV2Router) &&
to != address(cbswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number - 4 &&
_holderLastTransferTimestamp[to] <
block.number - 4,
"_transfer:: Transfer Delay enabled. Try again later."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxBuyAmount,
"Buy transfer amount exceeds the max buy."
);
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxSellAmount,
"Sell transfer amount exceeds the max sell."
);
} else if (
!_isExcludedMaxTransactionAmount[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
uint256 penaltyAmount = 0;
if (takeFee) {
if (
tradingActiveBlock >= block.number + 1 &&
automatedMarketMakerPairs[from]
) {
penaltyAmount = (amount * 99) / 100;
super._transfer(from, sustainabilityAddress, penaltyAmount);
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = (amount * sellTotalFees) / 10000;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForSustainability +=
(fees * sellSustainabilityFee) /
sellTotalFees;
tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = (amount * buyTotalFees) / 10000;
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForSustainability +=
(fees * buySustainabilityFee) /
buyTotalFees;
tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees + penaltyAmount;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead)
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != address(cbswapV2Router) &&
to != address(cbswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number - 4 &&
_holderLastTransferTimestamp[to] <
block.number - 4,
"_transfer:: Transfer Delay enabled. Try again later."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxBuyAmount,
"Buy transfer amount exceeds the max buy."
);
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxSellAmount,
"Sell transfer amount exceeds the max sell."
);
} else if (
!_isExcludedMaxTransactionAmount[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
uint256 penaltyAmount = 0;
if (takeFee) {
if (
tradingActiveBlock >= block.number + 1 &&
automatedMarketMakerPairs[from]
) {
penaltyAmount = (amount * 99) / 100;
super._transfer(from, sustainabilityAddress, penaltyAmount);
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = (amount * sellTotalFees) / 10000;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForSustainability +=
(fees * sellSustainabilityFee) /
sellTotalFees;
tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = (amount * buyTotalFees) / 10000;
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForSustainability +=
(fees * buySustainabilityFee) /
buyTotalFees;
tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees + penaltyAmount;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "amount must be greater than 0");
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead)
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != address(cbswapV2Router) &&
to != address(cbswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number - 4 &&
_holderLastTransferTimestamp[to] <
block.number - 4,
"_transfer:: Transfer Delay enabled. Try again later."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxBuyAmount,
"Buy transfer amount exceeds the max buy."
);
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxSellAmount,
"Sell transfer amount exceeds the max sell."
);
} else if (
!_isExcludedMaxTransactionAmount[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount + balanceOf(to) <= maxWalletAmount,
"Cannot Exceed max wallet"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = true;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
uint256 penaltyAmount = 0;
if (takeFee) {
if (
tradingActiveBlock >= block.number + 1 &&
automatedMarketMakerPairs[from]
) {
penaltyAmount = (amount * 99) / 100;
super._transfer(from, sustainabilityAddress, penaltyAmount);
}
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = (amount * sellTotalFees) / 10000;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForSustainability +=
(fees * sellSustainabilityFee) /
sellTotalFees;
tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = (amount * buyTotalFees) / 10000;
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForSustainability +=
(fees * buySustainabilityFee) /
buyTotalFees;
tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees + penaltyAmount;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = cbswapV2Router.WETH();
_approve(address(this), address(cbswapV2Router), tokenAmount);
cbswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(cbswapV2Router), tokenAmount);
address(this),
tokenAmount,
address(liquidityAddress),
block.timestamp
);
}
cbswapV2Router.addLiquidityETH{value: ethAmount}(
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForSustainability +
tokensForTreasury;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 10) {
contractBalance = swapTokensAtAmount * 10;
}
bool success;
totalTokensToSwap /
2;
swapTokensForEth(contractBalance - liquidityTokens);
uint256 ethBalance = address(this).balance;
uint256 ethForLiquidity = ethBalance;
uint256 ethForSustainability = (ethBalance * tokensForSustainability) /
(totalTokensToSwap - (tokensForLiquidity / 2));
uint256 ethForTreasury = (ethBalance * tokensForTreasury) /
(totalTokensToSwap - (tokensForLiquidity / 2));
ethForLiquidity -= ethForSustainability + ethForTreasury;
tokensForLiquidity = 0;
tokensForSustainability = 0;
tokensForTreasury = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
}
(success, ) = address(sustainabilityAddress).call{
value: address(this).balance
}("");
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForSustainability +
tokensForTreasury;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 10) {
contractBalance = swapTokensAtAmount * 10;
}
bool success;
totalTokensToSwap /
2;
swapTokensForEth(contractBalance - liquidityTokens);
uint256 ethBalance = address(this).balance;
uint256 ethForLiquidity = ethBalance;
uint256 ethForSustainability = (ethBalance * tokensForSustainability) /
(totalTokensToSwap - (tokensForLiquidity / 2));
uint256 ethForTreasury = (ethBalance * tokensForTreasury) /
(totalTokensToSwap - (tokensForLiquidity / 2));
ethForLiquidity -= ethForSustainability + ethForTreasury;
tokensForLiquidity = 0;
tokensForSustainability = 0;
tokensForTreasury = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
}
(success, ) = address(sustainabilityAddress).call{
value: address(this).balance
}("");
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForSustainability +
tokensForTreasury;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 10) {
contractBalance = swapTokensAtAmount * 10;
}
bool success;
totalTokensToSwap /
2;
swapTokensForEth(contractBalance - liquidityTokens);
uint256 ethBalance = address(this).balance;
uint256 ethForLiquidity = ethBalance;
uint256 ethForSustainability = (ethBalance * tokensForSustainability) /
(totalTokensToSwap - (tokensForLiquidity / 2));
uint256 ethForTreasury = (ethBalance * tokensForTreasury) /
(totalTokensToSwap - (tokensForLiquidity / 2));
ethForLiquidity -= ethForSustainability + ethForTreasury;
tokensForLiquidity = 0;
tokensForSustainability = 0;
tokensForTreasury = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
}
(success, ) = address(sustainabilityAddress).call{
value: address(this).balance
}("");
}
uint256 liquidityTokens = (contractBalance * tokensForLiquidity) /
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForSustainability +
tokensForTreasury;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 10) {
contractBalance = swapTokensAtAmount * 10;
}
bool success;
totalTokensToSwap /
2;
swapTokensForEth(contractBalance - liquidityTokens);
uint256 ethBalance = address(this).balance;
uint256 ethForLiquidity = ethBalance;
uint256 ethForSustainability = (ethBalance * tokensForSustainability) /
(totalTokensToSwap - (tokensForLiquidity / 2));
uint256 ethForTreasury = (ethBalance * tokensForTreasury) /
(totalTokensToSwap - (tokensForLiquidity / 2));
ethForLiquidity -= ethForSustainability + ethForTreasury;
tokensForLiquidity = 0;
tokensForSustainability = 0;
tokensForTreasury = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
}
(success, ) = address(sustainabilityAddress).call{
value: address(this).balance
}("");
}
(success, ) = address(treasuryAddress).call{value: ethForTreasury}("");
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForSustainability +
tokensForTreasury;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 10) {
contractBalance = swapTokensAtAmount * 10;
}
bool success;
totalTokensToSwap /
2;
swapTokensForEth(contractBalance - liquidityTokens);
uint256 ethBalance = address(this).balance;
uint256 ethForLiquidity = ethBalance;
uint256 ethForSustainability = (ethBalance * tokensForSustainability) /
(totalTokensToSwap - (tokensForLiquidity / 2));
uint256 ethForTreasury = (ethBalance * tokensForTreasury) /
(totalTokensToSwap - (tokensForLiquidity / 2));
ethForLiquidity -= ethForSustainability + ethForTreasury;
tokensForLiquidity = 0;
tokensForSustainability = 0;
tokensForTreasury = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
}
(success, ) = address(sustainabilityAddress).call{
value: address(this).balance
}("");
}
function transferForeignToken(address _token, address _to)
external
onlyOwner
returns (bool _sent)
{
require(_token != address(0), "_token address cannot be 0");
require(_token != address(this), "Can't withdraw native tokens");
uint256 _contractBalance = IERC20(_token).balanceOf(address(this));
_sent = IERC20(_token).transfer(_to, _contractBalance);
emit TransferForeignToken(_token, _contractBalance);
}
function withdrawStuckETH() external onlyOwner {
bool success;
""
);
}
(success, ) = address(msg.sender).call{value: address(this).balance}(
function setSustainabilityAddress(address _sustainabilityAddress)
external
onlyOwner
{
require(
_sustainabilityAddress != address(0),
"_sustainabilityAddress address cannot be 0"
);
sustainabilityAddress = payable(_sustainabilityAddress);
emit UpdatedSustainabilityAddress(_sustainabilityAddress);
}
function setTreasuryAddress(address _treasuryAddress) external onlyOwner {
require(
_treasuryAddress != address(0),
"_treasuryAddress address cannot be 0"
);
treasuryAddress = payable(_treasuryAddress);
emit UpdatedTreasuryAddress(_treasuryAddress);
}
function setLiquidityAddress(address _liquidityAddress) external onlyOwner {
require(_liquidityAddress != address(0), "address cannot be 0");
liquidityAddress = payable(_liquidityAddress);
emit UpdatedLiquidityAddress(_liquidityAddress);
}
function requestToWithdrawLP(uint256 percToWithdraw) external onlyOwner {
require(
!lpWithdrawRequestPending,
"Cannot request again until first request is over."
);
require(
percToWithdraw <= 100 && percToWithdraw > 0,
"Need to set between 1-100%"
);
lpWithdrawRequestTimestamp = block.timestamp;
lpWithdrawRequestPending = true;
lpPercToWithDraw = percToWithdraw;
emit RequestedLPWithdraw();
}
function nextAvailableLpWithdrawDate() public view returns (uint256) {
if (lpWithdrawRequestPending) {
return lpWithdrawRequestTimestamp + lpWithdrawRequestDuration;
}
}
function nextAvailableLpWithdrawDate() public view returns (uint256) {
if (lpWithdrawRequestPending) {
return lpWithdrawRequestTimestamp + lpWithdrawRequestDuration;
}
}
} else {
function withdrawRequestedLP() external onlyOwner {
require(
block.timestamp >= nextAvailableLpWithdrawDate() &&
nextAvailableLpWithdrawDate() > 0,
"Must request and wait."
);
lpWithdrawRequestTimestamp = 0;
lpWithdrawRequestPending = false;
uint256 amtToWithdraw = (IERC20(address(cbswapV2Pair)).balanceOf(
address(this)
) * lpPercToWithDraw) / 100;
lpPercToWithDraw = 0;
IERC20(cbswapV2Pair).transfer(msg.sender, amtToWithdraw);
}
function cancelLPWithdrawRequest() external onlyOwner {
lpWithdrawRequestPending = false;
lpPercToWithDraw = 0;
lpWithdrawRequestTimestamp = 0;
emit CanceledLpWithdrawRequest();
}
} | 16,739,360 | [
1,
14925,
77,
17,
4819,
471,
30959,
17,
3350,
5349,
7990,
471,
3152,
431,
17704,
1317,
628,
1656,
281,
471,
943,
2492,
3844,
1707,
6138,
716,
279,
5859,
13667,
312,
6388,
5574,
18,
5502,
7412,
358,
4259,
6138,
3377,
506,
3221,
358,
279,
4207,
7412,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
21262,
12521,
1345,
353,
4232,
39,
3462,
16,
14223,
6914,
288,
203,
565,
2254,
5034,
1071,
943,
38,
9835,
6275,
31,
203,
565,
2254,
5034,
1071,
943,
55,
1165,
6275,
31,
203,
565,
2254,
5034,
1071,
943,
16936,
6275,
31,
203,
203,
565,
1599,
338,
8259,
1071,
276,
2038,
91,
438,
58,
22,
8259,
31,
203,
565,
1758,
1071,
276,
2038,
91,
438,
58,
22,
4154,
31,
203,
203,
565,
1426,
3238,
7720,
1382,
31,
203,
565,
2254,
5034,
1071,
7720,
5157,
861,
6275,
31,
203,
203,
565,
1758,
1071,
272,
641,
530,
2967,
1887,
31,
203,
565,
1758,
1071,
9787,
345,
22498,
1887,
31,
203,
565,
1758,
1071,
4501,
372,
24237,
1887,
31,
203,
203,
203,
565,
1426,
1071,
8181,
382,
12477,
273,
638,
31,
203,
565,
1426,
1071,
1284,
7459,
3896,
273,
629,
31,
203,
565,
1426,
1071,
7720,
1526,
273,
629,
31,
203,
203,
565,
1426,
1071,
7412,
6763,
1526,
273,
638,
31,
203,
203,
565,
2254,
5034,
1071,
30143,
5269,
2954,
281,
31,
203,
565,
2254,
5034,
1071,
30143,
55,
641,
530,
2967,
14667,
31,
203,
565,
2254,
5034,
1071,
30143,
48,
18988,
24237,
14667,
31,
203,
565,
2254,
5034,
1071,
30143,
56,
266,
345,
22498,
14667,
31,
203,
203,
565,
2254,
5034,
1071,
357,
80,
5269,
2954,
281,
31,
203,
565,
2254,
5034,
1071,
357,
80,
55,
641,
530,
2967,
14667,
31,
203,
565,
2254,
5034,
1071,
357,
80,
48,
18988,
24237,
14667,
31,
203,
565,
2254,
5034,
1071,
357,
80,
56,
266,
345,
22498,
14667,
31,
203,
2
] |
pragma solidity 0.6.10;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
//Note that assert() is now used because the try/catch mechanism in the DepoToken.sol contract does not revert on failure with require();
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a/*, "SafeMath: addition overflow"*/);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
assert(b <= a/*, errorMessage*/);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b/*, "SafeMath: multiplication overflow"*/);
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
assert(b > 0/*, errorMessage*/);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
assert(b != 0/*, errorMessage*/);
return a % b;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
assert(_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 {
assert(newOwner != address(0)/*, "Ownable: new owner is the zero address"*/);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// Contract used to calculate stakes. Unused currently.
abstract contract CalculatorInterface {
function calculateNumTokens(uint256 balance, uint256 daysStaked, address stakerAddress, uint256 totalSupply) public virtual returns (uint256);
function randomness() public view virtual returns (uint256);
}
// Parent token contract, see DepoToken.sol
abstract contract DepoToken {
function balanceOf(address account) public view virtual returns (uint256);
function _burn(address account, uint256 amount) external virtual;
}
/**
* @dev Implementation of Depo:
* Depo is a price-reactive cryptocurrency.
* That is, the inflation rate of the token is wholly dependent on its market activity.
* Minting does not happen when the price is less than the day prior.
* When the price is greater than the day prior, the inflation for that day is
* a function of its price, percent increase, volume, any positive price streaks,
* and the amount of time any given holder has been holding.
* In the first iteration, the dev team acts as the price oracle, but in the future, we plan to integrate a Chainlink price oracle.
* This contract is the staking contract for the project and is upgradeable by the owner.
*/
contract DepoStaking is Ownable {
using SafeMath for uint256;
// A 'staker' is an individual who holds the minimum staking amount in his address.
struct staker {
uint startTimestamp; // When the staking started in unix time (block.timesamp)
uint lastTimestamp; // When the last staking reward was claimed in unix time (block.timestamp)
}
struct update { // Price updateState
uint timestamp; // Last update timestamp, unix time
uint numerator; // Numerator of percent change (1% increase = 1/100)
uint denominator; // Denominator of percent change
uint price; // In USD. 0001 is $0.001, 1000 is $1.000, 1001 is $1.001, etc
uint volume; // In whole USD (100 = $100)
}
DepoToken public token; // ERC20 token contract that uses this upgradeable contract for staking and burning
modifier onlyToken() {
assert(_msgSender() == address(token)/*, "Caller must be DEPO token contract."*/);
_;
}
modifier onlyNextStakingContract() { // Caller must be the next staking contract
assert(_msgSender() == _nextStakingContract);
_;
}
mapping (address => staker) private _stakers; // Mapping of all individuals staking/holding tokens greater than minStake
mapping (address => string) private _whitelist; // Mapping of all addresses that do not burn tokens on receive and send (generally other smart contracts). Mapping of address to reason (string)
mapping (address => uint256) private _blacklist; // Mapping of all addresses that receive a specific token burn when receiving. Mapping of address to percent burn (uint256)
bool private _enableBurns; // Enable burning on transfer or fee on transfer
bool private _priceTarget1Hit; // Price targets, defined in updateState()
bool private _priceTarget2Hit;
address public _uniswapV2Pair; // Uniswap pair address, done for fees on Uniswap sells
uint8 private _uniswapSellerBurnPercent; // Uniswap sells pay a fee
bool private _enableUniswapDirectBurns; // Enable seller fees on Uniswap
uint256 private _minStake; // Minimum amount to stake
uint8 private _minStakeDurationDays; // Minimum amount of time to claim staking rewards
uint8 private _minPercentIncrease; // Minimum percent increase to enable rewards for the day. 10 = 1.0%, 100 = 10.0%
uint256 private _inflationAdjustmentFactor; // Factor to adjust the amount of rewards (inflation) to be given out in a single day
uint256 private _streak; // Number of days in a row that the price has increased
update public _lastUpdate; // latest price update
CalculatorInterface private _externalCalculator; // external calculator to calculate the number of tokens given several variables (defined above). Currently unused
address private _nextStakingContract; // Next staking contract deployed. Used for migrating staker state.
bool private _useExternalCalc; // self-explanatory
bool private _freeze; // freeze all transfers in an emergency
bool private _enableHoldersDay; // once a month, holders receive a nice bump
event StakerRemoved(address StakerAddress); // Staker was removed due to balance dropping below _minStake
event StakerAdded(address StakerAddress); // Staker was added due to balance increasing abolve _minStake
event StakesUpdated(uint Amount); // Staking rewards were claimed
event MassiveCelebration(); // Happens when price targets are hit
event Transfer(address indexed from, address indexed to, uint256 value); // self-explanatory
constructor (DepoToken Token) public {
token = Token;
_minStake = 500E18;
_inflationAdjustmentFactor = 100;
_streak = 0;
_minStakeDurationDays = 0;
_useExternalCalc = false;
_uniswapSellerBurnPercent = 5;
_enableBurns = false;
_freeze = false;
_minPercentIncrease = 10; // 1.0% min increase
_enableUniswapDirectBurns = false;
}
// The owner (or price oracle) will call this function to update the price on days the coin is positive. On negative days, no update is made.
function updateState(uint numerator, uint denominator, uint256 price, uint256 volume) external onlyOwner { // when chainlink is integrated a separate contract will call this function (onlyOwner state will be changed as well)
require(numerator > 0 && denominator > 0 && price > 0 && volume > 0, "Parameters cannot be negative or zero");
if (numerator < 2 && denominator == 100 || numerator < 20 && denominator == 1000) {
require(mulDiv(1000, numerator, denominator) >= _minPercentIncrease, "Increase must be at least _minPercentIncrease to count");
}
uint8 daysSinceLastUpdate = uint8((block.timestamp - _lastUpdate.timestamp) / 86400); // We calculate time since last price update in days. Overflow is possible but incredibly unlikely.
if (daysSinceLastUpdate == 0) { // We should only update once per day, but block timestamps can vary
_streak++;
} else if (daysSinceLastUpdate == 1) {
_streak++; // If we updated yesterday and today, we are on a streak
} else {
_streak = 1;
}
if (price >= 1000 && _priceTarget1Hit == false) { // 1000 = $1.00
_priceTarget1Hit = true;
_streak = 50;
emit MassiveCelebration();
} else if (price >= 10000 && _priceTarget2Hit == false) { // It is written, so it shall be done
_priceTarget2Hit = true;
_streak = 100;
_minStake = 100E18; // Need $1000 to stake
emit MassiveCelebration();
}
_lastUpdate = update(block.timestamp, numerator, denominator, price, volume);
}
function resetStakeTime() external { // This is only necessary if a new staking contract is deployed. Resets 0 timestamp to block.timestamp
uint balance = token.balanceOf(msg.sender);
assert(balance > 0);
assert(balance >= _minStake);
staker memory thisStaker = _stakers[msg.sender];
if (thisStaker.lastTimestamp == 0) {
_stakers[msg.sender].lastTimestamp = block.timestamp;
}
if (thisStaker.startTimestamp == 0) {
_stakers[msg.sender].startTimestamp = block.timestamp;
}
}
// This is used by the next staking contract to migrate staker state
function resetStakeTimeMigrateState(address addr) external onlyNextStakingContract returns (uint256 startTimestamp, uint256 lastTimestamp) {
startTimestamp = _stakers[addr].startTimestamp;
lastTimestamp = _stakers[addr].lastTimestamp;
_stakers[addr].lastTimestamp = block.timestamp;
_stakers[addr].startTimestamp = block.timestamp;
}
function updateMyStakes(address stakerAddress, uint256 balance, uint256 totalSupply) external onlyToken returns (uint256) { // This function is called by the token contract. Holders call the function on the token contract every day the price is positive to claim rewards.
assert(balance > 0);
staker memory thisStaker = _stakers[stakerAddress];
assert(thisStaker.lastTimestamp > 0/*,"Error: your last timestamp cannot be zero."*/); // We use asserts now so that we fail on errors due to try/catch in token contract.
assert(thisStaker.startTimestamp > 0/*,"Error: your start timestamp cannot be zero."*/);
assert((block.timestamp.sub(_lastUpdate.timestamp)) / 86400 == 0/*, "Stakes must be updated the same day of the latest update"*/); // We recognize that block.timestamp can be gamed by miners to some extent, but from what we undertand block timestamps *cannot be before the last block* by consensus rules, otherwise they will fork the chain
assert(block.timestamp > thisStaker.lastTimestamp/*, "Error: block timestamp is not greater than your last timestamp!"*/);
assert(_lastUpdate.timestamp > thisStaker.lastTimestamp/*, "Error: you can only update stakes once per day. You also cannot update stakes on the same day that you purchased them."*/);
uint daysStaked = block.timestamp.sub(thisStaker.startTimestamp) / 86400; // Calculate time staked in days
assert(daysStaked >= _minStakeDurationDays/*, "You must stake for at least minStakeDurationDays to claim rewards"*/);
assert(balance >= _minStake/*, "You must have a balance of at least minStake to claim rewards"*/);
uint numTokens = calculateNumTokens(balance, daysStaked, stakerAddress, totalSupply); // Calls token calculation function - this is either an external contract or the function in this contract
if (_enableHoldersDay && daysStaked >= 30) {
numTokens = mulDiv(balance, daysStaked, 600); // Once a month, holders get a nice bump
}
_stakers[stakerAddress].lastTimestamp = block.timestamp; // Again, this can be gamed to some extent, but *cannot be before the last block*
emit StakesUpdated(numTokens);
return numTokens; // Token contract will add these tokens to the balance of stakerAddress
}
function calculateNumTokens(uint256 balance, uint256 daysStaked, address stakerAddress, uint256 totalSupply) internal returns (uint256) {
if (_useExternalCalc) {
return _externalCalculator.calculateNumTokens(balance, daysStaked, stakerAddress, totalSupply); // Use external contract, if one is enabled (disabled by default, currently unused)
}
uint256 inflationAdjustmentFactor = _inflationAdjustmentFactor;
if (_streak > 1) {
inflationAdjustmentFactor /= _streak; // If there is a streak, we decrease the inflationAdjustmentFactor
}
if (daysStaked > 60) { // If you stake for more than 60 days, you have hit the upper limit of the multiplier
daysStaked = 60;
} else if (daysStaked == 0) { // If the minimum days staked is zero, we change the number to 1 so we don't return zero below
daysStaked = 1;
}
uint marketCap = mulDiv(totalSupply, _lastUpdate.price, 1000E18); // Market cap (including locked team tokens)
uint ratio = marketCap.div(_lastUpdate.volume); // Ratio of market cap to volume
if (ratio > 50) { // Too little volume. Decrease rewards.
inflationAdjustmentFactor = inflationAdjustmentFactor.mul(10);
} else if (ratio > 25) { // Still not enough. Streak doesn't count.
inflationAdjustmentFactor = _inflationAdjustmentFactor;
}
uint numTokens = mulDiv(balance, _lastUpdate.numerator * daysStaked, _lastUpdate.denominator * inflationAdjustmentFactor); // Function that calculates how many tokens are due. See muldiv below.
uint tenPercent = mulDiv(balance, 1, 10);
if (numTokens > tenPercent) { // We don't allow a daily rewards of greater than ten percent of a holder's balance.
numTokens = tenPercent;
}
return numTokens;
}
// Self-explanatory functions to update several configuration variables
function updateTokenAddress(DepoToken newToken) external onlyOwner {
require(address(newToken) != address(0));
token = newToken;
}
function updateCalculator(CalculatorInterface calc) external onlyOwner {
if(address(calc) == address(0)) {
_externalCalculator = CalculatorInterface(address(0));
_useExternalCalc = false;
} else {
_externalCalculator = calc;
_useExternalCalc = true;
}
}
function updateInflationAdjustmentFactor(uint256 inflationAdjustmentFactor) external onlyOwner {
_inflationAdjustmentFactor = inflationAdjustmentFactor;
}
function updateStreak(uint streak) external onlyOwner {
_streak = streak;
}
function updateMinStakeDurationDays(uint8 minStakeDurationDays) external onlyOwner {
_minStakeDurationDays = minStakeDurationDays;
}
function updateMinStakes(uint minStake) external onlyOwner {
_minStake = minStake;
}
function updateMinPercentIncrease(uint8 minIncrease) external onlyOwner {
_minPercentIncrease = minIncrease;
}
function enableBurns(bool enabledBurns) external onlyOwner {
_enableBurns = enabledBurns;
}
function updateHoldersDay(bool enableHoldersDay) external onlyOwner {
_enableHoldersDay = enableHoldersDay;
}
function updateWhitelist(address addr, string calldata reason, bool remove) external onlyOwner returns (bool) {
if (remove) {
delete _whitelist[addr];
return true;
} else {
_whitelist[addr] = reason;
return true;
}
return false;
}
function updateBlacklist(address addr, uint256 fee, bool remove) external onlyOwner returns (bool) {
if (remove) {
delete _blacklist[addr];
return true;
} else {
_blacklist[addr] = fee;
return true;
}
return false;
}
function updateUniswapPair(address addr) external onlyOwner returns (bool) {
require(addr != address(0));
_uniswapV2Pair = addr;
return true;
}
function updateDirectSellBurns(bool enableDirectSellBurns) external onlyOwner {
_enableUniswapDirectBurns = enableDirectSellBurns;
}
function updateUniswapSellerBurnPercent(uint8 sellerBurnPercent) external onlyOwner {
_uniswapSellerBurnPercent = sellerBurnPercent;
}
function freeze(bool enableFreeze) external onlyOwner {
_freeze = enableFreeze;
}
function updateNextStakingContract(address nextContract) external onlyOwner {
require(nextContract != address(0));
_nextStakingContract = nextContract;
}
function getStaker(address staker) external view returns (uint256, uint256) {
return (_stakers[staker].startTimestamp, _stakers[staker].lastTimestamp);
}
function getWhitelist(address addr) external view returns (string memory) {
return _whitelist[addr];
}
function getBlacklist(address addr) external view returns (uint) {
return _blacklist[addr];
}
// This function was not written by us. It was taken from here: https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1
// We believe it works but do not have the understanding of math required to verify it 100%.
// Takes in three numbers and calculates x * (y/z)
// This is very useful for this contract as percentages are used constantly
function mulDiv (uint x, uint y, uint z) public pure returns (uint) {
(uint l, uint h) = fullMul (x, y);
assert (h < z);
uint mm = mulmod (x, y, z);
if (mm > l) h -= 1;
l -= mm;
uint pow2 = z & -z;
z /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint r = 1;
r *= 2 - z * r;
r *= 2 - z * r;
r *= 2 - z * r;
r *= 2 - z * r;
r *= 2 - z * r;
r *= 2 - z * r;
r *= 2 - z * r;
r *= 2 - z * r;
return l * r;
}
function fullMul (uint x, uint y) private pure returns (uint l, uint h) {
uint mm = mulmod (x, y, uint (-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function streak() public view returns (uint) {
return _streak;
}
// Hooks the transfer() function on DepoToken. All transfers call this function. Takes in sender, recipient address and balances and amount and returns sender balance, recipient balance, and burned amount
function transferHook(address sender, address recipient, uint256 amount, uint256 senderBalance, uint256 recipientBalance) external onlyToken returns (uint256, uint256, uint256) {
assert(_freeze == false);
assert(sender != recipient);
assert(amount > 0);
assert(senderBalance >= amount);
uint totalAmount = amount;
bool shouldAddStaker = true; // We assume that the recipient is a potential staker (not a smart contract)
uint burnedAmount = 0;
if (_enableBurns && bytes(_whitelist[sender]).length == 0 && bytes(_whitelist[recipient]).length == 0) { // Burns are enabled and neither the recipient nor the sender are whitelisted
burnedAmount = mulDiv(amount, _randomness(), 100); // Calculates the amount to be burned. Random integer between 1% and 4%. See _randomness() below
if (_blacklist[recipient] > 0) { //Transferring to a blacklisted address incurs a specific fee
burnedAmount = mulDiv(amount, _blacklist[recipient], 100); // Calculate the fee. The fee is burnt
shouldAddStaker = false; // Blacklisted addresses will never be stakers.
}
if (burnedAmount > 0) {
if (burnedAmount > amount) {
totalAmount = 0;
} else {
totalAmount = amount.sub(burnedAmount);
}
senderBalance = senderBalance.sub(burnedAmount, "ERC20: burn amount exceeds balance"); // Remove the burned amount from the sender's balance
}
} else if (recipient == _uniswapV2Pair) { // Uniswap was used. This is a special case. Uniswap is burn on receive but whitelist on send, so sellers pay fee and buyers do not.
shouldAddStaker = false;
if (_enableUniswapDirectBurns) {
burnedAmount = mulDiv(amount, _uniswapSellerBurnPercent, 100); // Seller fee
if (burnedAmount > 0) {
if (burnedAmount > amount) {
totalAmount = 0;
} else {
totalAmount = amount.sub(burnedAmount);
}
senderBalance = senderBalance.sub(burnedAmount, "ERC20: burn amount exceeds balance");
}
}
}
if (bytes(_whitelist[recipient]).length > 0) {
shouldAddStaker = false;
}
// Here we calculate the percent of the balance an address is receiving. If the address receives too many tokens, the staking time and last time rewards were claimed is reset to block.timestamp
// This is necessary because otherwise funds could move from address to address with no penality and thus an individual could claim multiple times with the same funds
if (shouldAddStaker && _stakers[recipient].startTimestamp > 0 && recipientBalance > 0) { // If you are currently staking, these should all be true
uint percent = mulDiv(1000000, totalAmount, recipientBalance); // This is not really 'percent' it is just a number that represents the totalAmount as a fraction of the recipientBalance
assert(percent > 0);
if(percent.add(_stakers[recipient].startTimestamp) > block.timestamp) { // We represent the 'percent' as seconds and add to the recipient's unix time
_stakers[recipient].startTimestamp = block.timestamp;
} else {
_stakers[recipient].startTimestamp = _stakers[recipient].startTimestamp.add(percent); // Receiving too many tokens resets your holding time
}
if(percent.add(_stakers[recipient].lastTimestamp) > block.timestamp) {
_stakers[recipient].lastTimestamp = block.timestamp;
} else {
_stakers[recipient].lastTimestamp = _stakers[recipient].lastTimestamp.add(percent); // Receiving too many tokens may make you ineligible to claim the next day
}
} else if (shouldAddStaker && recipientBalance == 0 && (_stakers[recipient].startTimestamp > 0 || _stakers[recipient].lastTimestamp > 0)) { // Invalid state, so we reset their data/remove them
delete _stakers[recipient];
emit StakerRemoved(recipient);
}
senderBalance = senderBalance.sub(totalAmount, "ERC20: transfer amount exceeds balance"); // Normal ERC20 transfer
recipientBalance = recipientBalance.add(totalAmount);
if (shouldAddStaker && _stakers[recipient].startTimestamp == 0 && (totalAmount >= _minStake || recipientBalance >= _minStake)) { // If the recipient was not previously a staker and their balance is now greater than minStake, we add them automatically
_stakers[recipient] = staker(block.timestamp, block.timestamp);
emit StakerAdded(recipient);
}
if (senderBalance < _minStake) { // If the sender's balance is below the minimum stake, we remove them automatically
// Remove staker
delete _stakers[sender];
emit StakerRemoved(sender);
} else {
_stakers[sender].startTimestamp = block.timestamp; // Sending tokens automatically resets your 'holding time'
if (_stakers[sender].lastTimestamp == 0) {
_stakers[sender].lastTimestamp = block.timestamp;
}
}
return (senderBalance, recipientBalance, burnedAmount);
}
function _randomness() internal view returns (uint256) { // Calculates token burn on transfer between 1% and 4% (integers)
if(_useExternalCalc) {
return _externalCalculator.randomness();
}
return 1 + uint256(keccak256(abi.encodePacked(blockhash(block.number-1), _msgSender())))%4; // We use the previous block hash as entropy. Can be gamed by a miner to some extent, but we accept this.
}
function burn(address account, uint256 amount) external onlyOwner { // We allow ourselves to burn tokens in case they were minted due to a bug
token._burn(account, amount);
}
function resetStakeTimeDebug(address account) external onlyOwner { // We allow ourselves to reset stake times in case they get changed incorrectly due to a bug
_stakers[account].lastTimestamp = block.timestamp;
_stakers[account].startTimestamp = block.timestamp;
}
} | If the sender's balance is below the minimum stake, we remove them automatically
| if (senderBalance < _minStake) { | 5,713,030 | [
1,
2047,
326,
5793,
1807,
11013,
353,
5712,
326,
5224,
384,
911,
16,
732,
1206,
2182,
6635,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
309,
261,
15330,
13937,
411,
389,
1154,
510,
911,
13,
288,
540,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43114/0x9Fefb85d4eB2DF59923C6102c4801718E6415179/sources/contracts/3_Ballot.sol | Return reward multiplier over the given _from to _to block. View function to see pending CAKEs on frontend. Deposit LP tokens to MasterChef for CAKE allocation. Withdraw LP tokens from MasterChef. Stake CAKE tokens to MasterChef Withdraw CAKE tokens from STAKING. Withdraw without caring about rewards. EMERGENCY ONLY. | interface IPancakeswapFarm {
function poolLength() external view returns (uint256);
function userInfo() external view returns (uint256);
function getMultiplier(uint256 _from, uint256 _to)
external
view
returns (uint256);
function pendingCake(uint256 _pid, address _user)
external
view
returns (uint256);
function deposit(uint256 _pid, uint256 _amount) external;
function withdraw(uint256 _pid, uint256 _amount) external;
function enterStaking(uint256 _amount) external;
function leaveStaking(uint256 _amount) external;
function emergencyWithdraw(uint256 _pid) external;
}
| 4,562,732 | [
1,
990,
19890,
15027,
1879,
326,
864,
389,
2080,
358,
389,
869,
1203,
18,
4441,
445,
358,
2621,
4634,
6425,
47,
6705,
603,
15442,
18,
4019,
538,
305,
511,
52,
2430,
358,
13453,
39,
580,
74,
364,
6425,
6859,
13481,
18,
3423,
9446,
511,
52,
2430,
628,
13453,
39,
580,
74,
18,
934,
911,
6425,
6859,
2430,
358,
13453,
39,
580,
74,
3423,
9446,
6425,
6859,
2430,
628,
2347,
14607,
1360,
18,
3423,
9446,
2887,
5926,
310,
2973,
283,
6397,
18,
7141,
654,
16652,
16068,
20747,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
2971,
19292,
3223,
91,
438,
42,
4610,
288,
203,
565,
445,
2845,
1782,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
16753,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
31863,
5742,
12,
11890,
5034,
389,
2080,
16,
2254,
5034,
389,
869,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
4634,
31089,
12,
11890,
5034,
389,
6610,
16,
1758,
389,
1355,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
443,
1724,
12,
11890,
5034,
389,
6610,
16,
2254,
5034,
389,
8949,
13,
3903,
31,
203,
203,
565,
445,
598,
9446,
12,
11890,
5034,
389,
6610,
16,
2254,
5034,
389,
8949,
13,
3903,
31,
203,
203,
565,
445,
6103,
510,
6159,
12,
11890,
5034,
389,
8949,
13,
3903,
31,
203,
203,
565,
445,
8851,
510,
6159,
12,
11890,
5034,
389,
8949,
13,
3903,
31,
203,
203,
565,
445,
801,
24530,
1190,
9446,
12,
11890,
5034,
389,
6610,
13,
3903,
31,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x79e06a55f115825088969a6ef384D010c100eE39/sources/contracts/PE.sol | receives new price in gwei | function setPrice(uint newPriceGwei) public onlyOwner {
price = newPriceGwei;
}
| 9,669,000 | [
1,
8606,
3606,
394,
6205,
316,
314,
1814,
77,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
5147,
12,
11890,
394,
5147,
43,
1814,
77,
13,
1071,
1338,
5541,
288,
203,
3639,
6205,
273,
394,
5147,
43,
1814,
77,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x632393de9dd19b5fd0cc0c4ff17aa674b2f0a1c0
//Contract name: GESTokenCrowdSale
//Balance: 0 Ether
//Verification Date: 11/16/2017
//Transacion Count: 169
// CODE STARTS HERE
pragma solidity ^0.4.15;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20Basic {
using SafeMath for uint256;
mapping (address => mapping (address => uint256)) internal allowed;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is BurnableToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(0x0, _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
}
/*
* @title GESToken
*/
contract GESToken is MintableToken, PausableToken {
string public constant name = "Galaxy eSolutions";
string public constant symbol = "GES";
uint8 public constant decimals = 18;
}
/**
* @title Crowdsale
* @dev Modified contract for managing a token crowdsale.
*/
contract GESTokenCrowdSale is Ownable {
using SafeMath for uint256;
struct TimeBonus {
uint256 bonusPeriodEndTime;
uint percent;
uint256 weiCap;
}
/* true for finalised crowdsale */
bool public isFinalised;
/* The token object */
MintableToken public token;
/* Start and end timestamps where investments are allowed (both inclusive) */
uint256 public mainSaleStartTime;
uint256 public mainSaleEndTime;
/* Address where funds are transferref after collection */
address public wallet;
/* Address where final 10% of funds will be collected */
address public tokenWallet;
/* How many token units a buyer gets per ether */
uint256 public rate = 100;
/* Amount of raised money in wei */
uint256 public weiRaised;
/* Minimum amount of Wei allowed per transaction = 0.1 Ethers */
uint256 public saleMinimumWei = 100000000000000000;
TimeBonus[] public timeBonuses;
/**
* event for token purchase logging
* event for finalizing the crowdsale
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event FinalisedCrowdsale(uint256 totalSupply, uint256 minterBenefit);
function GESTokenCrowdSale(uint256 _mainSaleStartTime, address _wallet, address _tokenWallet) public {
/* Can't start main sale in the past */
require(_mainSaleStartTime >= now);
/* Confirming wallet addresses as valid */
require(_wallet != 0x0);
require(_tokenWallet != 0x0);
/* The Crowdsale bonus pattern
* 1 day = 86400 = 60 * 60 * 24 (Seconds * Minutes * Hours)
* 1 day * Number of days to close at, Bonus Percentage, Max Wei for which bonus is given
*/
timeBonuses.push(TimeBonus(86400 * 7, 30, 2000000000000000000000)); // 0 - 7 Days, 30 %, 2000 ETH
timeBonuses.push(TimeBonus(86400 * 14, 20, 5000000000000000000000)); // 8 -14 Days, 20 %, 2000ETH + 3000 ETH = 5000 ETH
timeBonuses.push(TimeBonus(86400 * 21, 10, 10000000000000000000000)); // 15-21 Days, 10 %, 5000 ETH + 5000 ETH = 10000 ETH
timeBonuses.push(TimeBonus(86400 * 60, 0, 25000000000000000000000)); // 22-60 Days, 0 %, 10000 ETH + 15000 ETH = 25000 ETH
token = createTokenContract();
mainSaleStartTime = _mainSaleStartTime;
mainSaleEndTime = mainSaleStartTime + 60 days;
wallet = _wallet;
tokenWallet = _tokenWallet;
isFinalised = false;
}
/* Creates the token to be sold */
function createTokenContract() internal returns (MintableToken) {
return new GESToken();
}
/* Fallback function can be used to buy tokens */
function () payable {
buyTokens(msg.sender);
}
/* Low level token purchase function */
function buyTokens(address beneficiary) public payable {
require(!isFinalised);
require(beneficiary != 0x0);
require(msg.value != 0);
require(now <= mainSaleEndTime && now >= mainSaleStartTime);
require(msg.value >= saleMinimumWei);
/* Add bonus to tokens depends on the period */
uint256 bonusedTokens = applyBonus(msg.value);
/* Update state on the blockchain */
weiRaised = weiRaised.add(msg.value);
token.mint(beneficiary, bonusedTokens);
TokenPurchase(msg.sender, beneficiary, msg.value, bonusedTokens);
}
/* Finish Crowdsale,
* Take totalSupply as 89% and mint 11% more to specified owner's wallet
* then stop minting forever.
*/
function finaliseCrowdsale() external onlyOwner returns (bool) {
require(!isFinalised);
uint256 totalSupply = token.totalSupply();
uint256 minterBenefit = totalSupply.mul(10).div(89);
token.mint(tokenWallet, minterBenefit);
token.finishMinting();
forwardFunds();
FinalisedCrowdsale(totalSupply, minterBenefit);
isFinalised = true;
return true;
}
/* Set new dates for main-sale (emergency case) */
function setMainSaleDates(uint256 _mainSaleStartTime) public onlyOwner returns (bool) {
require(!isFinalised);
mainSaleStartTime = _mainSaleStartTime;
mainSaleEndTime = mainSaleStartTime + 60 days;
return true;
}
/* Pause the token contract */
function pauseToken() external onlyOwner {
require(!isFinalised);
GESToken(token).pause();
}
/* Unpause the token contract */
function unpauseToken() external onlyOwner {
GESToken(token).unpause();
}
/* Transfer token's contract ownership to a new owner */
function transferTokenOwnership(address newOwner) external onlyOwner {
GESToken(token).transferOwnership(newOwner);
}
/* @return true if main sale event has ended */
function mainSaleHasEnded() external constant returns (bool) {
return now > mainSaleEndTime;
}
/* Send ether to the fund collection wallet */
function forwardFunds() internal {
wallet.transfer(this.balance);
}
/* Function to calculate bonus tokens based on current time(now) and maximum cap per tier */
function applyBonus(uint256 weiAmount) internal constant returns (uint256 bonusedTokens) {
/* Bonus tokens to be added */
uint256 tokensToAdd = 0;
/* Calculting the amont of tokens to be allocated based on rate and the money transferred*/
uint256 tokens = weiAmount.mul(rate);
uint256 diffInSeconds = now.sub(mainSaleStartTime);
for (uint i = 0; i < timeBonuses.length; i++) {
/* If cap[i] is reached then skip */
if(weiRaised.add(weiAmount) <= timeBonuses[i].weiCap){
for(uint j = i; j < timeBonuses.length; j++){
/* Check which week period time it lies and use that percent */
if (diffInSeconds <= timeBonuses[j].bonusPeriodEndTime) {
tokensToAdd = tokens.mul(timeBonuses[j].percent).div(100);
return tokens.add(tokensToAdd);
}
}
}
}
}
/*
* Function to extract funds as required before finalizing
*/
function fetchFunds() onlyOwner public {
wallet.transfer(this.balance);
}
}
| true for finalised crowdsale */ | bool public isFinalised;
| 2,509,824 | [
1,
3767,
364,
727,
5918,
276,
492,
2377,
5349,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
1426,
1071,
29200,
5918,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x23c4464ed220C07FB90803ea3617Dc5aDC5428F7/sources/Ownable.sol | * @dev Contract module which provides a basic access control mechanism, where there is an account (an owner) that can be granted exclusive access to specific functions. By default, the owner account will be the one that deploys the contract. This can later be changed with {transferOwnership}. This module is used through inheritance. It will make available the modifier `onlyGovernance`, which can be applied to your functions to restrict their use to the owner./ | abstract contract Ownable is Context {
address private _governance;
event OwnershipTransferred(address indexed previousGovernance, address indexed newGovernance);
constructor () {
address msgSender = _msgSender();
_governance = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function governance() public view returns (address) {
return _governance;
}
modifier onlyGovernance() {
require(_governance == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyGovernance {
emit OwnershipTransferred(_governance, address(0));
_governance = address(0);
}
function transferOwnership(address newGovernance) public virtual onlyGovernance {
require(newGovernance != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_governance, newGovernance);
_governance = newGovernance;
}
}
| 15,703,821 | [
1,
8924,
1605,
1492,
8121,
279,
5337,
2006,
3325,
12860,
16,
1625,
1915,
353,
392,
2236,
261,
304,
3410,
13,
716,
848,
506,
17578,
12060,
2006,
358,
2923,
4186,
18,
2525,
805,
16,
326,
3410,
2236,
903,
506,
326,
1245,
716,
5993,
383,
1900,
326,
6835,
18,
1220,
848,
5137,
506,
3550,
598,
288,
13866,
5460,
12565,
5496,
1220,
1605,
353,
1399,
3059,
16334,
18,
2597,
903,
1221,
2319,
326,
9606,
1375,
3700,
43,
1643,
82,
1359,
9191,
1492,
848,
506,
6754,
358,
3433,
4186,
358,
13108,
3675,
999,
358,
326,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
14223,
6914,
353,
1772,
288,
203,
565,
1758,
3238,
389,
75,
1643,
82,
1359,
31,
203,
203,
565,
871,
14223,
9646,
5310,
1429,
4193,
12,
2867,
8808,
2416,
43,
1643,
82,
1359,
16,
1758,
8808,
394,
43,
1643,
82,
1359,
1769,
203,
203,
203,
565,
3885,
1832,
288,
203,
3639,
1758,
1234,
12021,
273,
389,
3576,
12021,
5621,
203,
3639,
389,
75,
1643,
82,
1359,
273,
1234,
12021,
31,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
12,
2867,
12,
20,
3631,
1234,
12021,
1769,
203,
565,
289,
203,
203,
565,
445,
314,
1643,
82,
1359,
1435,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
75,
1643,
82,
1359,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
43,
1643,
82,
1359,
1435,
288,
203,
3639,
2583,
24899,
75,
1643,
82,
1359,
422,
389,
3576,
12021,
9334,
315,
5460,
429,
30,
4894,
353,
486,
326,
3410,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
1654,
8386,
5460,
12565,
1435,
1071,
5024,
1338,
43,
1643,
82,
1359,
288,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
24899,
75,
1643,
82,
1359,
16,
1758,
12,
20,
10019,
203,
3639,
389,
75,
1643,
82,
1359,
273,
1758,
12,
20,
1769,
203,
565,
289,
203,
203,
565,
445,
7412,
5460,
12565,
12,
2867,
394,
43,
1643,
82,
1359,
13,
1071,
5024,
1338,
43,
1643,
82,
1359,
288,
203,
3639,
2583,
12,
2704,
43,
1643,
82,
1359,
480,
1758,
12,
20,
3631,
315,
5460,
429,
30,
394,
3410,
353,
326,
2
] |
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
/**
* @title StudentRegister
* @notice StudentRegister contract is a contract to register the marks of a student and calculates his percentage
*/
contract StudentRegister{
/**
* @dev owner is a state variable
*/
address public owner;
/**
* @dev mapping address as key to struct student with mapping name students
*/
/**
* @dev assigning the contract deployer as the owner
*/
/**
* @dev a modifier onlyOwner is created to limit the access to function register to contract deployer
*/
struct course{
string courseID;
address teacherWA;
address[] students;
uint studentCount;
}
struct mark{
uint[] quiz;
uint[] assignment;
uint attendance;
}
/**
* @dev a struct student is defined
*/
struct student{
address studentWA;
string studentID;
course[] student_courses;
mark[] student_marks;
}
struct teacher{
address teacherWA;
course[] teacher_courses;
}
// global mapping
mapping (address=>student) public students;
mapping(address=>teacher) public teachers;
mapping(string=>course) public courses;
uint numStudents;
//only for registering a new student
mapping(uint=>student) newStudents;
function registerStudent(address studentWA,string memory studentID) public {
student storage s= students[studentWA];
s.studentWA=studentWA;
s.studentID=studentID;
}
function registerTeacher(address teacherWA) public {
teacher storage s= teachers[teacherWA];
s.teacherWA=teacherWA;
}
function createCourse(string memory courseID,address teacherWA) public {
course storage c= courses[courseID];
c.courseID=courseID;
c.teacherWA=teacherWA;
teacher storage t=teachers[teacherWA];
t.teacher_courses.push(c);
// //generate and return invite code
}
string public courseName = "";
function joinCourse(address studentWA,string memory courseID) public{
course storage c= courses[courseID];
c.students.push(studentWA);
c.studentCount++;
student storage s= students[studentWA];
s.student_courses.push(c);
courseName=s.student_courses[0].courseID;
uint[] memory myquiz;
uint[] memory assign;
uint attendance = 0;
mark memory myMark = mark(myquiz,assign,attendance);
s.student_marks.push(myMark);
}
function getStudentMarks(address studentWA, string memory courseID) public view returns(uint[] memory,uint[] memory,uint) {
student storage s = students[studentWA];
uint index = 0;
for(uint i = 0;i<s.student_courses.length;i++ )
{
if(keccak256(bytes(s.student_courses[i].courseID)) == keccak256(bytes(courseID))) {
index = i;
break;
}
}
uint quizLen= s.student_marks[index].quiz.length;
uint assignLen = s.student_marks[index].assignment.length;
uint[] memory quizMrk = new uint[](quizLen);
uint[] memory assignMrk = new uint[](assignLen);
for(uint i = 0; i<quizLen;i++){
quizMrk[i]=s.student_marks[index].quiz[i];
}
for(uint i = 0; i<assignLen;i++){
assignMrk[i]=s.student_marks[index].assignment[i];
}
return(quizMrk ,assignMrk , s.student_marks[index].attendance);
}
function inputMrks(address[] memory studentWA, string memory courseID,uint[] memory mrks) public{
uint indexi = 0;
for(uint j=0;j<studentWA.length;j++){
student storage s = students[studentWA[j]];
for(uint i = 0;i<s.student_courses.length;i++ )
{
if(keccak256(bytes(s.student_courses[i].courseID)) == keccak256(bytes(courseID))) {
indexi = i;
break;
}
}
s.student_marks[indexi].quiz.push(mrks[j]);
}
}
function getStudentCourses(address studentWA) public view returns(string[] memory){
student storage s = students[studentWA];
uint numOfCOurse = s.student_courses.length;
string[] memory coursesOfStudent = new string[](numOfCOurse);
for(uint i = 0;i<numOfCOurse;i++ ){
coursesOfStudent[i] = s.student_courses[i].courseID;
}
return (coursesOfStudent);
}
function getTeacherCourse(address teacherWA) public view returns(string[] memory){
teacher storage t = teachers[teacherWA];
uint numOfCOurse = t.teacher_courses.length;
string[] memory coursesOfteacher = new string[](numOfCOurse);
for(uint i = 0;i<numOfCOurse;i++ ){
coursesOfteacher[i] = t.teacher_courses[i].courseID;
}
return (coursesOfteacher);
}
// function getStudentDetails(address studentWA) public view returns (address,string memory,string memory,uint256,uint256){
// /**
// * @dev returning studentId,name,course,totalMarks and percentage of student to corresponding key
// */
// return(students[studentId].studentId,students[studentId].name,students[studentId].course,students[studentId].totalMarks,students[studentId].percentage);
// }
} | only for registering a new student | mapping(uint=>student) newStudents;
| 1,046,456 | [
1,
3700,
364,
22845,
279,
394,
18110,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
11890,
9207,
26240,
13,
394,
19943,
4877,
31,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "./IERC20.sol";
import "./IERC20Sec.sol";
import "./IFreezable.sol";
import "./IBurnable.sol";
import "./IMintable.sol";
import "./AccessControl.sol";
import "./Pausable.sol";
import "./Wallet.sol";
/**
* @dev Implementation of the {IERC20, IERC20Sec} interfaces.
*/
contract LivelyToken is
IERC20,
IERC20Sec,
IFreezable,
IBurnable,
IMintable,
AccessControl,
Pausable,
Wallet
{
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => uint256) private _freezes;
uint256 private _totalSupply;
/**
* @dev error IllegalArgumentError
*/
error IllegalArgumentError();
/**
* @dev error IllegalBalanceError
*/
error IllegalBalanceError();
/**
* @dev error IllegalTotalSupplyError
*/
error IllegalTotalSupplyError();
/**
* @dev error IllegalAllowanceError
*/
error IllegalAllowanceError();
/**
* @dev error IllegalWalletAddressError
*/
error IllegalWalletAddressError();
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor() {
_totalSupply = 1_000_000_000 * 10**18;
_balances[PUBLIC_SALE_WALLET_ADDRESS] = 500_000_000 * 10**18; // equivalent 50% total supply
_balances[FOUNDING_TEAM_WALLET_ADDRESS] = 200_000_000 * 10**18; // equivalent 20% total supply
_balances[RESERVES_WALLET_ADDRESS] = 100_000_000 * 10**18; // equivalent 10% total supply
_balances[AUDIO_VIDEO_PRODUCTIONS_WALLET_ADDRESS] = 80_000_000 * 10**18; // equivalent 8% total supply
_balances[BOUNTY_PROGRAMS_WALLET_ADDRESS] = 70_000_000 * 10**18; // equivalent 7% total supply
_balances[CHARITY_WALLET_ADDRESS] = 50_000_000 * 10**18; // equivalent 5% total supply
_allowances[PUBLIC_SALE_WALLET_ADDRESS][msg.sender] =
500_000_000 *
10**18;
_allowances[AUDIO_VIDEO_PRODUCTIONS_WALLET_ADDRESS][msg.sender] =
80_000_000 *
10**18;
_allowances[BOUNTY_PROGRAMS_WALLET_ADDRESS][msg.sender] =
70_000_000 *
10**18;
_allowances[CHARITY_WALLET_ADDRESS][msg.sender] = 50_000_000 * 10**18;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControl, Pausable)
returns (bool)
{
return
interfaceId == type(IERC20).interfaceId ||
interfaceId == type(IERC20Sec).interfaceId ||
interfaceId == type(IBurnable).interfaceId ||
interfaceId == type(IMintable).interfaceId ||
interfaceId == type(IPausable).interfaceId ||
interfaceId == type(IFreezable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev Returns the name of the token.
*/
function name() external pure override returns (string memory) {
return "Lively";
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external pure override returns (string memory) {
return "LVL";
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() external pure override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() external view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account)
external
view
override
returns (uint256)
{
return _balances[account];
}
/**
* @dev CONSENSUS_ROLE must initialize by ADMIN_ROLE only once
*
*/
// solhint-disable-next-line
function firstInitializeConsensusRole(address account)
public
validateSenderRole(ADMIN_ROLE)
validateAddress(account)
{
_firstInitializeConsensusRole(account);
_allowances[PUBLIC_SALE_WALLET_ADDRESS][account] = 500_000_000 * 10**18;
_allowances[FOUNDING_TEAM_WALLET_ADDRESS][account] =
200_000_000 *
10**18;
_allowances[RESERVES_WALLET_ADDRESS][account] = 100_000_000 * 10**18;
_allowances[AUDIO_VIDEO_PRODUCTIONS_WALLET_ADDRESS][account] =
80_000_000 *
10**18;
_allowances[BOUNTY_PROGRAMS_WALLET_ADDRESS][account] =
70_000_000 *
10**18;
_allowances[CHARITY_WALLET_ADDRESS][account] = 50_000_000 * 10**18;
}
/**
* @dev See {IFreezable-freezeOf}.
*/
// TODO test for address(0x0)
function freezeOf(address account)
external
view
override
returns (uint256)
{
return _freezes[account];
}
/**
* @dev See {IFreezable-freeze}.
*/
function freeze(uint256 currentFreezeBalance, uint256 amount)
external
override
whenNotPaused
whenNotPausedOf(msg.sender)
validateSenderAccount
returns (uint256 newFreezeBalance)
{
newFreezeBalance = _freeze(msg.sender, currentFreezeBalance, amount);
emit Freeze(msg.sender, currentFreezeBalance, amount);
return newFreezeBalance;
}
/**
* @dev See {IFreezable-unfreeze}.
*/
function unfreeze(uint256 currentFreezeBalance, uint256 amount)
external
override
whenNotPaused
whenNotPausedOf(msg.sender)
validateSenderAccount
returns (uint256 newFreezeBalance)
{
newFreezeBalance = _unfreeze(msg.sender, currentFreezeBalance, amount);
emit Unfreeze(msg.sender, currentFreezeBalance, amount);
return newFreezeBalance;
}
/**
* @dev See {IFreezable-freezeFrom}.
*/
function freezeFrom(
address account,
uint256 currentFreezeBalance,
uint256 amount
)
external
override
whenNotPaused
whenNotPausedOf(account)
validateSenderRoles(CONSENSUS_ROLE, ADMIN_ROLE)
validateAddress(account)
returns (uint256 newFreezeBalance)
{
newFreezeBalance = _freeze(account, currentFreezeBalance, amount);
emit FreezeFrom(msg.sender, account, currentFreezeBalance, amount);
return newFreezeBalance;
}
/**
* @dev See {IFreezable-unfreezeFrom}.
*/
function unfreezeFrom(
address account,
uint256 currentFreezeBalance,
uint256 amount
)
external
override
whenNotPaused
whenNotPausedOf(account)
validateSenderRoles(CONSENSUS_ROLE, ADMIN_ROLE)
validateAddress(account)
returns (uint256 newFreezeBalance)
{
newFreezeBalance = _unfreeze(account, currentFreezeBalance, amount);
emit UnfreezeFrom(msg.sender, account, currentFreezeBalance, amount);
return newFreezeBalance;
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount)
public
override
whenNotPaused
whenNotAccountsPausedOf(msg.sender, recipient)
validateSenderAccount
validateAddress(recipient)
returns (bool)
{
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount)
public
override
whenNotPaused
whenNotPausedOf(msg.sender)
validateSenderAccount
validateAddress(spender)
returns (bool)
{
_approve(msg.sender, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
)
external
override
whenNotPaused
whenNotAccountsPausedOf(sender, recipient)
validateSenderAccount
validateAddresses(sender, recipient)
returns (bool)
{
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][msg.sender];
if (currentAllowance < amount) revert IllegalAllowanceError();
unchecked {
_approve(sender, msg.sender, currentAllowance - amount);
}
return true;
}
/**
* @dev See {IERC20Sec-transferFromSec}.
*/
function transferFromSec(
address sender,
address recipient,
uint256 currentBalance,
uint256 amount
)
external
override
whenNotPaused
whenNotAccountsPausedOf(sender, recipient)
validateSenderAccount
validateAddresses(sender, recipient)
returns (bool)
{
uint256 senderBalance = _balances[sender];
if (senderBalance < amount) revert IllegalArgumentError();
if (senderBalance != currentBalance) revert IllegalBalanceError();
uint256 currentAllowance = _allowances[sender][msg.sender];
if (currentAllowance < amount) revert IllegalAllowanceError();
unchecked {
_approve(sender, msg.sender, currentAllowance - amount);
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit TransferFromSec(msg.sender, sender, recipient, amount);
return true;
}
/**
* @dev See {IERC20Sec-approveSec}.
*/
function approveSec(
address spender,
uint256 currentAllowance,
uint256 amount
)
external
override
whenNotPaused
whenNotPausedOf(msg.sender)
validateSenderAccount
validateAddress(spender)
returns (bool success)
{
uint256 currentAllowanceAccount = _allowances[msg.sender][spender];
if (currentAllowanceAccount != currentAllowance)
revert IllegalAllowanceError();
_allowances[msg.sender][spender] = amount;
emit ApprovalSec(msg.sender, spender, currentAllowanceAccount, amount);
return true;
}
/**
* @dev See {IERC20Sec-increaseAllowanceSec}.
*/
function increaseAllowanceSec(
address spender,
uint256 currentAllowance,
uint256 value
)
external
override
whenNotPaused
whenNotPausedOf(msg.sender)
validateSenderAccount
validateAddress(spender)
returns (bool)
{
uint256 currentAllowanceAccount = _allowances[msg.sender][spender];
if (currentAllowanceAccount != currentAllowance)
revert IllegalAllowanceError();
_allowances[msg.sender][spender] = currentAllowanceAccount + value;
emit ApprovalIncSec(
msg.sender,
spender,
currentAllowanceAccount,
value
);
return true;
}
/**
* @dev See {IERC20Sec-decreaseAllowanceSec}.
*/
function decreaseAllowanceSec(
address spender,
uint256 currentAllowance,
uint256 value
)
external
override
whenNotPaused
whenNotPausedOf(msg.sender)
validateSenderAccount
validateAddress(spender)
returns (bool)
{
uint256 currentAllowanceAccount = _allowances[msg.sender][spender];
if (currentAllowanceAccount < value) revert IllegalArgumentError();
if (currentAllowanceAccount != currentAllowance)
revert IllegalAllowanceError();
unchecked {
_allowances[msg.sender][spender] = currentAllowanceAccount - value;
}
emit ApprovalDecSec(
msg.sender,
spender,
currentAllowanceAccount,
value
);
return true;
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(
address account,
uint256 currentAccountBalance,
uint256 currentTotalSupply,
uint256 amount
)
external
override
whenPaused
validateSenderRole(CONSENSUS_ROLE)
validateAddress(account)
{
if (_balances[account] != currentAccountBalance)
revert IllegalBalanceError();
if (_totalSupply != currentTotalSupply)
revert IllegalTotalSupplyError();
_totalSupply += amount;
_balances[account] += amount;
emit Mint(
msg.sender,
account,
currentAccountBalance,
currentTotalSupply,
amount
);
}
/**
* @dev See {IBurnable-burn}.
*/
function burn(
address account,
uint256 currentBalance,
uint256 currentTotalSupply,
uint256 amount
)
external
override
whenPaused
validateSenderRoles(CONSENSUS_ROLE, BURNABLE_ROLE)
validateAddress(account)
returns (uint256 newBalance, uint256)
{
if (_totalSupply != currentTotalSupply)
revert IllegalTotalSupplyError();
uint256 currentAccountBalance = _balances[account];
if (currentAccountBalance != currentBalance)
revert IllegalBalanceError();
if (currentAccountBalance < amount) revert IllegalArgumentError();
unchecked {
newBalance = currentAccountBalance - amount;
}
_balances[account] = newBalance;
_totalSupply -= amount;
emit Burn(
msg.sender,
account,
currentBalance,
currentTotalSupply,
amount
);
return (newBalance, _totalSupply);
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal {
uint256 senderBalance = _balances[sender];
if (senderBalance < amount) revert IllegalArgumentError();
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal {
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets `amount` as the freeze(stake) of `account`.
*/
function _freeze(
address account,
uint256 currentFreezeBalance,
uint256 amount
) internal returns (uint256 newFreezeBalance) {
uint256 currentBalance = _balances[account];
if (currentBalance < amount) revert IllegalArgumentError();
uint256 currentFreeze = _freezes[account];
if (currentFreezeBalance != currentFreeze) revert IllegalBalanceError();
newFreezeBalance = currentFreeze + amount;
_freezes[account] = newFreezeBalance;
unchecked {
_balances[account] = currentBalance - amount;
}
return newFreezeBalance;
}
/**
* @dev Unfreeze `amount` of `account`.
*/
function _unfreeze(
address account,
uint256 currentFreezeBalance,
uint256 amount
) internal returns (uint256 newFreezeBalance) {
uint256 currentFreeze = _freezes[account];
if (currentFreeze < amount) revert IllegalArgumentError();
if (currentFreezeBalance != currentFreeze) revert IllegalBalanceError();
_balances[account] += amount;
unchecked {
newFreezeBalance = currentFreeze - amount;
}
_freezes[account] = newFreezeBalance;
return newFreezeBalance;
}
/**
* @dev See withdrawal balance of contract by CONSENSUS_ROLE
*/
// solhint-disable-next-line
function withdrawalBalance(address recepient)
external
validateSenderRole(CONSENSUS_ROLE)
{
payable(recepient).transfer(address(this).balance);
}
// solhint-disable-next-line
receive() external payable {}
// solhint-disable-next-line
fallback() external payable {}
}
| * @dev See {IFreezable-unfreeze}./ | function unfreeze(uint256 currentFreezeBalance, uint256 amount)
external
override
whenNotPaused
whenNotPausedOf(msg.sender)
validateSenderAccount
returns (uint256 newFreezeBalance)
{
newFreezeBalance = _unfreeze(msg.sender, currentFreezeBalance, amount);
emit Unfreeze(msg.sender, currentFreezeBalance, amount);
return newFreezeBalance;
}
| 6,363,244 | [
1,
9704,
288,
5501,
992,
94,
429,
17,
318,
29631,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
640,
29631,
12,
11890,
5034,
783,
9194,
8489,
13937,
16,
2254,
5034,
3844,
13,
203,
3639,
3903,
203,
3639,
3849,
203,
3639,
1347,
1248,
28590,
203,
3639,
1347,
1248,
28590,
951,
12,
3576,
18,
15330,
13,
203,
3639,
1954,
12021,
3032,
203,
3639,
1135,
261,
11890,
5034,
394,
9194,
8489,
13937,
13,
203,
565,
288,
203,
3639,
394,
9194,
8489,
13937,
273,
389,
318,
29631,
12,
3576,
18,
15330,
16,
783,
9194,
8489,
13937,
16,
3844,
1769,
203,
3639,
3626,
1351,
29631,
12,
3576,
18,
15330,
16,
783,
9194,
8489,
13937,
16,
3844,
1769,
203,
3639,
327,
394,
9194,
8489,
13937,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
* The edgeless casino contract v2 holds the players's funds and provides state channel functionality.
* The casino has at no time control over the players's funds.
* State channels can be updated and closed from both parties: the player and the casino.
* author: Julia Altenried
**/
pragma solidity ^0.4.19;
contract SafeMath {
function safeSub(uint a, uint b) pure internal returns(uint) {
assert(b <= a);
return a - b;
}
function safeSub(int a, int b) pure internal returns(int) {
if(b < 0) assert(a - b > a);
else assert(a - b <= a);
return a - b;
}
function safeAdd(uint a, uint b) pure internal returns(uint) {
uint c = a + b;
assert(c >= a && c >= b);
return c;
}
function safeMul(uint a, uint b) pure internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
}
contract Token {
function transferFrom(address sender, address receiver, uint amount) public returns(bool success) {}
function transfer(address receiver, uint amount) public returns(bool success) {}
function balanceOf(address holder) public constant returns(uint) {}
}
contract owned {
address public owner;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function owned() public{
owner = msg.sender;
}
}
/** owner should be able to close the contract is nobody has been using it for at least 30 days */
contract mortal is owned {
/** contract can be closed by the owner anytime after this timestamp if non-zero */
uint public closeAt;
/** the edgeless token contract */
Token edg;
function mortal(address tokenContract) internal{
edg = Token(tokenContract);
}
/**
* lets the owner close the contract if there are no player funds on it or if nobody has been using it for at least 30 days
*/
function closeContract(uint playerBalance) internal{
if(closeAt == 0) closeAt = now + 30 days;
if(closeAt < now || playerBalance == 0){
edg.transfer(owner, edg.balanceOf(address(this)));
selfdestruct(owner);
}
}
/**
* in case close has been called accidentally.
**/
function open() onlyOwner public{
closeAt = 0;
}
/**
* make sure the contract is not in process of being closed.
**/
modifier isAlive {
require(closeAt == 0);
_;
}
/**
* delays the time of closing.
**/
modifier keepAlive {
if(closeAt > 0) closeAt = now + 30 days;
_;
}
}
contract requiringAuthorization is mortal {
/** indicates if an address is authorized to act in the casino's name */
mapping(address => bool) public authorized;
/** tells if an address is allowed to receive funds from the bankroll **/
mapping(address => bool) public allowedReceiver;
modifier onlyAuthorized {
require(authorized[msg.sender]);
_;
}
/**
* Constructor. Authorize the owner.
* */
function requiringAuthorization() internal {
authorized[msg.sender] = true;
allowedReceiver[msg.sender] = true;
}
/**
* authorize a address to call game functions and set configs.
* @param addr the address to be authorized
**/
function authorize(address addr) public onlyOwner {
authorized[addr] = true;
}
/**
* deauthorize a address to call game functions and set configs.
* @param addr the address to be deauthorized
**/
function deauthorize(address addr) public onlyOwner {
authorized[addr] = false;
}
/**
* allow authorized wallets to withdraw funds from the bonkroll to this address
* @param receiver the receiver's address
* */
function allowReceiver(address receiver) public onlyOwner {
allowedReceiver[receiver] = true;
}
/**
* disallow authorized wallets to withdraw funds from the bonkroll to this address
* @param receiver the receiver's address
* */
function disallowReceiver(address receiver) public onlyOwner {
allowedReceiver[receiver] = false;
}
/**
* changes the owner of the contract. revokes authorization of the old owner and authorizes the new one.
* @param newOwner the address of the new owner
* */
function changeOwner(address newOwner) public onlyOwner {
deauthorize(owner);
authorize(newOwner);
disallowReceiver(owner);
allowReceiver(newOwner);
owner = newOwner;
}
}
contract chargingGas is requiringAuthorization, SafeMath {
/** 1 EDG has 5 decimals **/
uint public constant oneEDG = 100000;
/** the price per kgas and GWei in tokens (with decimals) */
uint public gasPrice;
/** the amount of gas used per transaction in kGas */
mapping(bytes4 => uint) public gasPerTx;
/** the number of tokens (5 decimals) payed by the users to cover the gas cost */
uint public gasPayback;
function chargingGas(uint kGasPrice) internal{
//deposit, withdrawFor, updateChannel, updateBatch, transferToNewContract
bytes4[5] memory signatures = [bytes4(0x3edd1128),0x9607610a, 0xde48ff52, 0xc97b6d1f, 0x6bf06fde];
//amount of gas consumed by the above methods in GWei
uint[5] memory gasUsage = [uint(146), 100, 65, 50, 85];
setGasUsage(signatures, gasUsage);
setGasPrice(kGasPrice);
}
/**
* sets the amount of gas consumed by methods with the given sigantures.
* only called from the edgeless casino constructor.
* @param signatures an array of method-signatures
* gasNeeded the amount of gas consumed by these methods
* */
function setGasUsage(bytes4[5] signatures, uint[5] gasNeeded) public onlyOwner {
require(signatures.length == gasNeeded.length);
for (uint8 i = 0; i < signatures.length; i++)
gasPerTx[signatures[i]] = gasNeeded[i];
}
/**
* updates the price per 1000 gas in EDG.
* @param price the new gas price (with decimals, max 0.1 EDG)
**/
function setGasPrice(uint price) public onlyAuthorized {
require(price < oneEDG/10);
gasPrice = price;
}
/**
* returns the gas cost of the called function.
* */
function getGasCost() internal view returns(uint) {
return safeMul(safeMul(gasPerTx[msg.sig], gasPrice), tx.gasprice) / 1000000000;
}
}
contract CasinoBank is chargingGas {
/** the total balance of all players with virtual decimals **/
uint public playerBalance;
/** the balance per player in edgeless tokens with virtual decimals */
mapping(address => uint) public balanceOf;
/** in case the user wants/needs to call the withdraw function from his own wallet, he first needs to request a withdrawal */
mapping(address => uint) public withdrawAfter;
/** a number to count withdrawal signatures to ensure each signature is different even if withdrawing the same amount to the same address */
mapping(address => uint) public withdrawCount;
/** the maximum amount of tokens the user is allowed to deposit (with decimals) */
uint public maxDeposit;
/** the maximum withdrawal of tokens the user is allowed to withdraw on one day (only enforced when the tx is not sent from an authorized wallet) **/
uint public maxWithdrawal;
/** waiting time for withdrawal if not requested via the server **/
uint public waitingTime;
/** the address of the predecessor **/
address public predecessor;
/** informs listeners how many tokens were deposited for a player */
event Deposit(address _player, uint _numTokens, uint _gasCost);
/** informs listeners how many tokens were withdrawn from the player to the receiver address */
event Withdrawal(address _player, address _receiver, uint _numTokens, uint _gasCost);
/**
* Constructor.
* @param depositLimit the maximum deposit allowed
* predecessorAddr the address of the predecessing contract
* */
function CasinoBank(uint depositLimit, address predecessorAddr) internal {
maxDeposit = depositLimit * oneEDG;
maxWithdrawal = maxDeposit;
waitingTime = 24 hours;
predecessor = predecessorAddr;
}
/**
* accepts deposits for an arbitrary address.
* retrieves tokens from the message sender and adds them to the balance of the specified address.
* edgeless tokens do not have any decimals, but are represented on this contract with decimals.
* @param receiver address of the receiver
* numTokens number of tokens to deposit (0 decimals)
* chargeGas indicates if the gas cost is subtracted from the user's edgeless token balance
**/
function deposit(address receiver, uint numTokens, bool chargeGas) public isAlive {
require(numTokens > 0);
uint value = safeMul(numTokens, oneEDG);
uint gasCost;
if (chargeGas) {
gasCost = getGasCost();
value = safeSub(value, gasCost);
gasPayback = safeAdd(gasPayback, gasCost);
}
uint newBalance = safeAdd(balanceOf[receiver], value);
require(newBalance <= maxDeposit);
assert(edg.transferFrom(msg.sender, address(this), numTokens));
balanceOf[receiver] = newBalance;
playerBalance = safeAdd(playerBalance, value);
Deposit(receiver, numTokens, gasCost);
}
/**
* If the user wants/needs to withdraw his funds himself, he needs to request the withdrawal first.
* This method sets the earliest possible withdrawal date to 'waitingTime from now (default 90m, but up to 24h).
* Reason: The user should not be able to withdraw his funds, while the the last game methods have not yet been mined.
**/
function requestWithdrawal() public {
withdrawAfter[msg.sender] = now + waitingTime;
}
/**
* In case the user requested a withdrawal and changes his mind.
* Necessary to be able to continue playing.
**/
function cancelWithdrawalRequest() public {
withdrawAfter[msg.sender] = 0;
}
/**
* withdraws an amount from the user balance if the waiting time passed since the request.
* @param amount the amount of tokens to withdraw
**/
function withdraw(uint amount) public keepAlive {
require(amount <= maxWithdrawal);
require(withdrawAfter[msg.sender] > 0 && now > withdrawAfter[msg.sender]);
withdrawAfter[msg.sender] = 0;
uint value = safeMul(amount, oneEDG);
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], value);
playerBalance = safeSub(playerBalance, value);
assert(edg.transfer(msg.sender, amount));
Withdrawal(msg.sender, msg.sender, amount, 0);
}
/**
* lets the owner withdraw from the bankroll
* @param receiver the receiver's address
* numTokens the number of tokens to withdraw (0 decimals)
**/
function withdrawBankroll(address receiver, uint numTokens) public onlyAuthorized {
require(numTokens <= bankroll());
require(allowedReceiver[receiver]);
assert(edg.transfer(receiver, numTokens));
}
/**
* withdraw the gas payback to the owner
**/
function withdrawGasPayback() public onlyAuthorized {
uint payback = gasPayback / oneEDG;
assert(payback > 0);
gasPayback = safeSub(gasPayback, payback * oneEDG);
assert(edg.transfer(owner, payback));
}
/**
* returns the current bankroll in tokens with 0 decimals
**/
function bankroll() constant public returns(uint) {
return safeSub(edg.balanceOf(address(this)), safeAdd(playerBalance, gasPayback) / oneEDG);
}
/**
* updates the maximum deposit.
* @param newMax the new maximum deposit (0 decimals)
**/
function setMaxDeposit(uint newMax) public onlyAuthorized {
maxDeposit = newMax * oneEDG;
}
/**
* updates the maximum withdrawal.
* @param newMax the new maximum withdrawal (0 decimals)
**/
function setMaxWithdrawal(uint newMax) public onlyAuthorized {
maxWithdrawal = newMax * oneEDG;
}
/**
* sets the time the player has to wait for his funds to be unlocked before withdrawal (if not withdrawing with help of the casino server).
* the time may not be longer than 24 hours.
* @param newWaitingTime the new waiting time in seconds
* */
function setWaitingTime(uint newWaitingTime) public onlyAuthorized {
require(newWaitingTime <= 24 hours);
waitingTime = newWaitingTime;
}
/**
* transfers an amount from the contract balance to the owner's wallet.
* @param receiver the receiver address
* amount the amount of tokens to withdraw (0 decimals)
* v,r,s the signature of the player
**/
function withdrawFor(address receiver, uint amount, uint8 v, bytes32 r, bytes32 s) public onlyAuthorized keepAlive {
address player = ecrecover(keccak256(receiver, amount, withdrawCount[receiver]), v, r, s);
withdrawCount[receiver]++;
uint gasCost = getGasCost();
uint value = safeAdd(safeMul(amount, oneEDG), gasCost);
gasPayback = safeAdd(gasPayback, gasCost);
balanceOf[player] = safeSub(balanceOf[player], value);
playerBalance = safeSub(playerBalance, value);
assert(edg.transfer(receiver, amount));
Withdrawal(player, receiver, amount, gasCost);
}
/**
* transfers the player's tokens directly to the new casino contract after an update.
* @param newCasino the address of the new casino contract
* v, r, s the signature of the player
* chargeGas indicates if the gas cost is payed by the player.
* */
function transferToNewContract(address newCasino, uint8 v, bytes32 r, bytes32 s, bool chargeGas) public onlyAuthorized keepAlive {
address player = ecrecover(keccak256(address(this), newCasino), v, r, s);
uint gasCost = 0;
if(chargeGas) gasCost = getGasCost();
uint value = safeSub(balanceOf[player], gasCost);
require(value > oneEDG);
//fractions of one EDG cannot be withdrawn
value /= oneEDG;
playerBalance = safeSub(playerBalance, balanceOf[player]);
balanceOf[player] = 0;
assert(edg.transfer(newCasino, value));
Withdrawal(player, newCasino, value, gasCost);
CasinoBank cb = CasinoBank(newCasino);
assert(cb.credit(player, value));
}
/**
* receive a player balance from the predecessor contract.
* @param player the address of the player to credit the value for
* value the number of tokens to credit (0 decimals)
* */
function credit(address player, uint value) public returns(bool) {
require(msg.sender == predecessor);
uint valueWithDecimals = safeMul(value, oneEDG);
balanceOf[player] = safeAdd(balanceOf[player], valueWithDecimals);
playerBalance = safeAdd(playerBalance, valueWithDecimals);
Deposit(player, value, 0);
return true;
}
/**
* lets the owner close the contract if there are no player funds on it or if nobody has been using it for at least 30 days
* */
function close() public onlyOwner {
closeContract(playerBalance);
}
}
contract EdgelessCasino is CasinoBank{
/** the most recent known state of a state channel */
mapping(address => State) public lastState;
/** fired when the state is updated */
event StateUpdate(address player, uint128 count, int128 winBalance, int difference, uint gasCost);
/** fired if one of the parties chooses to log the seeds and results */
event GameData(address player, bytes32[] serverSeeds, bytes32[] clientSeeds, int[] results, uint gasCost);
struct State{
uint128 count;
int128 winBalance;
}
/**
* creates a new edgeless casino contract.
* @param predecessorAddress the address of the predecessing contract
* tokenContract the address of the Edgeless token contract
* depositLimit the maximum deposit allowed
* kGasPrice the price per kGas in WEI
**/
function EdgelessCasino(address predecessorAddress, address tokenContract, uint depositLimit, uint kGasPrice) CasinoBank(depositLimit, predecessorAddress) mortal(tokenContract) chargingGas(kGasPrice) public{
}
/**
* updates several state channels at once. can be called by authorized wallets only.
* 1. determines the player address from the signature.
* 2. verifies if the signed game-count is higher than the last known game-count of this channel.
* 3. updates the balances accordingly. This means: It checks the already performed updates for this channel and computes
* the new balance difference to add or subtract from the player‘s balance.
* @param winBalances array of the current wins or losses
* gameCounts array of the numbers of signed game moves
* v,r,s array of the players's signatures
* chargeGas indicates if the gas costs should be subtracted from the players's balances
* */
function updateBatch(int128[] winBalances, uint128[] gameCounts, uint8[] v, bytes32[] r, bytes32[] s, bool chargeGas) public onlyAuthorized{
require(winBalances.length == gameCounts.length);
require(winBalances.length == v.length);
require(winBalances.length == r.length);
require(winBalances.length == s.length);
require(winBalances.length <= 50);
address player;
uint gasCost = 0;
if(chargeGas)
gasCost = getGasCost();
gasPayback = safeAdd(gasPayback, safeMul(gasCost, winBalances.length));
for(uint8 i = 0; i < winBalances.length; i++){
player = ecrecover(keccak256(winBalances[i], gameCounts[i]), v[i], r[i], s[i]);
_updateState(player, winBalances[i], gameCounts[i], gasCost);
}
}
/**
* updates a state channel. can be called by both parties.
* 1. verifies the signature.
* 2. verifies if the signed game-count is higher than the last known game-count of this channel.
* 3. updates the balances accordingly. This means: It checks the already performed updates for this channel and computes
* the new balance difference to add or subtract from the player‘s balance.
* @param winBalance the current win or loss
* gameCount the number of signed game moves
* v,r,s the signature of either the casino or the player
* chargeGas indicates if the gas costs should be subtracted from the player's balance
* */
function updateState(int128 winBalance, uint128 gameCount, uint8 v, bytes32 r, bytes32 s, bool chargeGas) public{
address player = determinePlayer(winBalance, gameCount, v, r, s);
uint gasCost = 0;
if(player == msg.sender)//if the player closes the state channel himself, make sure the signer is a casino wallet
require(authorized[ecrecover(keccak256(player, winBalance, gameCount), v, r, s)]);
else if (chargeGas){//subtract the gas costs from the player balance only if the casino wallet is the sender
gasCost = getGasCost();
gasPayback = safeAdd(gasPayback, gasCost);
}
_updateState(player, winBalance, gameCount, gasCost);
}
/**
* internal method to perform the actual state update.
* @param player the player address
* winBalance the player's win balance
* gameCount the player's game count
* */
function _updateState(address player, int128 winBalance, uint128 gameCount, uint gasCost) internal {
State storage last = lastState[player];
require(gameCount > last.count);
int difference = updatePlayerBalance(player, winBalance, last.winBalance, gasCost);
lastState[player] = State(gameCount, winBalance);
StateUpdate(player, gameCount, winBalance, difference, gasCost);
}
/**
* determines if the msg.sender or the signer of the passed signature is the player. returns the player's address
* @param winBalance the current winBalance, used to calculate the msg hash
* gameCount the current gameCount, used to calculate the msg.hash
* v, r, s the signature of the non-sending party
* */
function determinePlayer(int128 winBalance, uint128 gameCount, uint8 v, bytes32 r, bytes32 s) constant internal returns(address){
if (authorized[msg.sender])//casino is the sender -> player is the signer
return ecrecover(keccak256(winBalance, gameCount), v, r, s);
else
return msg.sender;
}
/**
* computes the difference of the win balance relative to the last known state and adds it to the player's balance.
* in case the casino is the sender, the gas cost in EDG gets subtracted from the player's balance.
* @param player the address of the player
* winBalance the current win-balance
* lastWinBalance the win-balance of the last known state
* gasCost the gas cost of the tx
* */
function updatePlayerBalance(address player, int128 winBalance, int128 lastWinBalance, uint gasCost) internal returns(int difference){
difference = safeSub(winBalance, lastWinBalance);
int outstanding = safeSub(difference, int(gasCost));
uint outs;
if(outstanding < 0){
outs = uint256(outstanding * (-1));
playerBalance = safeSub(playerBalance, outs);
balanceOf[player] = safeSub(balanceOf[player], outs);
}
else{
outs = uint256(outstanding);
assert(bankroll() * oneEDG > outs);
playerBalance = safeAdd(playerBalance, outs);
balanceOf[player] = safeAdd(balanceOf[player], outs);
}
}
/**
* logs some seeds and game results for players wishing to have their game history logged by the contract
* @param serverSeeds array containing the server seeds
* clientSeeds array containing the client seeds
* results array containing the results
* v, r, s the signature of the non-sending party (to make sure the correct results are logged)
* */
function logGameData(bytes32[] serverSeeds, bytes32[] clientSeeds, int[] results, uint8 v, bytes32 r, bytes32 s) public{
address player = determinePlayer(serverSeeds, clientSeeds, results, v, r, s);
uint gasCost;
//charge gas in case the server is logging the results for the player
if(player != msg.sender){
gasCost = (57 + 768 * serverSeeds.length / 1000)*gasPrice;
balanceOf[player] = safeSub(balanceOf[player], gasCost);
playerBalance = safeSub(playerBalance, gasCost);
gasPayback = safeAdd(gasPayback, gasCost);
}
GameData(player, serverSeeds, clientSeeds, results, gasCost);
}
/**
* determines if the msg.sender or the signer of the passed signature is the player. returns the player's address
* @param serverSeeds array containing the server seeds
* clientSeeds array containing the client seeds
* results array containing the results
* v, r, s the signature of the non-sending party
* */
function determinePlayer(bytes32[] serverSeeds, bytes32[] clientSeeds, int[] results, uint8 v, bytes32 r, bytes32 s) constant internal returns(address){
address signer = ecrecover(keccak256(serverSeeds, clientSeeds, results), v, r, s);
if (authorized[msg.sender])//casino is the sender -> player is the signer
return signer;
else if (authorized[signer])
return msg.sender;
else
revert();
}
} | * delays the time of closing./ | modifier keepAlive {
if(closeAt > 0) closeAt = now + 30 days;
_;
}
| 2,416,634 | [
1,
3771,
8271,
326,
813,
434,
7647,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
20597,
24115,
288,
203,
202,
202,
430,
12,
4412,
861,
405,
374,
13,
1746,
861,
273,
2037,
397,
5196,
4681,
31,
203,
202,
202,
67,
31,
203,
202,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.10;
/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
/*///////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
string public name;
string public symbol;
uint8 public immutable decimals;
/*///////////////////////////////////////////////////////////////
ERC20 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
/*///////////////////////////////////////////////////////////////
EIP-2612 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 internal immutable INITIAL_CHAIN_ID;
bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
mapping(address => uint256) public nonces;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) {
name = _name;
symbol = _symbol;
decimals = _decimals;
INITIAL_CHAIN_ID = block.chainid;
INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
}
/*///////////////////////////////////////////////////////////////
ERC20 LOGIC
//////////////////////////////////////////////////////////////*/
function approve(address spender, uint256 amount) public virtual returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transfer(address to, uint256 amount) public virtual returns (bool) {
balanceOf[msg.sender] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool) {
uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
balanceOf[from] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
return true;
}
/*///////////////////////////////////////////////////////////////
EIP-2612 LOGIC
//////////////////////////////////////////////////////////////*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
// Unchecked because the only math done is incrementing
// the owner's nonce which cannot realistically overflow.
unchecked {
address recoveredAddress = ecrecover(
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
),
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
),
v,
r,
s
);
require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
allowance[recoveredAddress][spender] = value;
}
emit Approval(owner, spender, value);
}
function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
}
function computeDomainSeparator() internal view virtual returns (bytes32) {
return
keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256("1"),
block.chainid,
address(this)
)
);
}
/*///////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 amount) internal virtual {
totalSupply += amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(address(0), to, amount);
}
function _burn(address from, uint256 amount) internal virtual {
balanceOf[from] -= amount;
// Cannot underflow because a user's balance
// will never be larger than the total supply.
unchecked {
totalSupply -= amount;
}
emit Transfer(from, address(0), amount);
}
}
/// @notice Provides a flexible and updatable auth pattern which is completely separate from application logic.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/auth/Auth.sol)
/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
abstract contract Auth {
event OwnerUpdated(address indexed user, address indexed newOwner);
event AuthorityUpdated(address indexed user, Authority indexed newAuthority);
address public owner;
Authority public authority;
constructor(address _owner, Authority _authority) {
owner = _owner;
authority = _authority;
emit OwnerUpdated(msg.sender, _owner);
emit AuthorityUpdated(msg.sender, _authority);
}
modifier requiresAuth() {
require(isAuthorized(msg.sender, msg.sig), "UNAUTHORIZED");
_;
}
function isAuthorized(address user, bytes4 functionSig) internal view virtual returns (bool) {
Authority auth = authority; // Memoizing authority saves us a warm SLOAD, around 100 gas.
// Checking if the caller is the owner only after calling the authority saves gas in most cases, but be
// aware that this makes protected functions uncallable even to the owner if the authority is out of order.
return (address(auth) != address(0) && auth.canCall(user, address(this), functionSig)) || user == owner;
}
function setAuthority(Authority newAuthority) public virtual {
// We check if the caller is the owner first because we want to ensure they can
// always swap out the authority even if it's reverting or using up a lot of gas.
require(msg.sender == owner || authority.canCall(msg.sender, address(this), msg.sig));
authority = newAuthority;
emit AuthorityUpdated(msg.sender, newAuthority);
}
function setOwner(address newOwner) public virtual requiresAuth {
owner = newOwner;
emit OwnerUpdated(msg.sender, newOwner);
}
}
/// @notice A generic interface for a contract which provides authorization data to an Auth instance.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/auth/Auth.sol)
/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
interface Authority {
function canCall(
address user,
address target,
bytes4 functionSig
) external view returns (bool);
}
/// @notice Flexible and target agnostic role based Authority that supports up to 256 roles.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/auth/authorities/MultiRolesAuthority.sol)
contract MultiRolesAuthority is Auth, Authority {
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event UserRoleUpdated(address indexed user, uint8 indexed role, bool enabled);
event PublicCapabilityUpdated(bytes4 indexed functionSig, bool enabled);
event RoleCapabilityUpdated(uint8 indexed role, bytes4 indexed functionSig, bool enabled);
event TargetCustomAuthorityUpdated(address indexed target, Authority indexed authority);
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(address _owner, Authority _authority) Auth(_owner, _authority) {}
/*///////////////////////////////////////////////////////////////
CUSTOM TARGET AUTHORITY STORAGE
//////////////////////////////////////////////////////////////*/
mapping(address => Authority) public getTargetCustomAuthority;
/*///////////////////////////////////////////////////////////////
ROLE/USER STORAGE
//////////////////////////////////////////////////////////////*/
mapping(address => bytes32) public getUserRoles;
mapping(bytes4 => bool) public isCapabilityPublic;
mapping(bytes4 => bytes32) public getRolesWithCapability;
function doesUserHaveRole(address user, uint8 role) public view virtual returns (bool) {
return (uint256(getUserRoles[user]) >> role) & 1 != 0;
}
function doesRoleHaveCapability(uint8 role, bytes4 functionSig) public view virtual returns (bool) {
return (uint256(getRolesWithCapability[functionSig]) >> role) & 1 != 0;
}
/*///////////////////////////////////////////////////////////////
AUTHORIZATION LOGIC
//////////////////////////////////////////////////////////////*/
function canCall(
address user,
address target,
bytes4 functionSig
) public view virtual override returns (bool) {
Authority customAuthority = getTargetCustomAuthority[target];
if (address(customAuthority) != address(0)) return customAuthority.canCall(user, target, functionSig);
return
isCapabilityPublic[functionSig] || bytes32(0) != getUserRoles[user] & getRolesWithCapability[functionSig];
}
/*///////////////////////////////////////////////////////////////
CUSTOM TARGET AUTHORITY CONFIGURATION LOGIC
//////////////////////////////////////////////////////////////*/
function setTargetCustomAuthority(address target, Authority customAuthority) public virtual requiresAuth {
getTargetCustomAuthority[target] = customAuthority;
emit TargetCustomAuthorityUpdated(target, customAuthority);
}
/*///////////////////////////////////////////////////////////////
PUBLIC CAPABILITY CONFIGURATION LOGIC
//////////////////////////////////////////////////////////////*/
function setPublicCapability(bytes4 functionSig, bool enabled) public virtual requiresAuth {
isCapabilityPublic[functionSig] = enabled;
emit PublicCapabilityUpdated(functionSig, enabled);
}
/*///////////////////////////////////////////////////////////////
USER ROLE ASSIGNMENT LOGIC
//////////////////////////////////////////////////////////////*/
function setUserRole(
address user,
uint8 role,
bool enabled
) public virtual requiresAuth {
if (enabled) {
getUserRoles[user] |= bytes32(1 << role);
} else {
getUserRoles[user] &= ~bytes32(1 << role);
}
emit UserRoleUpdated(user, role, enabled);
}
/*///////////////////////////////////////////////////////////////
ROLE CAPABILITY CONFIGURATION LOGIC
//////////////////////////////////////////////////////////////*/
function setRoleCapability(
uint8 role,
bytes4 functionSig,
bool enabled
) public virtual requiresAuth {
if (enabled) {
getRolesWithCapability[functionSig] |= bytes32(1 << role);
} else {
getRolesWithCapability[functionSig] &= ~bytes32(1 << role);
}
emit RoleCapabilityUpdated(role, functionSig, enabled);
}
}
/// @title CERC20
/// @author Compound Labs and Rari Capital
/// @notice Minimal Compound/Fuse Comptroller interface.
abstract contract CERC20 is ERC20 {
/// @notice Deposit an amount of underlying tokens to the CERC20.
/// @param underlyingAmount Amount of underlying tokens to deposit.
/// @return An error code or zero if there was no error in the deposit.
function mint(uint256 underlyingAmount) external virtual returns (uint256);
/// @notice Borrow an amount of underlying tokens from the CERC20.
/// @param underlyingAmount Amount of underlying tokens to borrow.
/// @return An error code or zero if there was no error in the borrow.
function borrow(uint256 underlyingAmount) external virtual returns (uint256);
/// @notice Repay an amount of underlying tokens to the CERC20.
/// @param underlyingAmount Amount of underlying tokens to repay.
/// @return An error code or zero if there was no error in the repay.
function repayBorrow(uint256 underlyingAmount) external virtual returns (uint256);
/// @notice Returns the underlying balance of a specific user.
/// @param user The user who's balance the CERC20 will retrieve.
/// @return The amount of underlying tokens the user is entitled to.
function balanceOfUnderlying(address user) external view virtual returns (uint256);
/// @notice Returns the amount of underlying tokens a cToken redeemable for.
/// @return The amount of underlying tokens a cToken is redeemable for.
function exchangeRateStored() external view virtual returns (uint256);
/// @notice Withdraw a specific amount of underlying tokens from the CERC20.
/// @param underlyingAmount Amount of underlying tokens to withdraw.
/// @return An error code or zero if there was no error in the withdraw.
function redeemUnderlying(uint256 underlyingAmount) external virtual returns (uint256);
/// @notice Return teh current borrow balance of a user in the CERC20.
/// @param user The user to get the borrow balance for.
/// @return The current borrow balance of the user.
function borrowBalanceCurrent(address user) external virtual returns (uint256);
/// @notice Repay a user's borrow on their behalf.
/// @param user The user who's borrow to repay.
/// @param underlyingAmount The amount of debt to repay.
/// @return An error code or zero if there was no error in the repayBorrowBehalf.
function repayBorrowBehalf(address user, uint256 underlyingAmount) external virtual returns (uint256);
}
/// @notice Price Feed
/// @author Compound Labs
/// @notice Minimal cToken price feed interface.
interface PriceFeed {
/// @notice Get the underlying price of the cToken's asset.
/// @param cToken The cToken to get the underlying price of.
/// @return The underlying asset price scaled by 1e18.
function getUnderlyingPrice(CERC20 cToken) external view returns (uint256);
function add(address[] calldata underlyings, address[] calldata _oracles) external;
function changeAdmin(address newAdmin) external;
}
/// @title Comptroller
/// @author Compound Labs and Rari Capital
/// @notice Minimal Compound/Fuse Comptroller interface.
interface Comptroller {
/// @notice Retrieves the admin of the Comptroller.
/// @return The current administrator of the Comptroller.
function admin() external view returns (address);
/// @notice Retrieves the price feed of the Comptroller.
/// @return The current price feed of the Comptroller.
function oracle() external view returns (PriceFeed);
/// @notice Maps underlying tokens to their equivalent cTokens in a pool.
/// @param token The underlying token to find the equivalent cToken for.
/// @return The equivalent cToken for the given underlying token.
function cTokensByUnderlying(ERC20 token) external view returns (CERC20);
/// @notice Get's data about a cToken.
/// @param cToken The cToken to get data about.
/// @return isListed Whether the cToken is listed in the Comptroller.
/// @return collateralFactor The collateral factor of the cToken.
function markets(CERC20 cToken) external view returns (bool isListed, uint256 collateralFactor);
/// @notice Enters into a list of cToken markets, enabling them as collateral.
/// @param cTokens The list of cTokens to enter into, enabling them as collateral.
/// @return A list of error codes, or 0 if there were no failures in entering the cTokens.
function enterMarkets(CERC20[] calldata cTokens) external returns (uint256[] memory);
function _setPendingAdmin(address newPendingAdmin)
external
returns (uint256);
function _setBorrowCapGuardian(address newBorrowCapGuardian) external;
function _setMarketSupplyCaps(
CERC20[] calldata cTokens,
uint256[] calldata newSupplyCaps
) external;
function _setMarketBorrowCaps(
CERC20[] calldata cTokens,
uint256[] calldata newBorrowCaps
) external;
function _setPauseGuardian(address newPauseGuardian)
external
returns (uint256);
function _setMintPaused(CERC20 cToken, bool state)
external
returns (bool);
function _setBorrowPaused(CERC20 cToken, bool borrowPaused)
external
returns (bool);
function _setTransferPaused(bool state) external returns (bool);
function _setSeizePaused(bool state) external returns (bool);
function _setPriceOracle(address newOracle)
external
returns (uint256);
function _setCloseFactor(uint256 newCloseFactorMantissa)
external
returns (uint256);
function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa)
external
returns (uint256);
function _setCollateralFactor(
CERC20 cToken,
uint256 newCollateralFactorMantissa
) external returns (uint256);
function _acceptAdmin() external virtual returns (uint256);
function _deployMarket(
bool isCEther,
bytes calldata constructionData,
uint256 collateralFactorMantissa
) external returns (uint256);
function borrowGuardianPaused(address cToken)
external
view
returns (bool);
function comptrollerImplementation()
external
view
returns (address);
function rewardsDistributors(uint256 index)
external
view
returns (address);
function _addRewardsDistributor(address distributor)
external
returns (uint256);
function _setWhitelistEnforcement(bool enforce)
external
returns (uint256);
function _setWhitelistStatuses(
address[] calldata suppliers,
bool[] calldata statuses
) external returns (uint256);
function _unsupportMarket(CERC20 cToken) external returns (uint256);
function _toggleAutoImplementations(bool enabled)
external
returns (uint256);
}
// OpenZeppelin Contracts v4.4.1 (governance/TimelockController.sol)
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `_msgSender()` is missing `role`.
* Overriding this function changes the behavior of the {onlyRole} modifier.
*
* Format of the revert message is described in {_checkRole}.
*
* _Available since v4.6._
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
/**
* @dev Contract module which acts as a timelocked controller. When set as the
* owner of an `Ownable` smart contract, it enforces a timelock on all
* `onlyOwner` maintenance operations. This gives time for users of the
* controlled contract to exit before a potentially dangerous maintenance
* operation is applied.
*
* By default, this contract is self administered, meaning administration tasks
* have to go through the timelock process. The proposer (resp executor) role
* is in charge of proposing (resp executing) operations. A common use case is
* to position this {TimelockController} as the owner of a smart contract, with
* a multisig or a DAO as the sole proposer.
*
* _Available since v3.3._
*/
contract TimelockController is AccessControl {
bytes32 public constant TIMELOCK_ADMIN_ROLE = keccak256("TIMELOCK_ADMIN_ROLE");
bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE");
bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE");
bytes32 public constant CANCELLER_ROLE = keccak256("CANCELLER_ROLE");
uint256 internal constant _DONE_TIMESTAMP = uint256(1);
mapping(bytes32 => uint256) private _timestamps;
uint256 private _minDelay;
/**
* @dev Emitted when a call is scheduled as part of operation `id`.
*/
event CallScheduled(
bytes32 indexed id,
uint256 indexed index,
address target,
uint256 value,
bytes data,
bytes32 predecessor,
uint256 delay
);
/**
* @dev Emitted when a call is performed as part of operation `id`.
*/
event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data);
/**
* @dev Emitted when operation `id` is cancelled.
*/
event Cancelled(bytes32 indexed id);
/**
* @dev Emitted when the minimum delay for future operations is modified.
*/
event MinDelayChange(uint256 oldDuration, uint256 newDuration);
/**
* @dev Initializes the contract with a given `minDelay`, and a list of
* initial proposers and executors. The proposers receive both the
* proposer and the canceller role (for backward compatibility). The
* executors receive the executor role.
*
* NOTE: At construction, both the deployer and the timelock itself are
* administrators. This helps further configuration of the timelock by the
* deployer. After configuration is done, it is recommended that the
* deployer renounces its admin position and relies on timelocked
* operations to perform future maintenance.
*/
constructor(
uint256 minDelay,
address[] memory proposers,
address[] memory executors
) {
_setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE);
_setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE);
_setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE);
_setRoleAdmin(CANCELLER_ROLE, TIMELOCK_ADMIN_ROLE);
// deployer + self administration
_setupRole(TIMELOCK_ADMIN_ROLE, _msgSender());
_setupRole(TIMELOCK_ADMIN_ROLE, address(this));
// register proposers and cancellers
for (uint256 i = 0; i < proposers.length; ++i) {
_setupRole(PROPOSER_ROLE, proposers[i]);
_setupRole(CANCELLER_ROLE, proposers[i]);
}
// register executors
for (uint256 i = 0; i < executors.length; ++i) {
_setupRole(EXECUTOR_ROLE, executors[i]);
}
_minDelay = minDelay;
emit MinDelayChange(0, minDelay);
}
/**
* @dev Modifier to make a function callable only by a certain role. In
* addition to checking the sender's role, `address(0)` 's role is also
* considered. Granting a role to `address(0)` is equivalent to enabling
* this role for everyone.
*/
modifier onlyRoleOrOpenRole(bytes32 role) {
if (!hasRole(role, address(0))) {
_checkRole(role, _msgSender());
}
_;
}
/**
* @dev Contract might receive/hold ETH as part of the maintenance process.
*/
receive() external payable {}
/**
* @dev Returns whether an id correspond to a registered operation. This
* includes both Pending, Ready and Done operations.
*/
function isOperation(bytes32 id) public view virtual returns (bool pending) {
return getTimestamp(id) > 0;
}
/**
* @dev Returns whether an operation is pending or not.
*/
function isOperationPending(bytes32 id) public view virtual returns (bool pending) {
return getTimestamp(id) > _DONE_TIMESTAMP;
}
/**
* @dev Returns whether an operation is ready or not.
*/
function isOperationReady(bytes32 id) public view virtual returns (bool ready) {
uint256 timestamp = getTimestamp(id);
return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp;
}
/**
* @dev Returns whether an operation is done or not.
*/
function isOperationDone(bytes32 id) public view virtual returns (bool done) {
return getTimestamp(id) == _DONE_TIMESTAMP;
}
/**
* @dev Returns the timestamp at with an operation becomes ready (0 for
* unset operations, 1 for done operations).
*/
function getTimestamp(bytes32 id) public view virtual returns (uint256 timestamp) {
return _timestamps[id];
}
/**
* @dev Returns the minimum delay for an operation to become valid.
*
* This value can be changed by executing an operation that calls `updateDelay`.
*/
function getMinDelay() public view virtual returns (uint256 duration) {
return _minDelay;
}
/**
* @dev Returns the identifier of an operation containing a single
* transaction.
*/
function hashOperation(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt
) public pure virtual returns (bytes32 hash) {
return keccak256(abi.encode(target, value, data, predecessor, salt));
}
/**
* @dev Returns the identifier of an operation containing a batch of
* transactions.
*/
function hashOperationBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas,
bytes32 predecessor,
bytes32 salt
) public pure virtual returns (bytes32 hash) {
return keccak256(abi.encode(targets, values, datas, predecessor, salt));
}
/**
* @dev Schedule an operation containing a single transaction.
*
* Emits a {CallScheduled} event.
*
* Requirements:
*
* - the caller must have the 'proposer' role.
*/
function schedule(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt,
uint256 delay
) public virtual onlyRole(PROPOSER_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt);
_schedule(id, delay);
emit CallScheduled(id, 0, target, value, data, predecessor, delay);
}
/**
* @dev Schedule an operation containing a batch of transactions.
*
* Emits one {CallScheduled} event per transaction in the batch.
*
* Requirements:
*
* - the caller must have the 'proposer' role.
*/
function scheduleBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas,
bytes32 predecessor,
bytes32 salt,
uint256 delay
) public virtual onlyRole(PROPOSER_ROLE) {
require(targets.length == values.length, "TimelockController: length mismatch");
require(targets.length == datas.length, "TimelockController: length mismatch");
bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt);
_schedule(id, delay);
for (uint256 i = 0; i < targets.length; ++i) {
emit CallScheduled(id, i, targets[i], values[i], datas[i], predecessor, delay);
}
}
/**
* @dev Schedule an operation that is to becomes valid after a given delay.
*/
function _schedule(bytes32 id, uint256 delay) private {
require(!isOperation(id), "TimelockController: operation already scheduled");
require(delay >= getMinDelay(), "TimelockController: insufficient delay");
_timestamps[id] = block.timestamp + delay;
}
/**
* @dev Cancel an operation.
*
* Requirements:
*
* - the caller must have the 'canceller' role.
*/
function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) {
require(isOperationPending(id), "TimelockController: operation cannot be cancelled");
delete _timestamps[id];
emit Cancelled(id);
}
/**
* @dev Execute an (ready) operation containing a single transaction.
*
* Emits a {CallExecuted} event.
*
* Requirements:
*
* - the caller must have the 'executor' role.
*/
// This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,
// thus any modifications to the operation during reentrancy should be caught.
// slither-disable-next-line reentrancy-eth
function execute(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt);
_beforeCall(id, predecessor);
_call(id, 0, target, value, data);
_afterCall(id);
}
/**
* @dev Execute an (ready) operation containing a batch of transactions.
*
* Emits one {CallExecuted} event per transaction in the batch.
*
* Requirements:
*
* - the caller must have the 'executor' role.
*/
function executeBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas,
bytes32 predecessor,
bytes32 salt
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
require(targets.length == values.length, "TimelockController: length mismatch");
require(targets.length == datas.length, "TimelockController: length mismatch");
bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt);
_beforeCall(id, predecessor);
for (uint256 i = 0; i < targets.length; ++i) {
_call(id, i, targets[i], values[i], datas[i]);
}
_afterCall(id);
}
/**
* @dev Checks before execution of an operation's calls.
*/
function _beforeCall(bytes32 id, bytes32 predecessor) private view {
require(isOperationReady(id), "TimelockController: operation is not ready");
require(predecessor == bytes32(0) || isOperationDone(predecessor), "TimelockController: missing dependency");
}
/**
* @dev Checks after execution of an operation's calls.
*/
function _afterCall(bytes32 id) private {
require(isOperationReady(id), "TimelockController: operation is not ready");
_timestamps[id] = _DONE_TIMESTAMP;
}
/**
* @dev Execute an operation's call.
*
* Emits a {CallExecuted} event.
*/
function _call(
bytes32 id,
uint256 index,
address target,
uint256 value,
bytes calldata data
) private {
(bool success, ) = target.call{value: value}(data);
require(success, "TimelockController: underlying transaction reverted");
emit CallExecuted(id, index, target, value, data);
}
/**
* @dev Changes the minimum timelock duration for future operations.
*
* Emits a {MinDelayChange} event.
*
* Requirements:
*
* - the caller must be the timelock itself. This can only be achieved by scheduling and later executing
* an operation where the timelock is the target and the data is the ABI-encoded call to this function.
*/
function updateDelay(uint256 newDelay) external virtual {
require(msg.sender == address(this), "TimelockController: caller must be timelock");
emit MinDelayChange(_minDelay, newDelay);
_minDelay = newDelay;
}
}
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.
library SafeTransferLib {
event Debug(bool one, bool two, uint256 retsize);
/*///////////////////////////////////////////////////////////////
ETH OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferETH(address to, uint256 amount) internal {
bool success;
assembly {
// Transfer the ETH and store if it succeeded or not.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
require(success, "ETH_TRANSFER_FAILED");
}
/*///////////////////////////////////////////////////////////////
ERC20 OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 amount
) internal {
bool success;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), from) // Append the "from" argument.
mstore(add(freeMemoryPointer, 36), to) // Append the "to" argument.
mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (not just any non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the addition in the
// order of operations or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
)
}
require(success, "TRANSFER_FROM_FAILED");
}
function safeTransfer(
ERC20 token,
address to,
uint256 amount
) internal {
bool success;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (not just any non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the addition in the
// order of operations or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
)
}
require(success, "TRANSFER_FAILED");
}
function safeApprove(
ERC20 token,
address to,
uint256 amount
) internal {
bool success;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (not just any non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the addition in the
// order of operations or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
)
}
require(success, "APPROVE_FAILED");
}
}
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
library FixedPointMathLib {
/*///////////////////////////////////////////////////////////////
SIMPLIFIED FIXED POINT OPERATIONS
//////////////////////////////////////////////////////////////*/
uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.
function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
}
function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.
}
function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.
}
function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.
}
/*///////////////////////////////////////////////////////////////
LOW LEVEL FIXED POINT OPERATIONS
//////////////////////////////////////////////////////////////*/
function mulDivDown(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 z) {
assembly {
// Store x * y in z for now.
z := mul(x, y)
// Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
revert(0, 0)
}
// Divide z by the denominator.
z := div(z, denominator)
}
}
function mulDivUp(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 z) {
assembly {
// Store x * y in z for now.
z := mul(x, y)
// Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
revert(0, 0)
}
// First, divide z - 1 by the denominator and add 1.
// We allow z - 1 to underflow if z is 0, because we multiply the
// end result by 0 if z is zero, ensuring we return 0 if z is zero.
z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1))
}
}
function rpow(
uint256 x,
uint256 n,
uint256 scalar
) internal pure returns (uint256 z) {
assembly {
switch x
case 0 {
switch n
case 0 {
// 0 ** 0 = 1
z := scalar
}
default {
// 0 ** n = 0
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
// If n is even, store scalar in z for now.
z := scalar
}
default {
// If n is odd, store x in z for now.
z := x
}
// Shifting right by 1 is like dividing by 2.
let half := shr(1, scalar)
for {
// Shift n right by 1 before looping to halve it.
n := shr(1, n)
} n {
// Shift n right by 1 each iteration to halve it.
n := shr(1, n)
} {
// Revert immediately if x ** 2 would overflow.
// Equivalent to iszero(eq(div(xx, x), x)) here.
if shr(128, x) {
revert(0, 0)
}
// Store x squared.
let xx := mul(x, x)
// Round to the nearest number.
let xxRound := add(xx, half)
// Revert if xx + half overflowed.
if lt(xxRound, xx) {
revert(0, 0)
}
// Set x to scaled xxRound.
x := div(xxRound, scalar)
// If n is even:
if mod(n, 2) {
// Compute z * x.
let zx := mul(z, x)
// If z * x overflowed:
if iszero(eq(div(zx, x), z)) {
// Revert if x is non-zero.
if iszero(iszero(x)) {
revert(0, 0)
}
}
// Round to the nearest number.
let zxRound := add(zx, half)
// Revert if zx + half overflowed.
if lt(zxRound, zx) {
revert(0, 0)
}
// Return properly scaled zxRound.
z := div(zxRound, scalar)
}
}
}
}
}
/*///////////////////////////////////////////////////////////////
GENERAL NUMBER UTILITIES
//////////////////////////////////////////////////////////////*/
function sqrt(uint256 x) internal pure returns (uint256 z) {
assembly {
// Start off with z at 1.
z := 1
// Used below to help find a nearby power of 2.
let y := x
// Find the lowest power of 2 that is at least sqrt(x).
if iszero(lt(y, 0x100000000000000000000000000000000)) {
y := shr(128, y) // Like dividing by 2 ** 128.
z := shl(64, z) // Like multiplying by 2 ** 64.
}
if iszero(lt(y, 0x10000000000000000)) {
y := shr(64, y) // Like dividing by 2 ** 64.
z := shl(32, z) // Like multiplying by 2 ** 32.
}
if iszero(lt(y, 0x100000000)) {
y := shr(32, y) // Like dividing by 2 ** 32.
z := shl(16, z) // Like multiplying by 2 ** 16.
}
if iszero(lt(y, 0x10000)) {
y := shr(16, y) // Like dividing by 2 ** 16.
z := shl(8, z) // Like multiplying by 2 ** 8.
}
if iszero(lt(y, 0x100)) {
y := shr(8, y) // Like dividing by 2 ** 8.
z := shl(4, z) // Like multiplying by 2 ** 4.
}
if iszero(lt(y, 0x10)) {
y := shr(4, y) // Like dividing by 2 ** 4.
z := shl(2, z) // Like multiplying by 2 ** 2.
}
if iszero(lt(y, 0x8)) {
// Equivalent to 2 ** z.
z := shl(1, z)
}
// Shifting right by 1 is like dividing by 2.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// Compute a rounded down version of z.
let zRoundDown := div(x, z)
// If zRoundDown is smaller, use it.
if lt(zRoundDown, z) {
z := zRoundDown
}
}
}
}
/// @notice Minimal ERC4626 tokenized Vault implementation.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/mixins/ERC4626.sol)
/// @dev Do not use in production! ERC-4626 is still in the last call stage and is subject to change.
abstract contract ERC4626 is ERC20 {
using SafeTransferLib for ERC20;
using FixedPointMathLib for uint256;
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed caller,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/*///////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
ERC20 public immutable asset;
constructor(
ERC20 _asset,
string memory _name,
string memory _symbol
) ERC20(_name, _symbol, _asset.decimals()) {
asset = _asset;
}
/*///////////////////////////////////////////////////////////////
DEPOSIT/WITHDRAWAL LOGIC
//////////////////////////////////////////////////////////////*/
function deposit(uint256 assets, address receiver) public virtual returns (uint256 shares) {
// Check for rounding error since we round down in previewDeposit.
require((shares = previewDeposit(assets)) != 0, "ZERO_SHARES");
// Need to transfer before minting or ERC777s could reenter.
asset.safeTransferFrom(msg.sender, address(this), assets);
_mint(receiver, shares);
emit Deposit(msg.sender, receiver, assets, shares);
afterDeposit(assets, shares);
}
function mint(uint256 shares, address receiver) public virtual returns (uint256 assets) {
assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.
// Need to transfer before minting or ERC777s could reenter.
asset.safeTransferFrom(msg.sender, address(this), assets);
_mint(receiver, shares);
emit Deposit(msg.sender, receiver, assets, shares);
afterDeposit(assets, shares);
}
function withdraw(
uint256 assets,
address receiver,
address owner
) public virtual returns (uint256 shares) {
shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.
if (msg.sender != owner) {
uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;
}
beforeWithdraw(assets, shares);
_burn(owner, shares);
emit Withdraw(msg.sender, receiver, owner, assets, shares);
asset.safeTransfer(receiver, assets);
}
function redeem(
uint256 shares,
address receiver,
address owner
) public virtual returns (uint256 assets) {
if (msg.sender != owner) {
uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;
}
// Check for rounding error since we round down in previewRedeem.
require((assets = previewRedeem(shares)) != 0, "ZERO_ASSETS");
beforeWithdraw(assets, shares);
_burn(owner, shares);
emit Withdraw(msg.sender, receiver, owner, assets, shares);
asset.safeTransfer(receiver, assets);
}
/*///////////////////////////////////////////////////////////////
ACCOUNTING LOGIC
//////////////////////////////////////////////////////////////*/
function totalAssets() public view virtual returns (uint256);
function convertToShares(uint256 assets) public view returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());
}
function convertToAssets(uint256 shares) public view returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);
}
function previewDeposit(uint256 assets) public view virtual returns (uint256) {
return convertToShares(assets);
}
function previewMint(uint256 shares) public view virtual returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);
}
function previewWithdraw(uint256 assets) public view virtual returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());
}
function previewRedeem(uint256 shares) public view virtual returns (uint256) {
return convertToAssets(shares);
}
/*///////////////////////////////////////////////////////////////
DEPOSIT/WITHDRAWAL LIMIT LOGIC
//////////////////////////////////////////////////////////////*/
function maxDeposit(address) public view virtual returns (uint256) {
return type(uint256).max;
}
function maxMint(address) public view virtual returns (uint256) {
return type(uint256).max;
}
function maxWithdraw(address owner) public view virtual returns (uint256) {
return convertToAssets(balanceOf[owner]);
}
function maxRedeem(address owner) public view virtual returns (uint256) {
return balanceOf[owner];
}
/*///////////////////////////////////////////////////////////////
INTERNAL HOOKS LOGIC
//////////////////////////////////////////////////////////////*/
function beforeWithdraw(uint256 assets, uint256 shares) internal virtual {}
function afterDeposit(uint256 assets, uint256 shares) internal virtual {}
}
/// @notice Gas optimized reentrancy protection for smart contracts.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/ReentrancyGuard.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
uint256 private locked = 1;
modifier nonReentrant() {
require(locked == 1, "REENTRANCY");
locked = 2;
_;
locked = 1;
}
}
/// @title Fuse Admin
/// @author Fei Protocol
/// @notice Minimal Fuse Admin interface.
interface FuseAdmin {
/// @notice Whitelists or blacklists a user from accessing the cTokens in the pool.
/// @param users The users to whitelist or blacklist.
/// @param enabled Whether to whitelist or blacklist each user.
function _setWhitelistStatuses(address[] calldata users, bool[] calldata enabled) external;
function _deployMarket(
address underlying,
address irm,
string calldata name,
string calldata symbol,
address impl,
bytes calldata data,
uint256 reserveFactor,
uint256 adminFee,
uint256 collateralFactorMantissa
) external;
}
interface IReverseRegistrar {
/**
@notice sets reverse ENS Record
@param name the ENS record to set
After calling this, a user has a fully configured reverse record claiming the provided name as that account's canonical name.
*/
function setName(string memory name) external returns (bytes32);
}
/**
@title helper contract to set reverse ens record with solmate Auth
@author joeysantoro
@notice sets reverse ENS record against canonical ReverseRegistrar https://docs.ens.domains/contract-api-reference/reverseregistrar.
*/
abstract contract ENSReverseRecordAuth is Auth {
/// @notice the ENS Reverse Registrar
IReverseRegistrar public constant REVERSE_REGISTRAR = IReverseRegistrar(0x084b1c3C81545d370f3634392De611CaaBFf8148);
function setENSName(string memory name) external requiresAuth {
REVERSE_REGISTRAR.setName(name);
}
}
/// @title Turbo Clerk
/// @author Transmissions11
/// @notice Fee determination module for Turbo Safes.
contract TurboClerk is Auth, ENSReverseRecordAuth {
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Creates a new Turbo Clerk contract.
/// @param _owner The owner of the Clerk.
/// @param _authority The Authority of the Clerk.
constructor(address _owner, Authority _authority) Auth(_owner, _authority) {}
/*///////////////////////////////////////////////////////////////
DEFAULT FEE CONFIGURATION
//////////////////////////////////////////////////////////////*/
/// @notice The default fee on Safe interest taken by the protocol.
/// @dev A fixed point number where 1e18 represents 100% and 0 represents 0%.
uint256 public defaultFeePercentage;
/// @notice Emitted when the default fee percentage is updated.
/// @param newDefaultFeePercentage The new default fee percentage.
event DefaultFeePercentageUpdated(address indexed user, uint256 newDefaultFeePercentage);
/// @notice Sets the default fee percentage.
/// @param newDefaultFeePercentage The new default fee percentage.
function setDefaultFeePercentage(uint256 newDefaultFeePercentage) external requiresAuth {
// A fee percentage over 100% makes no sense.
require(newDefaultFeePercentage <= 1e18, "FEE_TOO_HIGH");
// Update the default fee percentage.
defaultFeePercentage = newDefaultFeePercentage;
emit DefaultFeePercentageUpdated(msg.sender, newDefaultFeePercentage);
}
/*///////////////////////////////////////////////////////////////
CUSTOM FEE CONFIGURATION
//////////////////////////////////////////////////////////////*/
/// @notice Maps collaterals to their custom fees on interest taken by the protocol.
/// @dev A fixed point number where 1e18 represents 100% and 0 represents 0%.
mapping(ERC20 => uint256) public getCustomFeePercentageForCollateral;
/// @notice Maps Safes to their custom fees on interest taken by the protocol.
/// @dev A fixed point number where 1e18 represents 100% and 0 represents 0%.
mapping(TurboSafe => uint256) public getCustomFeePercentageForSafe;
/// @notice Emitted when a collateral's custom fee percentage is updated.
/// @param collateral The collateral who's custom fee percentage was updated.
/// @param newFeePercentage The new custom fee percentage.
event CustomFeePercentageUpdatedForCollateral(
address indexed user,
ERC20 indexed collateral,
uint256 newFeePercentage
);
/// @notice Sets a collateral's custom fee percentage.
/// @param collateral The collateral to set the custom fee percentage for.
/// @param newFeePercentage The new custom fee percentage for the collateral.
function setCustomFeePercentageForCollateral(ERC20 collateral, uint256 newFeePercentage) external requiresAuth {
// A fee percentage over 100% makes no sense.
require(newFeePercentage <= 1e18, "FEE_TOO_HIGH");
// Update the custom fee percentage for the Safe.
getCustomFeePercentageForCollateral[collateral] = newFeePercentage;
emit CustomFeePercentageUpdatedForCollateral(msg.sender, collateral, newFeePercentage);
}
/// @notice Emitted when a Safe's custom fee percentage is updated.
/// @param safe The Safe who's custom fee percentage was updated.
/// @param newFeePercentage The new custom fee percentage.
event CustomFeePercentageUpdatedForSafe(address indexed user, TurboSafe indexed safe, uint256 newFeePercentage);
/// @notice Sets a Safe's custom fee percentage.
/// @param safe The Safe to set the custom fee percentage for.
/// @param newFeePercentage The new custom fee percentage for the Safe.
function setCustomFeePercentageForSafe(TurboSafe safe, uint256 newFeePercentage) external requiresAuth {
// A fee percentage over 100% makes no sense.
require(newFeePercentage <= 1e18, "FEE_TOO_HIGH");
// Update the custom fee percentage for the Safe.
getCustomFeePercentageForSafe[safe] = newFeePercentage;
emit CustomFeePercentageUpdatedForSafe(msg.sender, safe, newFeePercentage);
}
/*///////////////////////////////////////////////////////////////
ACCOUNTING LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Returns the fee on interest taken by the protocol for a Safe.
/// @param safe The Safe to get the fee percentage for.
/// @param collateral The collateral/asset of the Safe.
/// @return The fee percentage for the Safe.
function getFeePercentageForSafe(TurboSafe safe, ERC20 collateral) external view returns (uint256) {
// Get the custom fee percentage for the Safe.
uint256 customFeePercentageForSafe = getCustomFeePercentageForSafe[safe];
// If a custom fee percentage is set for the Safe, return it.
if (customFeePercentageForSafe != 0) return customFeePercentageForSafe;
// Get the custom fee percentage for the collateral type.
uint256 customFeePercentageForCollateral = getCustomFeePercentageForCollateral[collateral];
// If a custom fee percentage is set for the collateral, return it.
if (customFeePercentageForCollateral != 0) return customFeePercentageForCollateral;
// Otherwise, return the default fee percentage.
return defaultFeePercentage;
}
}
/// @title Turbo Master
/// @author Transmissions11
/// @notice Factory for creating and managing Turbo Safes.
/// @dev Must be authorized to call the Turbo Fuse Pool's FuseAdmin.
contract TurboMaster is Auth, ENSReverseRecordAuth {
using SafeTransferLib for ERC20;
/*///////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
/// @notice The Turbo Fuse Pool the Safes will interact with.
Comptroller public immutable pool;
/// @notice The Fei token on the network.
ERC20 public immutable fei;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Creates a new Turbo Master contract.
/// @param _pool The Turbo Fuse Pool the Master will use.
/// @param _fei The Fei token on the network.
/// @param _owner The owner of the Master.
/// @param _authority The Authority of the Master.
constructor(
Comptroller _pool,
ERC20 _fei,
address _owner,
Authority _authority
) Auth(_owner, _authority) {
pool = _pool;
fei = _fei;
// Prevent the first safe from getting id 0.
safes.push(TurboSafe(address(0)));
}
/*///////////////////////////////////////////////////////////////
BOOSTER STORAGE
//////////////////////////////////////////////////////////////*/
/// @notice The Booster module used by the Master and its Safes.
TurboBooster public booster;
/// @notice Emitted when the Booster is updated.
/// @param user The user who triggered the update of the Booster.
/// @param newBooster The new Booster contract used by the Master.
event BoosterUpdated(address indexed user, TurboBooster newBooster);
/// @notice Update the Booster used by the Master.
/// @param newBooster The new Booster contract to be used by the Master.
function setBooster(TurboBooster newBooster) external requiresAuth {
booster = newBooster;
emit BoosterUpdated(msg.sender, newBooster);
}
/*///////////////////////////////////////////////////////////////
CLERK STORAGE
//////////////////////////////////////////////////////////////*/
/// @notice The Clerk module used by the Master and its Safes.
TurboClerk public clerk;
/// @notice Emitted when the Clerk is updated.
/// @param user The user who triggered the update of the Clerk.
/// @param newClerk The new Clerk contract used by the Master.
event ClerkUpdated(address indexed user, TurboClerk newClerk);
/// @notice Update the Clerk used by the Master.
/// @param newClerk The new Clerk contract to be used by the Master.
function setClerk(TurboClerk newClerk) external requiresAuth {
clerk = newClerk;
emit ClerkUpdated(msg.sender, newClerk);
}
/*///////////////////////////////////////////////////////////////
DEFAULT SAFE AUTHORITY CONFIGURATION
//////////////////////////////////////////////////////////////*/
/// @notice The default authority to be used by created Safes.
Authority public defaultSafeAuthority;
/// @notice Emitted when the default safe authority is updated.
/// @param user The user who triggered the update of the default safe authority.
/// @param newDefaultSafeAuthority The new default authority to be used by created Safes.
event DefaultSafeAuthorityUpdated(address indexed user, Authority newDefaultSafeAuthority);
/// @notice Set the default authority to be used by created Safes.
/// @param newDefaultSafeAuthority The new default safe authority.
function setDefaultSafeAuthority(Authority newDefaultSafeAuthority) external requiresAuth {
// Update the default safe authority.
defaultSafeAuthority = newDefaultSafeAuthority;
emit DefaultSafeAuthorityUpdated(msg.sender, newDefaultSafeAuthority);
}
/*///////////////////////////////////////////////////////////////
SAFE STORAGE
//////////////////////////////////////////////////////////////*/
/// @notice The total Fei currently boosting Vaults.
uint256 public totalBoosted;
/// @notice Maps Safe addresses to the id they are stored under in the Safes array.
mapping(TurboSafe => uint256) public getSafeId;
/// @notice Maps Vault addresses to the total amount of Fei they've being boosted with.
mapping(ERC4626 => uint256) public getTotalBoostedForVault;
/// @notice Maps collateral types to the total amount of Fei boosted by Safes using it as collateral.
mapping(ERC20 => uint256) public getTotalBoostedAgainstCollateral;
/// @notice An array of all Safes created by the Master.
/// @dev The first Safe is purposely invalid to prevent any Safes from having an id of 0.
TurboSafe[] public safes;
/// @notice Returns all Safes created by the Master.
/// @return An array of all Safes created by the Master.
/// @dev This is provided because Solidity converts public arrays into index getters,
/// but we need a way to allow external contracts and users to access the whole array.
function getAllSafes() external view returns (TurboSafe[] memory) {
return safes;
}
/*///////////////////////////////////////////////////////////////
SAFE CREATION LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when a new Safe is created.
/// @param user The user who created the Safe.
/// @param asset The asset of the Safe.
/// @param safe The newly deployed Safe contract.
/// @param id The index of the Safe in the safes array.
event TurboSafeCreated(address indexed user, ERC20 indexed asset, TurboSafe safe, uint256 id);
/// @notice Creates a new Turbo Safe which supports a specific asset.
/// @param asset The ERC20 token that the Safe should accept.
/// @return safe The newly deployed Turbo Safe which accepts the provided asset.
function createSafe(ERC20 asset) external requiresAuth returns (TurboSafe safe, uint256 id) {
// Create a new Safe using the default authority and provided asset.
safe = new TurboSafe(msg.sender, defaultSafeAuthority, asset);
// Add the safe to the list of Safes.
safes.push(safe);
unchecked {
// Get the index/id of the new Safe.
// Cannot underflow, we just pushed to it.
id = safes.length - 1;
}
// Store the id/index of the new Safe.
getSafeId[safe] = id;
emit TurboSafeCreated(msg.sender, asset, safe, id);
// Prepare a users array to whitelist the Safe.
address[] memory users = new address[](1);
users[0] = address(safe);
// Prepare an enabled array to whitelist the Safe.
bool[] memory enabled = new bool[](1);
enabled[0] = true;
// Whitelist the Safe to access the Turbo Fuse Pool.
FuseAdmin(pool.admin())._setWhitelistStatuses(users, enabled);
}
/*///////////////////////////////////////////////////////////////
SAFE CALLBACK LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Callback triggered whenever a Safe boosts a Vault.
/// @param asset The asset of the Safe.
/// @param vault The Vault that was boosted.
/// @param feiAmount The amount of Fei used to boost the Vault.
function onSafeBoost(
ERC20 asset,
ERC4626 vault,
uint256 feiAmount
) external {
// Get the caller as a Safe instance.
TurboSafe safe = TurboSafe(msg.sender);
// Ensure the Safe was created by this Master.
require(getSafeId[safe] != 0, "INVALID_SAFE");
// Update the total amount of Fei being using to boost Vaults.
totalBoosted += feiAmount;
// Cache the new total boosted for the Vault.
uint256 newTotalBoostedForVault;
// Cache the new total boosted against the Vault's collateral.
uint256 newTotalBoostedAgainstCollateral;
// Update the total amount of Fei being using to boost the Vault.
getTotalBoostedForVault[vault] = (newTotalBoostedForVault = getTotalBoostedForVault[vault] + feiAmount);
// Update the total amount of Fei boosted against the collateral type.
getTotalBoostedAgainstCollateral[asset] = (newTotalBoostedAgainstCollateral =
getTotalBoostedAgainstCollateral[asset] +
feiAmount);
// Check with the booster that the Safe is allowed to boost the Vault using this amount of Fei.
require(
booster.canSafeBoostVault(
safe,
asset,
vault,
feiAmount,
newTotalBoostedForVault,
newTotalBoostedAgainstCollateral
),
"BOOSTER_REJECTED"
);
}
/// @notice Callback triggered whenever a Safe withdraws from a Vault.
/// @param asset The asset of the Safe.
/// @param vault The Vault that was withdrawn from.
/// @param feiAmount The amount of Fei withdrawn from the Vault.
function onSafeLess(
ERC20 asset,
ERC4626 vault,
uint256 feiAmount
) external {
// Get the caller as a Safe instance.
TurboSafe safe = TurboSafe(msg.sender);
// Ensure the Safe was created by this Master.
require(getSafeId[safe] != 0, "INVALID_SAFE");
// Update the total amount of Fei being using to boost the Vault.
getTotalBoostedForVault[vault] -= feiAmount;
// Update the total amount of Fei being using to boost Vaults.
totalBoosted -= feiAmount;
// Update the total amount of Fei boosted against the collateral type.
getTotalBoostedAgainstCollateral[asset] -= feiAmount;
}
/*///////////////////////////////////////////////////////////////
SWEEP LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Emitted a token is sweeped from the Master.
/// @param user The user who sweeped the token from the Master.
/// @param to The recipient of the sweeped tokens.
/// @param amount The amount of the token that was sweeped.
event TokenSweeped(address indexed user, address indexed to, ERC20 indexed token, uint256 amount);
/// @notice Claim tokens sitting idly in the Master.
/// @param to The recipient of the sweeped tokens.
/// @param token The token to sweep and send.
/// @param amount The amount of the token to sweep.
function sweep(
address to,
ERC20 token,
uint256 amount
) external requiresAuth {
emit TokenSweeped(msg.sender, to, token, amount);
// Transfer the sweeped tokens to the recipient.
token.safeTransfer(to, amount);
}
}
/// @title Turbo Safe
/// @author Transmissions11
/// @notice Fuse liquidity accelerator.
contract TurboSafe is Auth, ERC4626, ReentrancyGuard {
using SafeTransferLib for ERC20;
using FixedPointMathLib for uint256;
/*///////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
/// @notice The Master contract that created the Safe.
/// @dev Fees are paid directly to the Master, where they can be swept.
TurboMaster public immutable master;
/// @notice The Fei token on the network.
ERC20 public immutable fei;
/// @notice The Turbo Fuse Pool contract that collateral is held in and Fei is borrowed from.
Comptroller public immutable pool;
/// @notice The Fei cToken in the Turbo Fuse Pool that Fei is borrowed from.
CERC20 public immutable feiTurboCToken;
/// @notice The cToken that accepts the asset in the Turbo Fuse Pool.
CERC20 public immutable assetTurboCToken;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Creates a new Safe that accepts a specific asset.
/// @param _owner The owner of the Safe.
/// @param _authority The Authority of the Safe.
/// @param _asset The ERC20 compliant token the Safe should accept.
constructor(
address _owner,
Authority _authority,
ERC20 _asset
)
Auth(_owner, _authority)
ERC4626(
_asset,
// ex: Dai Stablecoin Turbo Safe
string(abi.encodePacked(_asset.name(), " Turbo Safe")),
// ex: tsDAI
string(abi.encodePacked("ts", _asset.symbol()))
)
{
master = TurboMaster(msg.sender);
fei = master.fei();
// An asset of Fei makes no sense.
require(asset != fei, "INVALID_ASSET");
pool = master.pool();
feiTurboCToken = pool.cTokensByUnderlying(fei);
assetTurboCToken = pool.cTokensByUnderlying(asset);
// If the provided asset is not supported by the Turbo Fuse Pool, revert.
require(address(assetTurboCToken) != address(0), "UNSUPPORTED_ASSET");
// Construct an array of market(s) to enable as collateral.
CERC20[] memory marketsToEnter = new CERC20[](1);
marketsToEnter[0] = assetTurboCToken;
// Enter the market(s) and ensure to properly revert if there is an error.
require(pool.enterMarkets(marketsToEnter)[0] == 0, "ENTER_MARKETS_FAILED");
// Preemptively approve the asset to the Turbo Fuse Pool's corresponding cToken.
asset.safeApprove(address(assetTurboCToken), type(uint256).max);
// Preemptively approve Fei to the Turbo Fuse Pool's Fei cToken.
fei.safeApprove(address(feiTurboCToken), type(uint256).max);
}
/*///////////////////////////////////////////////////////////////
SAFE STORAGE
//////////////////////////////////////////////////////////////*/
/// @notice The current total amount of Fei the Safe is using to boost Vaults.
uint256 public totalFeiBoosted;
/// @notice Maps Vaults to the total amount of Fei they've being boosted with.
/// @dev Used to determine the fees to be paid back to the Master.
mapping(ERC4626 => uint256) public getTotalFeiBoostedForVault;
/*///////////////////////////////////////////////////////////////
MODIFIERS
//////////////////////////////////////////////////////////////*/
/// @dev Checks the caller is authorized using either the Master's Authority or the Safe's local Authority.
modifier requiresLocalOrMasterAuth() {
// Check if the caller is the owner first:
if (msg.sender != owner) {
Authority masterAuth = master.authority(); // Avoid wasting gas calling the Master twice.
// If the Master's Authority does not exist or does not accept upfront:
if (address(masterAuth) == address(0) || !masterAuth.canCall(msg.sender, address(this), msg.sig)) {
Authority auth = authority; // Memoizing saves us a warm SLOAD, around 100 gas.
// The only authorization option left is via the local Authority, otherwise revert.
require(
address(auth) != address(0) && auth.canCall(msg.sender, address(this), msg.sig),
"UNAUTHORIZED"
);
}
}
_;
}
/// @dev Checks the caller is authorized using the Master's Authority.
modifier requiresMasterAuth() {
Authority masterAuth = master.authority(); // Avoid wasting gas calling the Master twice.
// Revert if the Master's Authority does not approve of the call and the caller is not the Master's owner.
require(
(address(masterAuth) != address(0) && masterAuth.canCall(msg.sender, address(this), msg.sig)) ||
msg.sender == master.owner(),
"UNAUTHORIZED"
);
_;
}
/*///////////////////////////////////////////////////////////////
ERC4626 LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Called after any type of deposit occurs.
/// @param assetAmount The amount of assets being deposited.
/// @dev Using requiresAuth here prevents unauthorized users from depositing.
function afterDeposit(uint256 assetAmount, uint256) internal override nonReentrant requiresAuth {
// Collateralize the assets in the Turbo Fuse Pool.
require(assetTurboCToken.mint(assetAmount) == 0, "MINT_FAILED");
}
/// @notice Called before any type of withdrawal occurs.
/// @param assetAmount The amount of assets being withdrawn.
/// @dev Using requiresAuth here prevents unauthorized users from withdrawing.
function beforeWithdraw(uint256 assetAmount, uint256) internal override nonReentrant requiresAuth {
// Withdraw the assets from the Turbo Fuse Pool.
require(assetTurboCToken.redeemUnderlying(assetAmount) == 0, "REDEEM_FAILED");
}
/// @notice Returns the total amount of assets held in the Safe.
/// @return The total amount of assets held in the Safe.
function totalAssets() public view override returns (uint256) {
return assetTurboCToken.balanceOf(address(this)).mulWadDown(assetTurboCToken.exchangeRateStored());
}
/*///////////////////////////////////////////////////////////////
BOOST/LESS LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when a Vault is boosted by the Safe.
/// @param user The user who boosted the Vault.
/// @param vault The Vault that was boosted.
/// @param feiAmount The amount of Fei that was boosted to the Vault.
event VaultBoosted(address indexed user, ERC4626 indexed vault, uint256 feiAmount);
/// @notice Borrow Fei from the Turbo Fuse Pool and deposit it into an authorized Vault.
/// @param vault The Vault to deposit the borrowed Fei into.
/// @param feiAmount The amount of Fei to borrow and supply into the Vault.
function boost(ERC4626 vault, uint256 feiAmount) external nonReentrant requiresAuth {
// Ensure the Vault accepts Fei asset.
require(vault.asset() == fei, "NOT_FEI");
// Call the Master where it will do extra validation
// and update it's total count of funds used for boosting.
master.onSafeBoost(asset, vault, feiAmount);
// Increase the boost total proportionately.
totalFeiBoosted += feiAmount;
// Update the total Fei deposited into the Vault proportionately.
getTotalFeiBoostedForVault[vault] += feiAmount;
emit VaultBoosted(msg.sender, vault, feiAmount);
// Borrow the Fei amount from the Fei cToken in the Turbo Fuse Pool.
require(feiTurboCToken.borrow(feiAmount) == 0, "BORROW_FAILED");
// Approve the borrowed Fei to the specified Vault.
fei.safeApprove(address(vault), feiAmount);
// Deposit the Fei into the specified Vault.
vault.deposit(feiAmount, address(this));
}
/// @notice Emitted when a Vault is withdrawn from by the Safe.
/// @param user The user who lessed the Vault.
/// @param vault The Vault that was withdrawn from.
/// @param feiAmount The amount of Fei that was withdrawn from the Vault.
event VaultLessened(address indexed user, ERC4626 indexed vault, uint256 feiAmount);
/// @notice Withdraw Fei from a deposited Vault and use it to repay debt in the Turbo Fuse Pool.
/// @param vault The Vault to withdraw the Fei from.
/// @param feiAmount The amount of Fei to withdraw from the Vault and repay in the Turbo Fuse Pool.
function less(ERC4626 vault, uint256 feiAmount) external nonReentrant requiresLocalOrMasterAuth {
// Update the total Fei deposited into the Vault proportionately.
getTotalFeiBoostedForVault[vault] -= feiAmount;
// Decrease the boost total proportionately.
totalFeiBoosted -= feiAmount;
emit VaultLessened(msg.sender, vault, feiAmount);
// Withdraw the specified amount of Fei from the Vault.
vault.withdraw(feiAmount, address(this), address(this));
// Get out current amount of Fei debt in the Turbo Fuse Pool.
uint256 feiDebt = feiTurboCToken.borrowBalanceCurrent(address(this));
// Call the Master to allow it to update its accounting.
master.onSafeLess(asset, vault, feiAmount);
// If our debt balance decreased, repay the minimum.
// The surplus Fei will accrue as fees and can be sweeped.
if (feiAmount > feiDebt) feiAmount = feiDebt;
// Repay Fei debt in the Turbo Fuse Pool, unless we would repay nothing.
if (feiAmount != 0) require(feiTurboCToken.repayBorrow(feiAmount) == 0, "REPAY_FAILED");
}
/*///////////////////////////////////////////////////////////////
SLURP LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when a Vault is slurped from by the Safe.
/// @param user The user who slurped the Vault.
/// @param vault The Vault that was slurped.
/// @param protocolFeeAmount The amount of Fei accrued as fees to the Master.
/// @param safeInterestAmount The amount of Fei accrued as interest to the Safe.
event VaultSlurped(
address indexed user,
ERC4626 indexed vault,
uint256 protocolFeeAmount,
uint256 safeInterestAmount
);
/// @notice Accrue any interest earned by the Safe in the Vault.
/// @param vault The Vault to accrue interest from, if any.
/// @dev Sends a portion of the interest to the Master, as determined by the Clerk.
function slurp(ERC4626 vault) external nonReentrant requiresLocalOrMasterAuth returns(uint256 safeInterestAmount) {
// Cache the total Fei currently boosting the Vault.
uint256 totalFeiBoostedForVault = getTotalFeiBoostedForVault[vault];
// Ensure the Safe has Fei currently boosting the Vault.
require(totalFeiBoostedForVault != 0, "NO_FEI_BOOSTED");
// Compute the amount of Fei interest the Safe generated by boosting the Vault.
uint256 interestEarned = vault.previewRedeem(vault.balanceOf(address(this))) - totalFeiBoostedForVault;
// Compute what percentage of the interest earned will go back to the Safe.
uint256 protocolFeePercent = master.clerk().getFeePercentageForSafe(this, asset);
// Compute the amount of Fei the protocol will retain as fees.
uint256 protocolFeeAmount = interestEarned.mulWadDown(protocolFeePercent);
// Compute the amount of Fei the Safe will retain as interest.
safeInterestAmount = interestEarned - protocolFeeAmount;
emit VaultSlurped(msg.sender, vault, protocolFeeAmount, safeInterestAmount);
vault.withdraw(interestEarned, address(this), address(this));
// If we have unaccrued fees, withdraw them from the Vault and transfer them to the Master.
if (protocolFeeAmount != 0) fei.transfer(address(master), protocolFeeAmount);
}
/*///////////////////////////////////////////////////////////////
SWEEP LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Emitted a token is sweeped from the Safe.
/// @param user The user who sweeped the token from the Safe.
/// @param to The recipient of the sweeped tokens.
/// @param amount The amount of the token that was sweeped.
event TokenSweeped(address indexed user, address indexed to, ERC20 indexed token, uint256 amount);
/// @notice Claim tokens sitting idly in the Safe.
/// @param to The recipient of the sweeped tokens.
/// @param token The token to sweep and send.
/// @param amount The amount of the token to sweep.
function sweep(
address to,
ERC20 token,
uint256 amount
) external requiresAuth {
// Ensure the caller is not trying to steal Vault shares or collateral cTokens.
require(getTotalFeiBoostedForVault[ERC4626(address(token))] == 0 && token != assetTurboCToken, "INVALID_TOKEN");
emit TokenSweeped(msg.sender, to, token, amount);
// Transfer the sweeped tokens to the recipient.
token.safeTransfer(to, amount);
}
/*///////////////////////////////////////////////////////////////
GIB LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when a Safe is gibbed.
/// @param user The user who gibbed the Safe.
/// @param to The recipient of the impounded collateral.
/// @param assetAmount The amount of underling tokens impounded.
event SafeGibbed(address indexed user, address indexed to, uint256 assetAmount);
/// @notice Impound a specific amount of a Safe's collateral.
/// @param to The address to send the impounded collateral to.
/// @param assetAmount The amount of the asset to impound.
/// @dev Debt must be repaid in advance, or the redemption will fail.
function gib(address to, uint256 assetAmount) external nonReentrant requiresMasterAuth {
emit SafeGibbed(msg.sender, to, assetAmount);
// Withdraw the specified amount of assets from the Turbo Fuse Pool.
require(assetTurboCToken.redeemUnderlying(assetAmount) == 0, "REDEEM_FAILED");
// Transfer the assets to the authorized caller.
asset.safeTransfer(to, assetAmount);
}
}
/// @title Turbo Booster
/// @author Transmissions11
/// @notice Boost authorization module.
contract TurboBooster is Auth, ENSReverseRecordAuth {
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Creates a new Turbo Booster contract.
/// @param _owner The owner of the Booster.
/// @param _authority The Authority of the Booster.
constructor(address _owner, Authority _authority) Auth(_owner, _authority) {}
/*///////////////////////////////////////////////////////////////
GLOBAL FREEZE CONFIGURATION
//////////////////////////////////////////////////////////////*/
/// @notice Whether boosting is currently frozen.
bool public frozen;
/// @notice Emitted when boosting is frozen or unfrozen.
/// @param user The user who froze or unfroze boosting.
/// @param frozen Whether boosting is now frozen.
event FreezeStatusUpdated(address indexed user, bool frozen);
/// @notice Sets whether boosting is frozen.
/// @param freeze Whether boosting will be frozen.
function setFreezeStatus(bool freeze) external requiresAuth {
// Update freeze status.
frozen = freeze;
emit FreezeStatusUpdated(msg.sender, freeze);
}
/*///////////////////////////////////////////////////////////////
VAULT BOOST CAP CONFIGURATION
//////////////////////////////////////////////////////////////*/
ERC4626[] public boostableVaults;
/// @notice exposes an array of boostable vaults. Only used for visibility.
function getBoostableVaults() external view returns(ERC4626[] memory) {
return boostableVaults;
}
/// @notice Maps Vaults to the cap on the amount of Fei used to boost them.
mapping(ERC4626 => uint256) public getBoostCapForVault;
/// @notice Emitted when a Vault's boost cap is updated.
/// @param vault The Vault who's boost cap was updated.
/// @param newBoostCap The new boost cap for the Vault.
event BoostCapUpdatedForVault(address indexed user, ERC4626 indexed vault, uint256 newBoostCap);
/// @notice Sets a Vault's boost cap.
/// @param vault The Vault to set the boost cap for.
/// @param newBoostCap The new boost cap for the Vault.
function setBoostCapForVault(ERC4626 vault, uint256 newBoostCap) external requiresAuth {
require(newBoostCap != 0, "cap is zero");
// Add to boostable vaults array
if (getBoostCapForVault[vault] == 0) {
boostableVaults.push(vault);
}
// Update the boost cap for the Vault.
getBoostCapForVault[vault] = newBoostCap;
emit BoostCapUpdatedForVault(msg.sender, vault, newBoostCap);
}
/*///////////////////////////////////////////////////////////////
COLLATERAL BOOST CAP CONFIGURATION
//////////////////////////////////////////////////////////////*/
/// @notice Maps collateral types to the cap on the amount of Fei boosted against them.
mapping(ERC20 => uint256) public getBoostCapForCollateral;
/// @notice Emitted when a collateral type's boost cap is updated.
/// @param collateral The collateral type who's boost cap was updated.
/// @param newBoostCap The new boost cap for the collateral type.
event BoostCapUpdatedForCollateral(address indexed user, ERC20 indexed collateral, uint256 newBoostCap);
/// @notice Sets a collateral type's boost cap.
/// @param collateral The collateral type to set the boost cap for.
/// @param newBoostCap The new boost cap for the collateral type.
function setBoostCapForCollateral(ERC20 collateral, uint256 newBoostCap) external requiresAuth {
// Update the boost cap for the collateral type.
getBoostCapForCollateral[collateral] = newBoostCap;
emit BoostCapUpdatedForCollateral(msg.sender, collateral, newBoostCap);
}
/*///////////////////////////////////////////////////////////////
AUTHORIZATION LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Returns whether a Safe is authorized to boost a Vault.
/// @param safe The Safe to check is authorized to boost the Vault.
/// @param collateral The collateral/asset of the Safe.
/// @param vault The Vault to check the Safe is authorized to boost.
/// @param feiAmount The amount of Fei asset to check the Safe is authorized boost the Vault with.
/// @param newTotalBoostedForVault The total amount of Fei that will boosted to the Vault after boost (if it is not rejected).
/// @param newTotalBoostedAgainstCollateral The total amount of Fei that will be boosted against the Safe's collateral type after this boost.
/// @return Whether the Safe is authorized to boost the Vault with the given amount of Fei asset.
function canSafeBoostVault(
TurboSafe safe,
ERC20 collateral,
ERC4626 vault,
uint256 feiAmount,
uint256 newTotalBoostedForVault,
uint256 newTotalBoostedAgainstCollateral
) external view returns (bool) {
return
!frozen &&
getBoostCapForVault[vault] >= newTotalBoostedForVault &&
getBoostCapForCollateral[collateral] >= newTotalBoostedAgainstCollateral;
}
}
/**
@title Turbo Admin of Turbo Fuse Pool and Turbo Timelock
*/
contract TurboAdmin is Auth, ENSReverseRecordAuth {
/// @notice generic error thrown when comptroller call fails
error ComptrollerError();
/// @notice the fuse comptroller associated with the TurboAdmin
Comptroller public immutable comptroller;
/// @notice the turbo timelock
TimelockController public immutable timelock;
/// @notice constant zero interest rate model
address public constant ZERO_IRM = 0xC9dB5A1034BcBcca3f59dD61dbeE31b78CeFD126;
/// @notice cToken implementation
address public constant CTOKEN_IMPL = 0x67Db14E73C2Dce786B5bbBfa4D010dEab4BBFCF9;
/// @param _comptroller the fuse comptroller
constructor(Comptroller _comptroller, TimelockController _timelock, Authority _authority) Auth(address(0), _authority) {
comptroller = _comptroller;
timelock = _timelock;
}
// ************ TURBO ADMIN FUNCTIONS ************
function addCollateral(
address underlying,
string calldata name,
string calldata symbol,
uint256 collateralFactorMantissa,
uint256 supplyCap
) external requiresAuth {
bytes memory constructorData = abi.encode(
underlying,
address(comptroller),
ZERO_IRM,
name,
symbol,
CTOKEN_IMPL,
new bytes(0),
0, // zero admin fee
0 // zero reserve factor
);
if (
comptroller._deployMarket(
false,
constructorData,
collateralFactorMantissa
) != 0
) revert ComptrollerError();
// set borrow paused
CERC20 cToken = comptroller.cTokensByUnderlying(ERC20(underlying));
_setBorrowPausedInternal(cToken, true);
CERC20[] memory markets = new CERC20[](1);
markets[0] = cToken;
uint256[] memory caps = new uint256[](1);
caps[0] = supplyCap;
comptroller._setMarketSupplyCaps(markets, caps);
}
// ************ BORROW GUARDIAN FUNCTIONS ************
/**
* @notice Set the given supply caps for the given cToken markets. Supplying that brings total underlying supply to or above supply cap will revert.
* @dev Admin or borrowCapGuardian function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying.
* @param cTokens The addresses of the markets (tokens) to change the supply caps for
* @param newSupplyCaps The new supply cap values in underlying to be set. A value of 0 corresponds to unlimited supplying.
*/
function _setMarketSupplyCaps(
CERC20[] memory cTokens,
uint256[] calldata newSupplyCaps
) external requiresAuth {
_setMarketSupplyCapsInternal(cTokens, newSupplyCaps);
}
function _setMarketSupplyCapsByUnderlying(
address[] calldata underlyings,
uint256[] calldata newSupplyCaps
) external requiresAuth {
_setMarketSupplyCapsInternal(
_underlyingToCTokens(underlyings),
newSupplyCaps
);
}
function _setMarketSupplyCapsInternal(
CERC20[] memory cTokens,
uint256[] calldata newSupplyCaps
) internal {
comptroller._setMarketSupplyCaps(cTokens, newSupplyCaps);
}
function _underlyingToCTokens(address[] calldata underlyings)
internal
view
returns (CERC20[] memory)
{
CERC20[] memory cTokens = new CERC20[](underlyings.length);
for (uint256 i = 0; i < underlyings.length; i++) {
CERC20 cToken = comptroller.cTokensByUnderlying(ERC20(underlyings[i]));
require(address(cToken) != address(0), "cToken doesn't exist");
cTokens[i] = CERC20(cToken);
}
return cTokens;
}
/**
* @notice Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
* @param cTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(
CERC20[] memory cTokens,
uint256[] calldata newBorrowCaps
) external requiresAuth {
_setMarketBorrowCapsInternal(cTokens, newBorrowCaps);
}
function _setMarketBorrowCapsInternal(
CERC20[] memory cTokens,
uint256[] calldata newBorrowCaps
) internal {
comptroller._setMarketBorrowCaps(cTokens, newBorrowCaps);
}
function _setMarketBorrowCapsByUnderlying(
address[] calldata underlyings,
uint256[] calldata newBorrowCaps
) external requiresAuth {
_setMarketBorrowCapsInternal(
_underlyingToCTokens(underlyings),
newBorrowCaps
);
}
/**
* @notice Admin function to change the Borrow Cap Guardian
* @param newBorrowCapGuardian The address of the new Borrow Cap Guardian
*/
function _setBorrowCapGuardian(address newBorrowCapGuardian)
external
requiresAuth
{
comptroller._setBorrowCapGuardian(newBorrowCapGuardian);
}
// ************ PAUSE GUARDIAN FUNCTIONS ************
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian)
external
requiresAuth
returns (uint256)
{
return comptroller._setPauseGuardian(newPauseGuardian);
}
function _setMintPausedByUnderlying(ERC20 underlying, bool state)
external
requiresAuth
returns (bool)
{
CERC20 cToken = comptroller.cTokensByUnderlying(underlying);
require(address(cToken) != address(0), "cToken doesn't exist");
return _setMintPausedInternal(cToken, state);
}
function _setMintPaused(CERC20 cToken, bool state)
external
requiresAuth
returns (bool)
{
return _setMintPausedInternal(cToken, state);
}
function _setMintPausedInternal(CERC20 cToken, bool state)
internal
returns (bool)
{
return comptroller._setMintPaused(cToken, state);
}
function _setBorrowPausedByUnderlying(ERC20 underlying, bool state)
external
requiresAuth
returns (bool)
{
CERC20 cToken = comptroller.cTokensByUnderlying(underlying);
require(address(cToken) != address(0), "cToken doesn't exist");
return _setBorrowPausedInternal(cToken, state);
}
function _setBorrowPausedInternal(CERC20 cToken, bool state)
internal
returns (bool)
{
return comptroller._setBorrowPaused(cToken, state);
}
function _setBorrowPaused(CERC20 cToken, bool state)
external
requiresAuth
returns (bool)
{
return _setBorrowPausedInternal(CERC20(cToken), state);
}
function _setTransferPaused(bool state)
external
requiresAuth
returns (bool)
{
return comptroller._setTransferPaused(state);
}
function _setSeizePaused(bool state)
external
requiresAuth
returns (bool)
{
return comptroller._setSeizePaused(state);
}
// ************ FUSE ADMIN FUNCTIONS ************
function oracleAdd(
address[] calldata underlyings,
address[] calldata _oracles
) external requiresAuth {
comptroller.oracle().add(underlyings, _oracles);
}
function oracleChangeAdmin(address newAdmin) external requiresAuth {
comptroller.oracle().changeAdmin(newAdmin);
}
function _addRewardsDistributor(address distributor)
external
requiresAuth
{
if (comptroller._addRewardsDistributor(distributor) != 0)
revert ComptrollerError();
}
function _setWhitelistEnforcement(bool enforce)
external
requiresAuth
{
if (comptroller._setWhitelistEnforcement(enforce) != 0)
revert ComptrollerError();
}
function _setWhitelistStatuses(
address[] calldata suppliers,
bool[] calldata statuses
) external requiresAuth {
if (comptroller._setWhitelistStatuses(suppliers, statuses) != 0)
revert ComptrollerError();
}
function _setPriceOracle(address newOracle) public requiresAuth {
if (comptroller._setPriceOracle(newOracle) != 0)
revert ComptrollerError();
}
function _setCloseFactor(uint256 newCloseFactorMantissa)
external
requiresAuth
{
if (comptroller._setCloseFactor(newCloseFactorMantissa) != 0)
revert ComptrollerError();
}
function _setCollateralFactor(
CERC20 cToken,
uint256 newCollateralFactorMantissa
) public requiresAuth {
if (
comptroller._setCollateralFactor(
cToken,
newCollateralFactorMantissa
) != 0
) revert ComptrollerError();
}
function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa)
external
requiresAuth
{
if (
comptroller._setLiquidationIncentive(
newLiquidationIncentiveMantissa
) != 0
) revert ComptrollerError();
}
function _deployMarket(
address underlying,
address irm,
string calldata name,
string calldata symbol,
address impl,
bytes calldata data,
uint256 reserveFactor,
uint256 adminFee,
uint256 collateralFactorMantissa
) external requiresAuth {
bytes memory constructorData = abi.encode(
underlying,
address(comptroller),
irm,
name,
symbol,
impl,
data,
reserveFactor,
adminFee
);
if (
comptroller._deployMarket(
false,
constructorData,
collateralFactorMantissa
) != 0
) revert ComptrollerError();
}
function _unsupportMarket(CERC20 cToken) external requiresAuth {
if (comptroller._unsupportMarket(cToken) != 0)
revert ComptrollerError();
}
function _toggleAutoImplementations(bool enabled)
public
requiresAuth
{
if (comptroller._toggleAutoImplementations(enabled) != 0)
revert ComptrollerError();
}
function scheduleSetPendingAdmin(address newPendingAdmin) public requiresAuth {
_schedule(address(this), abi.encodeWithSelector(this._setPendingAdmin.selector, newPendingAdmin));
}
function _setPendingAdmin(address newPendingAdmin)
public
{
require(msg.sender == address(timelock), "timelock");
if (comptroller._setPendingAdmin(newPendingAdmin) != 0)
revert ComptrollerError();
}
function _acceptAdmin() public {
if (comptroller._acceptAdmin() != 0) revert ComptrollerError();
}
// ************ TIMELOCK ADMIN FUNCTIONS ************
function schedule(address target, bytes memory data) public requiresAuth {
_schedule(target, data);
}
function _schedule(address target, bytes memory data) internal {
timelock.schedule(target, 0, data, bytes32(0), keccak256(abi.encodePacked(block.timestamp)), 15 days);
}
function cancel(bytes32 id) public requiresAuth {
timelock.cancel(id);
}
function execute(address target, bytes memory data, bytes32 salt) public requiresAuth {
timelock.execute(target, 0, data, bytes32(0), salt);
}
}
/// @title Fei
/// @author Fei Protocol
/// @notice Minimal interface for the Fei token.
abstract contract Fei is ERC20 {
function mint(address to, uint256 amount) external virtual;
}
/// @title Turbo Gibber
/// @author Transmissions11
/// @notice Atomic impounder module.
contract TurboGibber is Auth, ReentrancyGuard, ENSReverseRecordAuth {
using SafeTransferLib for Fei;
/*///////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
/// @notice The Master contract.
/// @dev Used to validate Safes are legitimate.
TurboMaster public immutable master;
/// @notice The Fei token on the network.
Fei public immutable fei;
/// @notice The Fei cToken in the Turbo Fuse Pool.
CERC20 public immutable feiTurboCToken;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Creates a new Turbo Gibber contract.
/// @param _master The Master of the Gibber.
/// @param _owner The owner of the Gibber.
/// @param _authority The Authority of the Gibber.
constructor(
TurboMaster _master,
address _owner,
Authority _authority
) Auth(_owner, _authority) {
master = _master;
fei = Fei(address(master.fei()));
feiTurboCToken = master.pool().cTokensByUnderlying(fei);
// Preemptively approve to the Fei cToken in the Turbo Fuse Pool.
fei.safeApprove(address(feiTurboCToken), type(uint256).max);
}
/*///////////////////////////////////////////////////////////////
ATOMIC IMPOUND LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Emitted an impound is executed.
/// @param user The user who executed the impound.
/// @param safe The Safe that was impounded.
/// @param feiAmount The amount of Fei that was repaid.
/// @param assetAmount The amount of assets impounded.
event ImpoundExecuted(address indexed user, TurboSafe indexed safe, uint256 feiAmount, uint256 assetAmount);
/// @notice Impound a safe.
/// @param safe The Safe to be impounded.
/// @param feiAmount The amount of Fei to repay the Safe's debt with.
/// @param assetAmount The amount of assets to impound.
/// @param to The recipient of the impounded collateral tokens.
function impound(
TurboSafe safe,
uint256 feiAmount,
uint256 assetAmount,
address to
) external requiresAuth nonReentrant {
// Ensure the Safe is registered with the Master.
require(master.getSafeId(safe) != 0);
emit ImpoundExecuted(msg.sender, safe, feiAmount, assetAmount);
// Mint the Fei amount requested.
fei.mint(address(this), feiAmount);
// Repay the safe's Fei debt with the minted Fei, ensuring to catch cToken errors.
require(feiTurboCToken.repayBorrowBehalf(address(safe), feiAmount) == 0, "REPAY_FAILED");
// Impound some of the safe's collateral and send it to the chosen recipient.
safe.gib(to, assetAmount);
}
/// @notice Impound all of a safe's collateral.
/// @param safe The Safe to be impounded.
/// @param to The recipient of the impounded collateral tokens.
function impoundAll(TurboSafe safe, address to) external requiresAuth nonReentrant {
// Ensure the Safe is registered with the Master.
require(master.getSafeId(safe) != 0);
// Get the asset cToken in the Turbo Fuse Pool.
CERC20 assetTurboCToken = safe.assetTurboCToken();
// Get the amount of assets to impound from the Safe.
uint256 assetAmount = assetTurboCToken.balanceOfUnderlying(address(safe));
// Get the amount of Fei debt to repay for the Safe.
uint256 feiAmount = feiTurboCToken.borrowBalanceCurrent(address(safe));
emit ImpoundExecuted(msg.sender, safe, feiAmount, assetAmount);
// Mint the Fei amount requested.
fei.mint(address(this), feiAmount);
// Repay the safe's Fei debt with the minted Fei, ensuring to catch cToken errors.
require(feiTurboCToken.repayBorrowBehalf(address(safe), feiAmount) == 0, "REPAY_FAILED");
// Impound all of the safe's collateral and send it to the chosen recipient.
safe.gib(to, assetAmount);
}
}
/// @title Turbo Savior
/// @author Transmissions11
/// @notice Safe repayment module.
contract TurboSavior is Auth, ReentrancyGuard, ENSReverseRecordAuth {
using FixedPointMathLib for uint256;
/*///////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
/// @notice The Master contract.
/// @dev Used to validate Safes are legitimate.
TurboMaster public immutable master;
/// @notice The Fei token on the network.
Fei public immutable fei;
/// @notice The Turbo Fuse Pool used by the Master.
Comptroller public immutable pool;
/// @notice The Fei cToken in the Turbo Fuse Pool.
CERC20 public immutable feiTurboCToken;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Creates a new Turbo Savior contract.
/// @param _master The Master of the Savior.
/// @param _owner The owner of the Savior.
/// @param _authority The Authority of the Savior.
constructor(
TurboMaster _master,
address _owner,
Authority _authority
) Auth(_owner, _authority) {
master = _master;
fei = Fei(address(master.fei()));
pool = master.pool();
feiTurboCToken = pool.cTokensByUnderlying(fei);
}
/*///////////////////////////////////////////////////////////////
LINE LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice The minimum percentage debt must make up of the borrow limit for a Safe to be saved.
/// @dev A fixed point number where 1e18 represents 100% and 0 represents 0%.
uint256 public minDebtPercentageForSaving;
/// @notice Emitted when the minimum debt percentage for saving is updated.
/// @param newDefaultFeePercentage The new minimum debt percentage for saving.
event MinDebtPercentageForSavingUpdated(address indexed user, uint256 newDefaultFeePercentage);
/// @notice Sets the minimum debt percentage.
/// @param newMinDebtPercentageForSaving The new minimum debt percentage.
function setMinDebtPercentageForSaving(uint256 newMinDebtPercentageForSaving) external requiresAuth {
// A minimum debt percentage over 100% makes no sense.
require(newMinDebtPercentageForSaving <= 1e18, "PERCENT_TOO_HIGH");
// Update the minimum debt percentage.
minDebtPercentageForSaving = newMinDebtPercentageForSaving;
emit MinDebtPercentageForSavingUpdated(msg.sender, newMinDebtPercentageForSaving);
}
/*///////////////////////////////////////////////////////////////
SAVE LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Emitted a save is executed.
/// @param user The user who executed the save.
/// @param safe The Safe that was saved.
/// @param vault The Vault that was lessed.
/// @param feiAmount The amount of Fei that was lessed.
event SafeSaved(address indexed user, TurboSafe indexed safe, ERC4626 indexed vault, uint256 feiAmount);
/// @notice Save a Safe (call less on owner's behalf to prevent liquidation).
/// @param safe The Safe to be saved.
/// @param vault The Vault to less from.
/// @param feiAmount The amount of Fei to less from the Safe.
function save(
TurboSafe safe,
ERC4626 vault,
uint256 feiAmount
) external requiresAuth nonReentrant {
// Ensure the Safe is registered with the Master.
require(master.getSafeId(safe) != 0);
emit SafeSaved(msg.sender, safe, vault, feiAmount);
// Cache the Safe's collateral asset.
CERC20 assetTurboCToken = safe.assetTurboCToken();
// Cache the pool's current oracle.
PriceFeed oracle = pool.oracle();
// Get the Safe's asset's collateral factor in the Turbo Fuse Pool.
(, uint256 collateralFactor) = pool.markets(assetTurboCToken);
// Compute the value of the Safe's collateral. Rounded down to favor saving.
uint256 borrowLimit = assetTurboCToken
.balanceOf(address(safe))
.mulWadDown(assetTurboCToken.exchangeRateStored())
.mulWadDown(collateralFactor)
.mulWadDown(oracle.getUnderlyingPrice(assetTurboCToken));
// Compute the value of the Safe's debt. Rounding up to favor saving them.
uint256 debtValue = feiTurboCToken.borrowBalanceCurrent(address(safe)).mulWadUp(
oracle.getUnderlyingPrice(feiTurboCToken)
);
// Ensure the Safe's debt percentage is high enough to justify saving, otherwise revert.
require(
borrowLimit != 0 && debtValue.divWadUp(borrowLimit) >= minDebtPercentageForSaving,
"DEBT_PERCENT_TOO_LOW"
);
// Less the Fei from the Safe.
safe.less(vault, feiAmount);
}
}
/// @title ERC4626 interface
/// @author Fei Protocol
/// See: https://eips.ethereum.org/EIPS/eip-4626
abstract contract IERC4626 is ERC20 {
/*////////////////////////////////////////////////////////
Events
////////////////////////////////////////////////////////*/
/// @notice `sender` has exchanged `assets` for `shares`,
/// and transferred those `shares` to `receiver`.
event Deposit(
address indexed sender,
address indexed receiver,
uint256 assets,
uint256 shares
);
/// @notice `sender` has exchanged `shares` for `assets`,
/// and transferred those `assets` to `receiver`.
event Withdraw(
address indexed sender,
address indexed receiver,
uint256 assets,
uint256 shares
);
/*////////////////////////////////////////////////////////
Vault properties
////////////////////////////////////////////////////////*/
/// @notice The address of the underlying ERC20 token used for
/// the Vault for accounting, depositing, and withdrawing.
function asset() external view virtual returns(address asset);
/// @notice Total amount of the underlying asset that
/// is "managed" by Vault.
function totalAssets() external view virtual returns(uint256 totalAssets);
/*////////////////////////////////////////////////////////
Deposit/Withdrawal Logic
////////////////////////////////////////////////////////*/
/// @notice Mints `shares` Vault shares to `receiver` by
/// depositing exactly `assets` of underlying tokens.
function deposit(uint256 assets, address receiver) external virtual returns(uint256 shares);
/// @notice Mints exactly `shares` Vault shares to `receiver`
/// by depositing `assets` of underlying tokens.
function mint(uint256 shares, address receiver) external virtual returns(uint256 assets);
/// @notice Redeems `shares` from `owner` and sends `assets`
/// of underlying tokens to `receiver`.
function withdraw(uint256 assets, address receiver, address owner) external virtual returns(uint256 shares);
/// @notice Redeems `shares` from `owner` and sends `assets`
/// of underlying tokens to `receiver`.
function redeem(uint256 shares, address receiver, address owner) external virtual returns(uint256 assets);
/*////////////////////////////////////////////////////////
Vault Accounting Logic
////////////////////////////////////////////////////////*/
/// @notice The amount of shares that the vault would
/// exchange for the amount of assets provided, in an
/// ideal scenario where all the conditions are met.
function convertToShares(uint256 assets) external view virtual returns(uint256 shares);
/// @notice The amount of assets that the vault would
/// exchange for the amount of shares provided, in an
/// ideal scenario where all the conditions are met.
function convertToAssets(uint256 shares) external view virtual returns(uint256 assets);
/// @notice Total number of underlying assets that can
/// be deposited by `owner` into the Vault, where `owner`
/// corresponds to the input parameter `receiver` of a
/// `deposit` call.
function maxDeposit(address owner) external view virtual returns(uint256 maxAssets);
/// @notice Allows an on-chain or off-chain user to simulate
/// the effects of their deposit at the current block, given
/// current on-chain conditions.
function previewDeposit(uint256 assets) external view virtual returns(uint256 shares);
/// @notice Total number of underlying shares that can be minted
/// for `owner`, where `owner` corresponds to the input
/// parameter `receiver` of a `mint` call.
function maxMint(address owner) external view virtual returns(uint256 maxShares);
/// @notice Allows an on-chain or off-chain user to simulate
/// the effects of their mint at the current block, given
/// current on-chain conditions.
function previewMint(uint256 shares) external view virtual returns(uint256 assets);
/// @notice Total number of underlying assets that can be
/// withdrawn from the Vault by `owner`, where `owner`
/// corresponds to the input parameter of a `withdraw` call.
function maxWithdraw(address owner) external view virtual returns(uint256 maxAssets);
/// @notice Allows an on-chain or off-chain user to simulate
/// the effects of their withdrawal at the current block,
/// given current on-chain conditions.
function previewWithdraw(uint256 assets) external view virtual returns(uint256 shares);
/// @notice Total number of underlying shares that can be
/// redeemed from the Vault by `owner`, where `owner` corresponds
/// to the input parameter of a `redeem` call.
function maxRedeem(address owner) external view virtual returns(uint256 maxShares);
/// @notice Allows an on-chain or off-chain user to simulate
/// the effects of their redeemption at the current block,
/// given current on-chain conditions.
function previewRedeem(uint256 shares) external view virtual returns(uint256 assets);
}
/**
@title ERC4626Router Base Interface
@author joeysantoro
@notice A canonical router between ERC4626 Vaults https://eips.ethereum.org/EIPS/eip-4626
The base router is a multicall style router inspired by Uniswap v3 with built-in features for permit, WETH9 wrap/unwrap, and ERC20 token pulling/sweeping/approving.
It includes methods for the four mutable ERC4626 functions deposit/mint/withdraw/redeem as well.
These can all be arbitrarily composed using the multicall functionality of the router.
NOTE the router is capable of pulling any approved token from your wallet. This is only possible when your address is msg.sender, but regardless be careful when interacting with the router or ERC4626 Vaults.
The router makes no special considerations for unique ERC20 implementations such as fee on transfer.
There are no built in protections for unexpected behavior beyond enforcing the minSharesOut is received.
*/
interface IERC4626RouterBase {
/************************** Errors **************************/
/// @notice thrown when amount of assets received is below the min set by caller
error MinAmountError();
/// @notice thrown when amount of shares received is below the min set by caller
error MinSharesError();
/// @notice thrown when amount of assets received is above the max set by caller
error MaxAmountError();
/// @notice thrown when amount of shares received is above the max set by caller
error MaxSharesError();
/************************** Mint **************************/
/**
@notice mint `shares` from an ERC4626 vault.
@param vault The ERC4626 vault to mint shares from.
@param to The destination of ownership shares.
@param shares The amount of shares to mint from `vault`.
@param maxAmountIn The max amount of assets used to mint.
@return amountIn the amount of assets used to mint by `to`.
@dev throws MaxAmountError
*/
function mint(
IERC4626 vault,
address to,
uint256 shares,
uint256 maxAmountIn
) external payable returns (uint256 amountIn);
/************************** Deposit **************************/
/**
@notice deposit `amount` to an ERC4626 vault.
@param vault The ERC4626 vault to deposit assets to.
@param to The destination of ownership shares.
@param amount The amount of assets to deposit to `vault`.
@param minSharesOut The min amount of `vault` shares received by `to`.
@return sharesOut the amount of shares received by `to`.
@dev throws MinSharesError
*/
function deposit(
IERC4626 vault,
address to,
uint256 amount,
uint256 minSharesOut
) external payable returns (uint256 sharesOut);
/************************** Withdraw **************************/
/**
@notice withdraw `amount` from an ERC4626 vault.
@param vault The ERC4626 vault to withdraw assets from.
@param to The destination of assets.
@param amount The amount of assets to withdraw from vault.
@param minSharesOut The min amount of shares received by `to`.
@return sharesOut the amount of shares received by `to`.
@dev throws MaxSharesError
*/
function withdraw(
IERC4626 vault,
address to,
uint256 amount,
uint256 minSharesOut
) external payable returns (uint256 sharesOut);
/************************** Redeem **************************/
/**
@notice redeem `shares` shares from an ERC4626 vault.
@param vault The ERC4626 vault to redeem shares from.
@param to The destination of assets.
@param shares The amount of shares to redeem from vault.
@param minAmountOut The min amount of assets received by `to`.
@return amountOut the amount of assets received by `to`.
@dev throws MinAmountError
*/
function redeem(
IERC4626 vault,
address to,
uint256 shares,
uint256 minAmountOut
) external payable returns (uint256 amountOut);
}
// forked from https://github.com/Uniswap/v3-periphery/blob/main/contracts/interfaces/ISelfPermit.sol
/// @title Self Permit
/// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route
interface ISelfPermit {
/// @notice Permits this contract to spend a given token from `msg.sender`
/// @dev The `owner` is always msg.sender and the `spender` is always address(this).
/// @param token The address of the token spent
/// @param value The amount that can be spent of token
/// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function selfPermit(
address token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
/// @notice Permits this contract to spend a given token from `msg.sender`
/// @dev The `owner` is always msg.sender and the `spender` is always address(this).
/// Can be used instead of #selfPermit to prevent calls from failing due to a frontrun of a call to #selfPermit
/// @param token The address of the token spent
/// @param value The amount that can be spent of token
/// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function selfPermitIfNecessary(
address token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
/// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter
/// @dev The `owner` is always msg.sender and the `spender` is always address(this)
/// @param token The address of the token spent
/// @param nonce The current nonce of the owner
/// @param expiry The timestamp at which the permit is no longer valid
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function selfPermitAllowed(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
/// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter
/// @dev The `owner` is always msg.sender and the `spender` is always address(this)
/// Can be used instead of #selfPermitAllowed to prevent calls from failing due to a frontrun of a call to #selfPermitAllowed.
/// @param token The address of the token spent
/// @param nonce The current nonce of the owner
/// @param expiry The timestamp at which the permit is no longer valid
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function selfPermitAllowedIfNecessary(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
}
// forked from https://github.com/Uniswap/v3-periphery/blob/main/contracts/interfaces/external/IERC20PermitAllowed.sol
/// @title Interface for permit
/// @notice Interface used by DAI/CHAI for permit
interface IERC20PermitAllowed {
/// @notice Approve the spender to spend some tokens via the holder signature
/// @dev This is the permit interface used by DAI and CHAI
/// @param holder The address of the token holder, the token owner
/// @param spender The address of the token spender
/// @param nonce The holder's nonce, increases at each call to permit
/// @param expiry The timestamp at which the permit is no longer valid
/// @param allowed Boolean that sets approval amount, true for type(uint256).max and false for 0
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address holder,
address spender,
uint256 nonce,
uint256 expiry,
bool allowed,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
/// @title Self Permit
/// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route
/// @dev These functions are expected to be embedded in multicalls to allow EOAs to approve a contract and call a function
/// that requires an approval in a single transaction.
abstract contract SelfPermit is ISelfPermit {
/// @inheritdoc ISelfPermit
function selfPermit(
address token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public payable override {
ERC20(token).permit(msg.sender, address(this), value, deadline, v, r, s);
}
/// @inheritdoc ISelfPermit
function selfPermitIfNecessary(
address token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable override {
if (ERC20(token).allowance(msg.sender, address(this)) < value) selfPermit(token, value, deadline, v, r, s);
}
/// @inheritdoc ISelfPermit
function selfPermitAllowed(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public payable override {
IERC20PermitAllowed(token).permit(msg.sender, address(this), nonce, expiry, true, v, r, s);
}
/// @inheritdoc ISelfPermit
function selfPermitAllowedIfNecessary(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external payable override {
if (ERC20(token).allowance(msg.sender, address(this)) < type(uint256).max)
selfPermitAllowed(token, nonce, expiry, v, r, s);
}
}// forked from https://github.com/Uniswap/v3-periphery/blob/main/contracts/base/Multicall.sol
// forked from https://github.com/Uniswap/v3-periphery/blob/main/contracts/interfaces/IMulticall.sol
/// @title Multicall interface
/// @notice Enables calling multiple methods in a single call to the contract
interface IMulticall {
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
/// @dev The `msg.value` should not be trusted for any method callable from multicall.
/// @param data The encoded function data for each of the calls to make to this contract
/// @return results The results from each of the calls passed in via data
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}
/// @title Multicall
/// @notice Enables calling multiple methods in a single call to the contract
abstract contract Multicall is IMulticall {
/// @inheritdoc IMulticall
function multicall(bytes[] calldata data) public payable override returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
// Next 5 lines from https://ethereum.stackexchange.com/a/83577
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
results[i] = result;
}
}
}/**
@title Periphery Payments
@notice Immutable state used by periphery contracts
Largely Forked from https://github.com/Uniswap/v3-periphery/blob/main/contracts/base/PeripheryPayments.sol
Changes:
* no interface
* no inheritdoc
* add immutable WETH9 in constructor instead of PeripheryImmutableState
* receive from any address
* Solmate interfaces and transfer lib
* casting
* add approve, wrapWETH9 and pullToken
*/
abstract contract PeripheryPayments {
using SafeTransferLib for *;
IWETH9 public immutable WETH9;
constructor(IWETH9 _WETH9) {
WETH9 = _WETH9;
}
receive() external payable {}
function approve(ERC20 token, address to, uint256 amount) public payable {
token.safeApprove(to, amount);
}
function unwrapWETH9(uint256 amountMinimum, address recipient) public payable {
uint256 balanceWETH9 = WETH9.balanceOf(address(this));
require(balanceWETH9 >= amountMinimum, 'Insufficient WETH9');
if (balanceWETH9 > 0) {
WETH9.withdraw(balanceWETH9);
recipient.safeTransferETH(balanceWETH9);
}
}
function wrapWETH9() public payable {
if (address(this).balance > 0) WETH9.deposit{value: address(this).balance}(); // wrap everything
}
function pullToken(ERC20 token, uint256 amount, address recipient) public payable {
token.safeTransferFrom(msg.sender, recipient, amount);
}
function sweepToken(
ERC20 token,
uint256 amountMinimum,
address recipient
) public payable {
uint256 balanceToken = token.balanceOf(address(this));
require(balanceToken >= amountMinimum, 'Insufficient token');
if (balanceToken > 0) {
token.safeTransfer(recipient, balanceToken);
}
}
function refundETH() external payable {
if (address(this).balance > 0) SafeTransferLib.safeTransferETH(msg.sender, address(this).balance);
}
}
abstract contract IWETH9 is ERC20 {
/// @notice Deposit ether to get wrapped ether
function deposit() external payable virtual;
/// @notice Withdraw wrapped ether to get ether
function withdraw(uint256) external virtual;
}
/// @title ERC4626 Router Base Contract
/// @author joeysantoro
abstract contract ERC4626RouterBase is IERC4626RouterBase, SelfPermit, Multicall, PeripheryPayments {
using SafeTransferLib for ERC20;
/// @inheritdoc IERC4626RouterBase
function mint(
IERC4626 vault,
address to,
uint256 shares,
uint256 maxAmountIn
) public payable virtual override returns (uint256 amountIn) {
if ((amountIn = vault.mint(shares, to)) > maxAmountIn) {
revert MaxAmountError();
}
}
/// @inheritdoc IERC4626RouterBase
function deposit(
IERC4626 vault,
address to,
uint256 amount,
uint256 minSharesOut
) public payable virtual override returns (uint256 sharesOut) {
if ((sharesOut = vault.deposit(amount, to)) < minSharesOut) {
revert MinSharesError();
}
}
/// @inheritdoc IERC4626RouterBase
function withdraw(
IERC4626 vault,
address to,
uint256 amount,
uint256 maxSharesOut
) public payable virtual override returns (uint256 sharesOut) {
if ((sharesOut = vault.withdraw(amount, to, msg.sender)) > maxSharesOut) {
revert MaxSharesError();
}
}
/// @inheritdoc IERC4626RouterBase
function redeem(
IERC4626 vault,
address to,
uint256 shares,
uint256 minAmountOut
) public payable virtual override returns (uint256 amountOut) {
if ((amountOut = vault.redeem(shares, to, msg.sender)) < minAmountOut) {
revert MinAmountError();
}
}
}
/**
@title a router which can perform multiple Turbo actions between Master and the Safes
@notice routes custom users flows between actions on the master and safes.
Extends the ERC4626RouterBase to allow for flexible combinations of actions involving ERC4626 and permit, weth, and Turbo specific actions.
Safe Creation has functions bundled with deposit (and optionally boost) because a newly created Safe address can only be known at runtime.
The caller is always atomically given the owner role of a new safe.
Authentication requires the caller to be the owner of the Safe to perform any ERC4626 method or TurboSafe requiresAuth method.
Assumes the Safe's authority gives permission to call these functions to the TurboRouter.
*/
contract TurboRouter is ERC4626RouterBase, ENSReverseRecordAuth {
using SafeTransferLib for ERC20;
TurboMaster public immutable master;
constructor (TurboMaster _master, address _owner, Authority _authority, IWETH9 weth) Auth(_owner, _authority) PeripheryPayments(weth) {
master = _master;
}
modifier authenticate(address target) {
require(msg.sender == Auth(target).owner() || Auth(target).authority().canCall(msg.sender, target, msg.sig), "NOT_AUTHED");
_;
}
function createSafe(ERC20 underlying) external returns (TurboSafe safe) {
(safe, ) = master.createSafe(underlying);
safe.setOwner(msg.sender);
}
function createSafeAndDeposit(ERC20 underlying, address to, uint256 amount, uint256 minSharesOut) external returns (TurboSafe safe) {
(safe, ) = master.createSafe(underlying);
// approve max from router to save depositor gas in future.
approve(underlying, address(safe), type(uint256).max);
super.deposit(IERC4626(address(safe)), to, amount, minSharesOut);
safe.setOwner(msg.sender);
}
function createSafeAndDepositAndBoost(
ERC20 underlying,
address to,
uint256 amount,
uint256 minSharesOut,
ERC4626 boostedVault,
uint256 boostedFeiAmount
) public returns (TurboSafe safe) {
(safe, ) = master.createSafe(underlying);
// approve max from router to save depositor gas in future.
approve(underlying, address(safe), type(uint256).max);
super.deposit(IERC4626(address(safe)), to, amount, minSharesOut);
safe.boost(boostedVault, boostedFeiAmount);
safe.setOwner(msg.sender);
}
function createSafeAndDepositAndBoostMany(
ERC20 underlying,
address to,
uint256 amount,
uint256 minSharesOut,
ERC4626[] calldata boostedVaults,
uint256[] calldata boostedFeiAmounts
) public returns (TurboSafe safe) {
(safe, ) = master.createSafe(underlying);
// approve max from router to save depositor gas in future.
approve(underlying, address(safe), type(uint256).max);
super.deposit(IERC4626(address(safe)), to, amount, minSharesOut);
unchecked {
require(boostedVaults.length == boostedFeiAmounts.length, "length");
for (uint256 i = 0; i < boostedVaults.length; i++) {
safe.boost(boostedVaults[i], boostedFeiAmounts[i]);
}
}
safe.setOwner(msg.sender);
}
function deposit(IERC4626 safe, address to, uint256 amount, uint256 minSharesOut)
public
payable
override
authenticate(address(safe))
returns (uint256)
{
return super.deposit(safe, to, amount, minSharesOut);
}
function mint(IERC4626 safe, address to, uint256 shares, uint256 maxAmountIn)
public
payable
override
authenticate(address(safe))
returns (uint256)
{
return super.mint(safe, to, shares, maxAmountIn);
}
function withdraw(IERC4626 safe, address to, uint256 amount, uint256 maxSharesOut)
public
payable
override
authenticate(address(safe))
returns (uint256)
{
return super.withdraw(safe, to, amount, maxSharesOut);
}
function redeem(IERC4626 safe, address to, uint256 shares, uint256 minAmountOut)
public
payable
override
authenticate(address(safe))
returns (uint256)
{
return super.redeem(safe, to, shares, minAmountOut);
}
function slurp(TurboSafe safe, ERC4626 vault) external authenticate(address(safe)) {
safe.slurp(vault);
}
function boost(TurboSafe safe, ERC4626 vault, uint256 feiAmount) public authenticate(address(safe)) {
safe.boost(vault, feiAmount);
}
function less(TurboSafe safe, ERC4626 vault, uint256 feiAmount) external authenticate(address(safe)) {
safe.less(vault, feiAmount);
}
function lessAll(TurboSafe safe, ERC4626 vault) external authenticate(address(safe)) {
safe.less(vault, vault.maxWithdraw(address(safe)));
}
function sweep(TurboSafe safe, address to, ERC20 token, uint256 amount) external authenticate(address(safe)) {
safe.sweep(to, token, amount);
}
function sweepAll(TurboSafe safe, address to, ERC20 token) external authenticate(address(safe)) {
safe.sweep(to, token, token.balanceOf(address(safe)));
}
function slurpAndLessAll(TurboSafe safe, ERC4626 vault) external authenticate(address(safe)) {
safe.slurp(vault);
safe.less(vault, vault.maxWithdraw(address(safe)));
}
}
/**
@title Turbo Configurer
IS INTENDED FOR MAINNET DEPLOYMENT
This contract is a helper utility to completely configure the turbo system, assuming the contracts are deployed.
The deployment should follow the logic in Deployer.sol.
Each function details its access control assumptions.
*/
contract Configurer {
/// @notice Fei DAO Timelock, to be granted TURBO_ADMIN_ROLE and GOVERN_ROLE
address constant feiDAOTimelock = 0xd51dbA7a94e1adEa403553A8235C302cEbF41a3c;
/// @notice Tribe Guardian, to be granted GUARDIAN_ROLE
address constant guardian = 0xB8f482539F2d3Ae2C9ea6076894df36D1f632775;
ERC20 fei = ERC20(0x956F47F50A910163D8BF957Cf5846D573E7f87CA);
ERC20 tribe = ERC20(0xc7283b66Eb1EB5FB86327f08e1B5816b0720212B);
/******************** ROLES ********************/
/// @notice HIGH CLEARANCE. capable of calling `gib` to impound collateral.
uint8 public constant GIBBER_ROLE = 1;
/// @notice HIGH CLEARANCE. Optional module which can interact with any user's vault by default.
uint8 public constant ROUTER_ROLE = 2;
/// @notice Capable of lessing any vault. Exposed on optional TurboSavior module.
uint8 public constant SAVIOR_ROLE = 3;
/// @notice Operational admin of Turbo, can whitelist collaterals, strategies, and configure most parameters.
uint8 public constant TURBO_ADMIN_ROLE = 4;
/// @notice Pause and security Guardian role
uint8 public constant GUARDIAN_ROLE = 5;
/// @notice HIGH CLEARANCE. Capable of critical governance functionality on TurboAdmin such as oracle upgrades.
uint8 public constant GOVERN_ROLE = 6;
/// @notice limited version of TURBO_ADMIN_ROLE which can manage collateral and vault parameters.
uint8 public constant TURBO_STRATEGIST_ROLE = 7;
/******************** CONFIGURATION ********************/
/// @notice configure the turbo timelock. Requires TIMELOCK_ADMIN_ROLE over timelock.
function configureTimelock(TimelockController turboTimelock, TurboAdmin admin) public {
turboTimelock.grantRole(turboTimelock.TIMELOCK_ADMIN_ROLE(), address(admin));
turboTimelock.grantRole(turboTimelock.EXECUTOR_ROLE(), address(admin));
turboTimelock.grantRole(turboTimelock.PROPOSER_ROLE(), address(admin));
turboTimelock.revokeRole(turboTimelock.TIMELOCK_ADMIN_ROLE(), address(this));
}
/// @notice configure the turbo authority. Requires ownership over turbo authority.
function configureAuthority(MultiRolesAuthority turboAuthority) public {
// GIBBER_ROLE
turboAuthority.setRoleCapability(GIBBER_ROLE, TurboSafe.gib.selector, true);
// TURBO_ADMIN_ROLE
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboSafe.slurp.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboSafe.less.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboMaster.createSafe.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboMaster.setBooster.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboMaster.setClerk.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboMaster.setDefaultSafeAuthority.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboMaster.sweep.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboClerk.setDefaultFeePercentage.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboClerk.setCustomFeePercentageForCollateral.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboClerk.setCustomFeePercentageForSafe.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboBooster.setFreezeStatus.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboBooster.setBoostCapForVault.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboBooster.setBoostCapForCollateral.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboSavior.setMinDebtPercentageForSaving.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setMarketSupplyCaps.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setMarketSupplyCapsByUnderlying.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setMarketBorrowCaps.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setMarketBorrowCapsByUnderlying.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setMintPausedByUnderlying.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setMintPaused.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setBorrowPausedByUnderlying.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setBorrowPaused.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin.oracleAdd.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin.addCollateral.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._deployMarket.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._addRewardsDistributor.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setWhitelistStatuses.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setCloseFactor.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setCollateralFactor.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setLiquidationIncentive.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin.schedule.selector, true);
// GUARDIAN_ROLE
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboSafe.less.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboBooster.setFreezeStatus.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setMarketSupplyCaps.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setMarketSupplyCapsByUnderlying.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setMarketBorrowCaps.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setMarketBorrowCapsByUnderlying.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setMintPausedByUnderlying.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setMintPaused.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setBorrowPausedByUnderlying.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setBorrowPaused.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setTransferPaused.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setSeizePaused.selector, true);
// GOVERN_ROLE
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin._setBorrowCapGuardian.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin._setPauseGuardian.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin.oracleChangeAdmin.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin._setWhitelistEnforcement.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin._setPriceOracle.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin._unsupportMarket.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin._toggleAutoImplementations.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin.scheduleSetPendingAdmin.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin.schedule.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin.cancel.selector, true);
turboAuthority.setPublicCapability(TurboAdmin.execute.selector, true);
// TURBO_STRATEGIST_ROLE
turboAuthority.setRoleCapability(TURBO_STRATEGIST_ROLE, TurboAdmin.addCollateral.selector, true);
turboAuthority.setRoleCapability(TURBO_STRATEGIST_ROLE, TurboAdmin._setMarketSupplyCaps.selector, true);
turboAuthority.setRoleCapability(TURBO_STRATEGIST_ROLE, TurboAdmin._setMarketSupplyCapsByUnderlying.selector, true);
turboAuthority.setRoleCapability(TURBO_STRATEGIST_ROLE, TurboBooster.setBoostCapForVault.selector, true);
turboAuthority.setRoleCapability(TURBO_STRATEGIST_ROLE, TurboBooster.setBoostCapForCollateral.selector, true);
turboAuthority.setPublicCapability(TurboSavior.save.selector, true);
}
/// @notice configure the default authority. Requires ownership over default authority.
function configureDefaultAuthority(MultiRolesAuthority defaultAuthority) public {
// ROUTER_ROLE
defaultAuthority.setRoleCapability(ROUTER_ROLE, TurboSafe.boost.selector, true);
defaultAuthority.setRoleCapability(ROUTER_ROLE, TurboSafe.less.selector, true);
defaultAuthority.setRoleCapability(ROUTER_ROLE, TurboSafe.slurp.selector, true);
defaultAuthority.setRoleCapability(ROUTER_ROLE, TurboSafe.sweep.selector, true);
defaultAuthority.setRoleCapability(ROUTER_ROLE, ERC4626.deposit.selector, true);
defaultAuthority.setRoleCapability(ROUTER_ROLE, ERC4626.mint.selector, true);
defaultAuthority.setRoleCapability(ROUTER_ROLE, ERC4626.withdraw.selector, true);
defaultAuthority.setRoleCapability(ROUTER_ROLE, ERC4626.redeem.selector, true);
// SAVIOR_ROLE
defaultAuthority.setRoleCapability(SAVIOR_ROLE, TurboSafe.less.selector, true);
}
/// @notice configure the turbo pool through turboAdmin. TurboAdmin requires pool ownership, and Configurer requires TURBO_ADMIN_ROLE.
function configurePool(TurboAdmin turboAdmin, TurboBooster booster) public {
turboAdmin._deployMarket(
address(fei),
turboAdmin.ZERO_IRM(),
"Turbo Fei",
"fFEI",
turboAdmin.CTOKEN_IMPL(),
new bytes(0),
0,
0,
0
);
turboAdmin.addCollateral(
address(tribe),
"Turbo Tribe",
"fTRIBE",
60e16,
50_000_000e18
);
booster.setBoostCapForCollateral(tribe, 2_000_000e18); // 1M boost cap TRIBE
address[] memory users = new address[](1);
users[0] = feiDAOTimelock;
bool[] memory enabled = new bool[](1);
enabled[0] = true;
turboAdmin._setWhitelistStatuses(users, enabled);
}
/// @notice requires TURBO_ADMIN_ROLE.
function configureClerk(TurboClerk clerk) public {
clerk.setDefaultFeePercentage(75e16); // 75% default revenue split
}
/// @notice requires TURBO_ADMIN_ROLE.
function configureSavior(TurboSavior savior) public {
savior.setMinDebtPercentageForSaving(80e16); // 80%
}
/// @notice requires ownership of Turbo Authority and default authority.
function configureRoles(
MultiRolesAuthority turboAuthority,
MultiRolesAuthority defaultAuthority,
TurboRouter router,
TurboSavior savior,
TurboGibber gibber
) public {
defaultAuthority.setUserRole(address(router), ROUTER_ROLE, true);
defaultAuthority.setUserRole(address(savior), SAVIOR_ROLE, true);
turboAuthority.setUserRole(address(gibber), GIBBER_ROLE, true);
}
/// @notice requires TURBO_ADMIN_ROLE and ownership over Turbo Authority.
function configureMaster(
TurboMaster master,
TurboClerk clerk,
TurboBooster booster,
TurboAdmin admin,
MultiRolesAuthority defaultAuthority
) public {
MultiRolesAuthority turboAuthority = MultiRolesAuthority(address(master.authority()));
turboAuthority.setUserRole(address(master), TURBO_ADMIN_ROLE, true);
turboAuthority.setUserRole(address(admin), TURBO_ADMIN_ROLE, true);
turboAuthority.setUserRole(address(feiDAOTimelock), TURBO_ADMIN_ROLE, true);
turboAuthority.setUserRole(address(feiDAOTimelock), GOVERN_ROLE, true);
turboAuthority.setUserRole(address(guardian), GUARDIAN_ROLE, true);
master.setClerk(clerk);
master.setBooster(booster);
master.setDefaultSafeAuthority(defaultAuthority);
}
function configureAdmin(MultiRolesAuthority turboAuthority, Comptroller pool, TurboAdmin admin) public {
// temporarily assume ownership of pool (required by deployer)
pool._acceptAdmin();
// Temporarily grant the deployer the turbo admin role for setup
turboAuthority.setUserRole(address(this), TURBO_ADMIN_ROLE, true);
pool._setPendingAdmin(address(admin));
admin._acceptAdmin();
}
function resetOwnership(
MultiRolesAuthority defaultAuthority,
MultiRolesAuthority turboAuthority,
TimelockController turboTimelock,
address admin
) public {
if (admin != address(0)) {
turboAuthority.setUserRole(admin, TURBO_ADMIN_ROLE, true);
}
turboAuthority.setUserRole(address(this), TURBO_ADMIN_ROLE, false);
turboAuthority.setOwner(address(turboTimelock));
defaultAuthority.setOwner(address(turboTimelock));
}
} | @notice Deposit an amount of underlying tokens to the CERC20. @param underlyingAmount Amount of underlying tokens to deposit. @return An error code or zero if there was no error in the deposit. @notice Borrow an amount of underlying tokens from the CERC20. @param underlyingAmount Amount of underlying tokens to borrow. @return An error code or zero if there was no error in the borrow. @notice Repay an amount of underlying tokens to the CERC20. @param underlyingAmount Amount of underlying tokens to repay. @return An error code or zero if there was no error in the repay. @notice Returns the underlying balance of a specific user. @param user The user who's balance the CERC20 will retrieve. @return The amount of underlying tokens the user is entitled to. @notice Returns the amount of underlying tokens a cToken redeemable for. @return The amount of underlying tokens a cToken is redeemable for. @notice Withdraw a specific amount of underlying tokens from the CERC20. @param underlyingAmount Amount of underlying tokens to withdraw. @return An error code or zero if there was no error in the withdraw. @notice Return teh current borrow balance of a user in the CERC20. @param user The user to get the borrow balance for. @return The current borrow balance of the user. @notice Repay a user's borrow on their behalf. @param user The user who's borrow to repay. @param underlyingAmount The amount of debt to repay. @return An error code or zero if there was no error in the repayBorrowBehalf. @notice Price Feed @author Compound Labs @notice Minimal cToken price feed interface. | interface PriceFeed {
function getUnderlyingPrice(CERC20 cToken) external view returns (uint256);
function add(address[] calldata underlyings, address[] calldata _oracles) external;
function changeAdmin(address newAdmin) external;
}
| 1,253,439 | [
1,
758,
1724,
392,
3844,
434,
6808,
2430,
358,
326,
385,
654,
39,
3462,
18,
225,
6808,
6275,
16811,
434,
6808,
2430,
358,
443,
1724,
18,
327,
1922,
555,
981,
578,
3634,
309,
1915,
1703,
1158,
555,
316,
326,
443,
1724,
18,
225,
605,
15318,
392,
3844,
434,
6808,
2430,
628,
326,
385,
654,
39,
3462,
18,
225,
6808,
6275,
16811,
434,
6808,
2430,
358,
29759,
18,
327,
1922,
555,
981,
578,
3634,
309,
1915,
1703,
1158,
555,
316,
326,
29759,
18,
225,
868,
10239,
392,
3844,
434,
6808,
2430,
358,
326,
385,
654,
39,
3462,
18,
225,
6808,
6275,
16811,
434,
6808,
2430,
358,
2071,
528,
18,
327,
1922,
555,
981,
578,
3634,
309,
1915,
1703,
1158,
555,
316,
326,
2071,
528,
18,
225,
2860,
326,
6808,
11013,
434,
279,
2923,
729,
18,
225,
729,
1021,
729,
10354,
1807,
11013,
326,
385,
654,
39,
3462,
903,
4614,
18,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
5831,
20137,
8141,
288,
203,
565,
445,
10833,
765,
6291,
5147,
12,
39,
654,
39,
3462,
276,
1345,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
527,
12,
2867,
8526,
745,
892,
3613,
715,
899,
16,
1758,
8526,
745,
892,
389,
10610,
9558,
13,
3903,
31,
203,
203,
565,
445,
2549,
4446,
12,
2867,
394,
4446,
13,
3903,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
import "./OrderMixin.sol";
import "./OrderRFQMixin.sol";
/// @title 1inch Limit Order Protocol v2
contract LimitOrderProtocol is
EIP712("1inch Limit Order Protocol", "2"),
OrderMixin,
OrderRFQMixin
{
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns(bytes32) {
return _domainSeparatorV4();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./helpers/AmountCalculator.sol";
import "./helpers/ChainlinkCalculator.sol";
import "./helpers/NonceManager.sol";
import "./helpers/PredicateHelper.sol";
import "./interfaces/InteractiveNotificationReceiver.sol";
import "./libraries/ArgumentsDecoder.sol";
import "./libraries/Permitable.sol";
/// @title Regular Limit Order mixin
abstract contract OrderMixin is
EIP712,
AmountCalculator,
ChainlinkCalculator,
NonceManager,
PredicateHelper,
Permitable
{
using Address for address;
using ArgumentsDecoder for bytes;
/// @notice Emitted every time order gets filled, including partial fills
event OrderFilled(
address indexed maker,
bytes32 orderHash,
uint256 remaining
);
/// @notice Emitted when order gets cancelled
event OrderCanceled(
address indexed maker,
bytes32 orderHash,
uint256 remainingRaw
);
// Fixed-size order part with core information
struct StaticOrder {
uint256 salt;
address makerAsset;
address takerAsset;
address maker;
address receiver;
address allowedSender; // equals to Zero address on public orders
uint256 makingAmount;
uint256 takingAmount;
}
// `StaticOrder` extension including variable-sized additional order meta information
struct Order {
uint256 salt;
address makerAsset;
address takerAsset;
address maker;
address receiver;
address allowedSender; // equals to Zero address on public orders
uint256 makingAmount;
uint256 takingAmount;
bytes makerAssetData;
bytes takerAssetData;
bytes getMakerAmount; // this.staticcall(abi.encodePacked(bytes, swapTakerAmount)) => (swapMakerAmount)
bytes getTakerAmount; // this.staticcall(abi.encodePacked(bytes, swapMakerAmount)) => (swapTakerAmount)
bytes predicate; // this.staticcall(bytes) => (bool)
bytes permit; // On first fill: permit.1.call(abi.encodePacked(permit.selector, permit.2))
bytes interaction;
}
bytes32 constant public LIMIT_ORDER_TYPEHASH = keccak256(
"Order(uint256 salt,address makerAsset,address takerAsset,address maker,address receiver,address allowedSender,uint256 makingAmount,uint256 takingAmount,bytes makerAssetData,bytes takerAssetData,bytes getMakerAmount,bytes getTakerAmount,bytes predicate,bytes permit,bytes interaction)"
);
uint256 constant private _ORDER_DOES_NOT_EXIST = 0;
uint256 constant private _ORDER_FILLED = 1;
/// @notice Stores unfilled amounts for each order plus one.
/// Therefore 0 means order doesn't exist and 1 means order was filled
mapping(bytes32 => uint256) private _remaining;
/// @notice Returns unfilled amount for order. Throws if order does not exist
function remaining(bytes32 orderHash) external view returns(uint256) {
uint256 amount = _remaining[orderHash];
require(amount != _ORDER_DOES_NOT_EXIST, "LOP: Unknown order");
unchecked { amount -= 1; }
return amount;
}
/// @notice Returns unfilled amount for order
/// @return Result Unfilled amount of order plus one if order exists. Otherwise 0
function remainingRaw(bytes32 orderHash) external view returns(uint256) {
return _remaining[orderHash];
}
/// @notice Same as `remainingRaw` but for multiple orders
function remainingsRaw(bytes32[] memory orderHashes) external view returns(uint256[] memory) {
uint256[] memory results = new uint256[](orderHashes.length);
for (uint256 i = 0; i < orderHashes.length; i++) {
results[i] = _remaining[orderHashes[i]];
}
return results;
}
/**
* @notice Calls every target with corresponding data. Then reverts with CALL_RESULTS_0101011 where zeroes and ones
* denote failure or success of the corresponding call
* @param targets Array of addresses that will be called
* @param data Array of data that will be passed to each call
*/
function simulateCalls(address[] calldata targets, bytes[] calldata data) external {
require(targets.length == data.length, "LOP: array size mismatch");
bytes memory reason = new bytes(targets.length);
for (uint256 i = 0; i < targets.length; i++) {
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory result) = targets[i].call(data[i]);
if (success && result.length > 0) {
success = result.length == 32 && result.decodeBool();
}
reason[i] = success ? bytes1("1") : bytes1("0");
}
// Always revert and provide per call results
revert(string(abi.encodePacked("CALL_RESULTS_", reason)));
}
/// @notice Cancels order by setting remaining amount to zero
function cancelOrder(Order memory order) external {
require(order.maker == msg.sender, "LOP: Access denied");
bytes32 orderHash = hashOrder(order);
uint256 orderRemaining = _remaining[orderHash];
require(orderRemaining != _ORDER_FILLED, "LOP: already filled");
emit OrderCanceled(msg.sender, orderHash, orderRemaining);
_remaining[orderHash] = _ORDER_FILLED;
}
/// @notice Fills an order. If one doesn't exist (first fill) it will be created using order.makerAssetData
/// @param order Order quote to fill
/// @param signature Signature to confirm quote ownership
/// @param makingAmount Making amount
/// @param takingAmount Taking amount
/// @param thresholdAmount Specifies maximum allowed takingAmount when takingAmount is zero, otherwise specifies minimum allowed makingAmount
function fillOrder(
Order memory order,
bytes calldata signature,
uint256 makingAmount,
uint256 takingAmount,
uint256 thresholdAmount
) external returns(uint256 /* actualMakingAmount */, uint256 /* actualTakingAmount */) {
return fillOrderTo(order, signature, makingAmount, takingAmount, thresholdAmount, msg.sender);
}
/// @notice Same as `fillOrder` but calls permit first,
/// allowing to approve token spending and make a swap in one transaction.
/// Also allows to specify funds destination instead of `msg.sender`
/// @param order Order quote to fill
/// @param signature Signature to confirm quote ownership
/// @param makingAmount Making amount
/// @param takingAmount Taking amount
/// @param thresholdAmount Specifies maximum allowed takingAmount when takingAmount is zero, otherwise specifies minimum allowed makingAmount
/// @param target Address that will receive swap funds
/// @param permit Should consist of abiencoded token address and encoded `IERC20Permit.permit` call.
/// @dev See tests for examples
function fillOrderToWithPermit(
Order memory order,
bytes calldata signature,
uint256 makingAmount,
uint256 takingAmount,
uint256 thresholdAmount,
address target,
bytes calldata permit
) external returns(uint256 /* actualMakingAmount */, uint256 /* actualTakingAmount */) {
require(permit.length >= 20, "LOP: permit length too low");
(address token, bytes calldata permitData) = permit.decodeTargetAndData();
_permit(token, permitData);
return fillOrderTo(order, signature, makingAmount, takingAmount, thresholdAmount, target);
}
/// @notice Same as `fillOrder` but allows to specify funds destination instead of `msg.sender`
/// @param order Order quote to fill
/// @param signature Signature to confirm quote ownership
/// @param makingAmount Making amount
/// @param takingAmount Taking amount
/// @param thresholdAmount Specifies maximum allowed takingAmount when takingAmount is zero, otherwise specifies minimum allowed makingAmount
/// @param target Address that will receive swap funds
function fillOrderTo(
Order memory order,
bytes calldata signature,
uint256 makingAmount,
uint256 takingAmount,
uint256 thresholdAmount,
address target
) public returns(uint256 /* actualMakingAmount */, uint256 /* actualTakingAmount */) {
require(target != address(0), "LOP: zero target is forbidden");
bytes32 orderHash = hashOrder(order);
{ // Stack too deep
uint256 remainingMakerAmount = _remaining[orderHash];
require(remainingMakerAmount != _ORDER_FILLED, "LOP: remaining amount is 0");
require(order.allowedSender == address(0) || order.allowedSender == msg.sender, "LOP: private order");
if (remainingMakerAmount == _ORDER_DOES_NOT_EXIST) {
// First fill: validate order and permit maker asset
require(SignatureChecker.isValidSignatureNow(order.maker, orderHash, signature), "LOP: bad signature");
remainingMakerAmount = order.makingAmount;
if (order.permit.length >= 20) {
// proceed only if permit length is enough to store address
(address token, bytes memory permit) = order.permit.decodeTargetAndCalldata();
_permitMemory(token, permit);
require(_remaining[orderHash] == _ORDER_DOES_NOT_EXIST, "LOP: reentrancy detected");
}
} else {
unchecked { remainingMakerAmount -= 1; }
}
// Check if order is valid
if (order.predicate.length > 0) {
require(checkPredicate(order), "LOP: predicate returned false");
}
// Compute maker and taker assets amount
if ((takingAmount == 0) == (makingAmount == 0)) {
revert("LOP: only one amount should be 0");
} else if (takingAmount == 0) {
uint256 requestedMakingAmount = makingAmount;
if (makingAmount > remainingMakerAmount) {
makingAmount = remainingMakerAmount;
}
takingAmount = _callGetter(order.getTakerAmount, order.makingAmount, makingAmount);
// check that actual rate is not worse than what was expected
// takingAmount / makingAmount <= thresholdAmount / requestedMakingAmount
require(takingAmount * requestedMakingAmount <= thresholdAmount * makingAmount, "LOP: taking amount too high");
} else {
uint256 requestedTakingAmount = takingAmount;
makingAmount = _callGetter(order.getMakerAmount, order.takingAmount, takingAmount);
if (makingAmount > remainingMakerAmount) {
makingAmount = remainingMakerAmount;
takingAmount = _callGetter(order.getTakerAmount, order.makingAmount, makingAmount);
}
// check that actual rate is not worse than what was expected
// makingAmount / takingAmount >= thresholdAmount / requestedTakingAmount
require(makingAmount * requestedTakingAmount >= thresholdAmount * takingAmount, "LOP: making amount too low");
}
require(makingAmount > 0 && takingAmount > 0, "LOP: can't swap 0 amount");
// Update remaining amount in storage
unchecked {
remainingMakerAmount = remainingMakerAmount - makingAmount;
_remaining[orderHash] = remainingMakerAmount + 1;
}
emit OrderFilled(msg.sender, orderHash, remainingMakerAmount);
}
// Taker => Maker
_makeCall(
order.takerAsset,
abi.encodePacked(
IERC20.transferFrom.selector,
uint256(uint160(msg.sender)),
uint256(uint160(order.receiver == address(0) ? order.maker : order.receiver)),
takingAmount,
order.takerAssetData
)
);
// Maker can handle funds interactively
if (order.interaction.length >= 20) {
// proceed only if interaction length is enough to store address
(address interactionTarget, bytes memory interactionData) = order.interaction.decodeTargetAndCalldata();
InteractiveNotificationReceiver(interactionTarget).notifyFillOrder(
msg.sender, order.makerAsset, order.takerAsset, makingAmount, takingAmount, interactionData
);
}
// Maker => Taker
_makeCall(
order.makerAsset,
abi.encodePacked(
IERC20.transferFrom.selector,
uint256(uint160(order.maker)),
uint256(uint160(target)),
makingAmount,
order.makerAssetData
)
);
return (makingAmount, takingAmount);
}
/// @notice Checks order predicate
function checkPredicate(Order memory order) public view returns(bool) {
bytes memory result = address(this).functionStaticCall(order.predicate, "LOP: predicate call failed");
require(result.length == 32, "LOP: invalid predicate return");
return result.decodeBool();
}
function hashOrder(Order memory order) public view returns(bytes32) {
StaticOrder memory staticOrder;
assembly { // solhint-disable-line no-inline-assembly
staticOrder := order
}
return _hashTypedDataV4(
keccak256(
abi.encode(
LIMIT_ORDER_TYPEHASH,
staticOrder,
keccak256(order.makerAssetData),
keccak256(order.takerAssetData),
keccak256(order.getMakerAmount),
keccak256(order.getTakerAmount),
keccak256(order.predicate),
keccak256(order.permit),
keccak256(order.interaction)
)
)
);
}
function _makeCall(address asset, bytes memory assetData) private {
bytes memory result = asset.functionCall(assetData, "LOP: asset.call failed");
if (result.length > 0) {
require(result.length == 32 && result.decodeBool(), "LOP: asset.call bad result");
}
}
function _callGetter(bytes memory getter, uint256 orderAmount, uint256 amount) private view returns(uint256) {
if (getter.length == 0) {
// On empty getter calldata only exact amount is allowed
require(amount == orderAmount, "LOP: wrong amount");
return orderAmount;
} else {
bytes memory result = address(this).functionStaticCall(abi.encodePacked(getter, amount), "LOP: getAmount call failed");
require(result.length == 32, "LOP: invalid getAmount return");
return result.decodeUint256();
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./helpers/AmountCalculator.sol";
import "./libraries/Permitable.sol";
/// @title RFQ Limit Order mixin
abstract contract OrderRFQMixin is EIP712, AmountCalculator, Permitable {
using SafeERC20 for IERC20;
/// @notice Emitted when RFQ gets filled
event OrderFilledRFQ(
bytes32 orderHash,
uint256 makingAmount
);
struct OrderRFQ {
uint256 info; // lowest 64 bits is the order id, next 64 bits is the expiration timestamp
IERC20 makerAsset;
IERC20 takerAsset;
address maker;
address allowedSender; // equals to Zero address on public orders
uint256 makingAmount;
uint256 takingAmount;
}
bytes32 constant public LIMIT_ORDER_RFQ_TYPEHASH = keccak256(
"OrderRFQ(uint256 info,address makerAsset,address takerAsset,address maker,address allowedSender,uint256 makingAmount,uint256 takingAmount)"
);
mapping(address => mapping(uint256 => uint256)) private _invalidator;
/// @notice Returns bitmask for double-spend invalidators based on lowest byte of order.info and filled quotes
/// @return Result Each bit represents whether corresponding was already invalidated
function invalidatorForOrderRFQ(address maker, uint256 slot) external view returns(uint256) {
return _invalidator[maker][slot];
}
/// @notice Cancels order's quote
function cancelOrderRFQ(uint256 orderInfo) external {
_invalidateOrder(msg.sender, orderInfo);
}
/// @notice Fills order's quote, fully or partially (whichever is possible)
/// @param order Order quote to fill
/// @param signature Signature to confirm quote ownership
/// @param makingAmount Making amount
/// @param takingAmount Taking amount
function fillOrderRFQ(
OrderRFQ memory order,
bytes calldata signature,
uint256 makingAmount,
uint256 takingAmount
) external returns(uint256, uint256) {
return fillOrderRFQTo(order, signature, makingAmount, takingAmount, msg.sender);
}
/// @notice Fills Same as `fillOrderRFQ` but calls permit first,
/// allowing to approve token spending and make a swap in one transaction.
/// Also allows to specify funds destination instead of `msg.sender`
/// @param order Order quote to fill
/// @param signature Signature to confirm quote ownership
/// @param makingAmount Making amount
/// @param takingAmount Taking amount
/// @param target Address that will receive swap funds
/// @param permit Should consist of abiencoded token address and encoded `IERC20Permit.permit` call.
/// @dev See tests for examples
function fillOrderRFQToWithPermit(
OrderRFQ memory order,
bytes calldata signature,
uint256 makingAmount,
uint256 takingAmount,
address target,
bytes calldata permit
) external returns(uint256, uint256) {
_permit(address(order.takerAsset), permit);
return fillOrderRFQTo(order, signature, makingAmount, takingAmount, target);
}
/// @notice Same as `fillOrderRFQ` but allows to specify funds destination instead of `msg.sender`
/// @param order Order quote to fill
/// @param signature Signature to confirm quote ownership
/// @param makingAmount Making amount
/// @param takingAmount Taking amount
/// @param target Address that will receive swap funds
function fillOrderRFQTo(
OrderRFQ memory order,
bytes calldata signature,
uint256 makingAmount,
uint256 takingAmount,
address target
) public returns(uint256, uint256) {
require(target != address(0), "LOP: zero target is forbidden");
address maker = order.maker;
// Validate order
require(order.allowedSender == address(0) || order.allowedSender == msg.sender, "LOP: private order");
bytes32 orderHash = _hashTypedDataV4(keccak256(abi.encode(LIMIT_ORDER_RFQ_TYPEHASH, order)));
require(SignatureChecker.isValidSignatureNow(maker, orderHash, signature), "LOP: bad signature");
{ // Stack too deep
uint256 info = order.info;
// Check time expiration
uint256 expiration = uint128(info) >> 64;
require(expiration == 0 || block.timestamp <= expiration, "LOP: order expired"); // solhint-disable-line not-rely-on-time
_invalidateOrder(maker, info);
}
{ // stack too deep
uint256 orderMakingAmount = order.makingAmount;
uint256 orderTakingAmount = order.takingAmount;
// Compute partial fill if needed
if (takingAmount == 0 && makingAmount == 0) {
// Two zeros means whole order
makingAmount = orderMakingAmount;
takingAmount = orderTakingAmount;
}
else if (takingAmount == 0) {
require(makingAmount <= orderMakingAmount, "LOP: making amount exceeded");
takingAmount = getTakerAmount(orderMakingAmount, orderTakingAmount, makingAmount);
}
else if (makingAmount == 0) {
require(takingAmount <= orderTakingAmount, "LOP: taking amount exceeded");
makingAmount = getMakerAmount(orderMakingAmount, orderTakingAmount, takingAmount);
}
else {
revert("LOP: both amounts are non-zero");
}
}
require(makingAmount > 0 && takingAmount > 0, "LOP: can't swap 0 amount");
// Maker => Taker, Taker => Maker
order.makerAsset.safeTransferFrom(maker, target, makingAmount);
order.takerAsset.safeTransferFrom(msg.sender, maker, takingAmount);
emit OrderFilledRFQ(orderHash, makingAmount);
return (makingAmount, takingAmount);
}
function _invalidateOrder(address maker, uint256 orderInfo) private {
uint256 invalidatorSlot = uint64(orderInfo) >> 8;
uint256 invalidatorBit = 1 << uint8(orderInfo);
mapping(uint256 => uint256) storage invalidatorStorage = _invalidator[maker];
uint256 invalidator = invalidatorStorage[invalidatorSlot];
require(invalidator & invalidatorBit == 0, "LOP: invalidated order");
invalidatorStorage[invalidatorSlot] = invalidator | invalidatorBit;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ECDSA.sol";
import "../Address.sol";
import "../../interfaces/IERC1271.sol";
/**
* @dev Signature verification helper: Provide a single mechanism to verify both private-key (EOA) ECDSA signature and
* ERC1271 contract sigantures. Using this instead of ECDSA.recover in your contract will make them compatible with
* smart contract wallets such as Argent and Gnosis.
*
* Note: unlike ECDSA signatures, contract signature's are revocable, and the outcome of this function can thus change
* through time. It could return true at block N and false at block N+1 (or the opposite).
*
* _Available since v4.1._
*/
library SignatureChecker {
function isValidSignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
(address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature);
if (error == ECDSA.RecoverError.NoError && recovered == signer) {
return true;
}
(bool success, bytes memory result) = signer.staticcall(
abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature)
);
return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
pragma abicoder v1;
import "@openzeppelin/contracts/utils/Address.sol";
/// @title A helper contract for calculations related to order amounts
contract AmountCalculator {
using Address for address;
/// @notice Calculates maker amount
/// @return Result Floored maker amount
function getMakerAmount(uint256 orderMakerAmount, uint256 orderTakerAmount, uint256 swapTakerAmount) public pure returns(uint256) {
return swapTakerAmount * orderMakerAmount / orderTakerAmount;
}
/// @notice Calculates taker amount
/// @return Result Ceiled taker amount
function getTakerAmount(uint256 orderMakerAmount, uint256 orderTakerAmount, uint256 swapMakerAmount) public pure returns(uint256) {
return (swapMakerAmount * orderTakerAmount + orderMakerAmount - 1) / orderMakerAmount;
}
/// @notice Performs an arbitrary call to target with data
/// @return Result Bytes transmuted to uint256
function arbitraryStaticCall(address target, bytes memory data) external view returns(uint256) {
(bytes memory result) = target.functionStaticCall(data, "AC: arbitraryStaticCall");
return abi.decode(result, (uint256));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
pragma abicoder v1;
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
/// @title A helper contract for interactions with https://docs.chain.link
contract ChainlinkCalculator {
using SafeCast for int256;
uint256 private constant _SPREAD_DENOMINATOR = 1e9;
uint256 private constant _ORACLE_EXPIRATION_TIME = 30 minutes;
uint256 private constant _INVERSE_MASK = 1 << 255;
/// @notice Calculates price of token relative to oracle unit (ETH or USD)
/// @param inverseAndSpread concatenated inverse flag and spread.
/// Lowest 254 bits specify spread amount. Spread is scaled by 1e9, i.e. 101% = 1.01e9, 99% = 0.99e9.
/// Highest bit is set when oracle price should be inverted,
/// e.g. for DAI-ETH oracle, inverse=false means that we request DAI price in ETH
/// and inverse=true means that we request ETH price in DAI
/// @return Amount * spread * oracle price
function singlePrice(AggregatorV3Interface oracle, uint256 inverseAndSpread, uint256 amount) external view returns(uint256) {
(, int256 latestAnswer,, uint256 latestTimestamp,) = oracle.latestRoundData();
// solhint-disable-next-line not-rely-on-time
require(latestTimestamp + _ORACLE_EXPIRATION_TIME > block.timestamp, "CC: stale data");
bool inverse = inverseAndSpread & _INVERSE_MASK > 0;
uint256 spread = inverseAndSpread & (~_INVERSE_MASK);
if (inverse) {
return amount * spread * (10 ** oracle.decimals()) / latestAnswer.toUint256() / _SPREAD_DENOMINATOR;
} else {
return amount * spread * latestAnswer.toUint256() / (10 ** oracle.decimals()) / _SPREAD_DENOMINATOR;
}
}
/// @notice Calculates price of token A relative to token B. Note that order is important
/// @return Result Token A relative price times amount
function doublePrice(AggregatorV3Interface oracle1, AggregatorV3Interface oracle2, uint256 spread, uint256 amount) external view returns(uint256) {
require(oracle1.decimals() == oracle2.decimals(), "CC: oracle decimals don't match");
(, int256 latestAnswer1,, uint256 latestTimestamp1,) = oracle1.latestRoundData();
(, int256 latestAnswer2,, uint256 latestTimestamp2,) = oracle2.latestRoundData();
// solhint-disable-next-line not-rely-on-time
require(latestTimestamp1 + _ORACLE_EXPIRATION_TIME > block.timestamp, "CC: stale data O1");
// solhint-disable-next-line not-rely-on-time
require(latestTimestamp2 + _ORACLE_EXPIRATION_TIME > block.timestamp, "CC: stale data O2");
return amount * spread * latestAnswer1.toUint256() / latestAnswer2.toUint256() / _SPREAD_DENOMINATOR;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
pragma abicoder v1;
/// @title A helper contract for managing nonce of tx sender
contract NonceManager {
event NonceIncreased(address indexed maker, uint256 newNonce);
mapping(address => uint256) public nonce;
/// @notice Advances nonce by one
function increaseNonce() external {
advanceNonce(1);
}
/// @notice Advances nonce by specified amount
function advanceNonce(uint8 amount) public {
uint256 newNonce = nonce[msg.sender] + amount;
nonce[msg.sender] = newNonce;
emit NonceIncreased(msg.sender, newNonce);
}
/// @notice Checks if `makerAddress` has specified `makerNonce`
/// @return Result True if `makerAddress` has specified nonce. Otherwise, false
function nonceEquals(address makerAddress, uint256 makerNonce) external view returns(bool) {
return nonce[makerAddress] == makerNonce;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/utils/Address.sol";
/// @title A helper contract for executing boolean functions on arbitrary target call results
contract PredicateHelper {
using Address for address;
/// @notice Calls every target with corresponding data
/// @return Result True if call to any target returned True. Otherwise, false
function or(address[] calldata targets, bytes[] calldata data) external view returns(bool) {
require(targets.length == data.length, "PH: input array size mismatch");
for (uint256 i = 0; i < targets.length; i++) {
bytes memory result = targets[i].functionStaticCall(data[i], "PH: 'or' subcall failed");
require(result.length == 32, "PH: invalid call result");
if (abi.decode(result, (bool))) {
return true;
}
}
return false;
}
/// @notice Calls every target with corresponding data
/// @return Result True if calls to all targets returned True. Otherwise, false
function and(address[] calldata targets, bytes[] calldata data) external view returns(bool) {
require(targets.length == data.length, "PH: input array size mismatch");
for (uint256 i = 0; i < targets.length; i++) {
bytes memory result = targets[i].functionStaticCall(data[i], "PH: 'and' subcall failed");
require(result.length == 32, "PH: invalid call result");
if (!abi.decode(result, (bool))) {
return false;
}
}
return true;
}
/// @notice Calls target with specified data and tests if it's equal to the value
/// @param value Value to test
/// @return Result True if call to target returns the same value as `value`. Otherwise, false
function eq(uint256 value, address target, bytes memory data) external view returns(bool) {
bytes memory result = target.functionStaticCall(data, "PH: eq");
require(result.length == 32, "PH: invalid call result");
return abi.decode(result, (uint256)) == value;
}
/// @notice Calls target with specified data and tests if it's lower than value
/// @param value Value to test
/// @return Result True if call to target returns value which is lower than `value`. Otherwise, false
function lt(uint256 value, address target, bytes memory data) external view returns(bool) {
bytes memory result = target.functionStaticCall(data, "PH: lt");
require(result.length == 32, "PH: invalid call result");
return abi.decode(result, (uint256)) < value;
}
/// @notice Calls target with specified data and tests if it's bigger than value
/// @param value Value to test
/// @return Result True if call to target returns value which is bigger than `value`. Otherwise, false
function gt(uint256 value, address target, bytes memory data) external view returns(bool) {
bytes memory result = target.functionStaticCall(data, "PH: gt");
require(result.length == 32, "PH: invalid call result");
return abi.decode(result, (uint256)) > value;
}
/// @notice Checks passed time against block timestamp
/// @return Result True if current block timestamp is lower than `time`. Otherwise, false
function timestampBelow(uint256 time) external view returns(bool) {
return block.timestamp < time; // solhint-disable-line not-rely-on-time
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
pragma abicoder v1;
/// @title Interface for interactor which acts between `maker => taker` and `taker => maker` transfers.
interface InteractiveNotificationReceiver {
/// @notice Callback method that gets called after taker transferred funds to maker but before
/// the opposite transfer happened
function notifyFillOrder(
address taker,
address makerAsset,
address takerAsset,
uint256 makingAmount,
uint256 takingAmount,
bytes memory interactiveData
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
pragma abicoder v1;
/// @title Library with gas efficient alternatives to `abi.decode`
library ArgumentsDecoder {
function decodeUint256(bytes memory data) internal pure returns(uint256) {
uint256 value;
assembly { // solhint-disable-line no-inline-assembly
value := mload(add(data, 0x20))
}
return value;
}
function decodeBool(bytes memory data) internal pure returns(bool) {
bool value;
assembly { // solhint-disable-line no-inline-assembly
value := eq(mload(add(data, 0x20)), 1)
}
return value;
}
function decodeTargetAndCalldata(bytes memory data) internal pure returns(address, bytes memory) {
address target;
bytes memory args;
assembly { // solhint-disable-line no-inline-assembly
target := mload(add(data, 0x14))
args := add(data, 0x14)
mstore(args, sub(mload(data), 0x14))
}
return (target, args);
}
function decodeTargetAndData(bytes calldata data) internal pure returns(address, bytes calldata) {
address target;
bytes calldata args;
assembly { // solhint-disable-line no-inline-assembly
target := shr(96, calldataload(data.offset))
}
args = data[20:];
return (target, args);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
pragma abicoder v1;
import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import "./RevertReasonParser.sol";
import "../interfaces/IDaiLikePermit.sol";
/// @title Base contract with common permit handling logics
abstract contract Permitable {
function _permit(address token, bytes calldata permit) internal {
if (permit.length > 0) {
bool success;
bytes memory result;
if (permit.length == 32 * 7) {
// solhint-disable-next-line avoid-low-level-calls
(success, result) = token.call(abi.encodePacked(IERC20Permit.permit.selector, permit));
} else if (permit.length == 32 * 8) {
// solhint-disable-next-line avoid-low-level-calls
(success, result) = token.call(abi.encodePacked(IDaiLikePermit.permit.selector, permit));
} else {
revert("Wrong permit length");
}
if (!success) {
revert(RevertReasonParser.parse(result, "Permit failed: "));
}
}
}
function _permitMemory(address token, bytes memory permit) internal {
if (permit.length > 0) {
bool success;
bytes memory result;
if (permit.length == 32 * 7) {
// solhint-disable-next-line avoid-low-level-calls
(success, result) = token.call(abi.encodePacked(IERC20Permit.permit.selector, permit));
} else if (permit.length == 32 * 8) {
// solhint-disable-next-line avoid-low-level-calls
(success, result) = token.call(abi.encodePacked(IDaiLikePermit.permit.selector, permit));
} else {
revert("Wrong permit length");
}
if (!success) {
revert(RevertReasonParser.parse(result, "Permit failed: "));
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*
* _Available since v4.1._
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorV3Interface {
function decimals()
external
view
returns (
uint8
);
function description()
external
view
returns (
string memory
);
function version()
external
view
returns (
uint256
);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(
uint80 _roundId
)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
pragma abicoder v1;
/// @title Library that allows to parse unsuccessful arbitrary calls revert reasons.
/// See https://solidity.readthedocs.io/en/latest/control-structures.html#revert for details.
/// Note that we assume revert reason being abi-encoded as Error(string) so it may fail to parse reason
/// if structured reverts appear in the future.
///
/// All unsuccessful parsings get encoded as Unknown(data) string
library RevertReasonParser {
bytes4 constant private _PANIC_SELECTOR = bytes4(keccak256("Panic(uint256)"));
bytes4 constant private _ERROR_SELECTOR = bytes4(keccak256("Error(string)"));
function parse(bytes memory data, string memory prefix) internal pure returns (string memory) {
if (data.length >= 4) {
bytes4 selector;
assembly { // solhint-disable-line no-inline-assembly
selector := mload(add(data, 0x20))
}
// 68 = 4-byte selector + 32 bytes offset + 32 bytes length
if (selector == _ERROR_SELECTOR && data.length >= 68) {
uint256 offset;
bytes memory reason;
assembly { // solhint-disable-line no-inline-assembly
// 36 = 32 bytes data length + 4-byte selector
offset := mload(add(data, 36))
reason := add(data, add(36, offset))
}
/*
revert reason is padded up to 32 bytes with ABI encoder: Error(string)
also sometimes there is extra 32 bytes of zeros padded in the end:
https://github.com/ethereum/solidity/issues/10170
because of that we can't check for equality and instead check
that offset + string length + extra 36 bytes is less than overall data length
*/
require(data.length >= 36 + offset + reason.length, "Invalid revert reason");
return string(abi.encodePacked(prefix, "Error(", reason, ")"));
}
// 36 = 4-byte selector + 32 bytes integer
else if (selector == _PANIC_SELECTOR && data.length == 36) {
uint256 code;
assembly { // solhint-disable-line no-inline-assembly
// 36 = 32 bytes data length + 4-byte selector
code := mload(add(data, 36))
}
return string(abi.encodePacked(prefix, "Panic(", _toHex(code), ")"));
}
}
return string(abi.encodePacked(prefix, "Unknown(", _toHex(data), ")"));
}
function _toHex(uint256 value) private pure returns(string memory) {
return _toHex(abi.encodePacked(value));
}
function _toHex(bytes memory data) private pure returns(string memory) {
bytes16 alphabet = 0x30313233343536373839616263646566;
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint256 i = 0; i < data.length; i++) {
str[2 * i + 2] = alphabet[uint8(data[i] >> 4)];
str[2 * i + 3] = alphabet[uint8(data[i] & 0x0f)];
}
return string(str);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
pragma abicoder v1;
/// @title Interface for DAI-style permits
interface IDaiLikePermit {
function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
} | solhint-disable-line no-inline-assembly
| assembly { | 1,390,224 | [
1,
18281,
11317,
17,
8394,
17,
1369,
1158,
17,
10047,
17,
28050,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
7734,
19931,
288,
282,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.21;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/* Standard SafeMath implementation from Zeppelin */
/**
* @title Claimable
* @dev Extension for the Ownable contract, where the ownership needs to be claimed.
* This allows the new owner to accept the transfer.
*/
contract Claimable is Ownable {
address public pendingOwner;
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() onlyPendingOwner public {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
/* Standard Claimable implementation from Zeppelin */
/**
* @title Contracts that should be able to recover tokens
* @author SylTi
* @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner.
* This will prevent any accidental loss of tokens.
*/
contract CanReclaimToken is Ownable {
using SafeERC20 for ERC20Basic;
/**
* @dev Reclaim all ERC20Basic compatible tokens
* @param token ERC20Basic The address of the token contract
*/
function reclaimToken(ERC20Basic token) external onlyOwner {
uint256 balance = token.balanceOf(this);
token.safeTransfer(owner, balance);
}
}
/* Standard Claimable implementation from Zeppelin */
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Standard Burnable Token
* @dev Adds burnFrom method to ERC20 implementations
*/
contract StandardBurnableToken is BurnableToken, StandardToken {
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param _from address The address which you want to send tokens from
* @param _value uint256 The amount of token to be burned
*/
function burnFrom(address _from, uint256 _value) public {
require(_value <= allowed[_from][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
_burn(_from, _value);
}
}
// Standard burnable token implementation from Zeppelin
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
// PausableToken implementation from Zeppelin
// Claimable implementation from Zeppelin
/* Standard Claimable implementation from Zeppelin */
interface CrowdsaleContract {
function isActive() public view returns(bool);
}
contract BulleonToken is StandardBurnableToken, PausableToken, Claimable, CanReclaimToken {
/* Additional events */
event AddedToWhitelist(address wallet);
event RemoveWhitelist(address wallet);
/* Base params */
string public constant name = "Bulleon"; /* solium-disable-line uppercase */
string public constant symbol = "BUL"; /* solium-disable-line uppercase */
uint8 public constant decimals = 18; /* solium-disable-line uppercase */
uint256 constant exchangersBalance = 39991750231582759746295 + 14715165984103328399573 + 1846107707643607869274; // YoBit + Etherdelta + IDEX
/* Premine and start balance settings */
address constant premineWallet = 0x286BE9799488cA4543399c2ec964e7184077711C;
uint256 constant premineAmount = 178420 * (10 ** uint256(decimals));
/* Additional params */
address public CrowdsaleAddress;
CrowdsaleContract crowdsale;
mapping(address=>bool) whitelist; // Users that may transfer tokens before ICO ended
/**
* @dev Constructor that gives msg.sender all availabel of existing tokens.
*/
constructor() public {
totalSupply_ = 7970000 * (10 ** uint256(decimals));
balances[msg.sender] = totalSupply_;
transfer(premineWallet, premineAmount.add(exchangersBalance));
addToWhitelist(msg.sender);
addToWhitelist(premineWallet);
paused = true; // Lock token at start
}
/**
* @dev Sets crowdsale contract address (used for checking ICO status)
*/
function setCrowdsaleAddress(address _ico) public onlyOwner {
CrowdsaleAddress = _ico;
crowdsale = CrowdsaleContract(CrowdsaleAddress);
addToWhitelist(CrowdsaleAddress);
}
/**
* @dev called by user the to pause, triggers stopped state
* not actualy used
*/
function pause() onlyOwner whenNotPaused public {
revert();
}
/**
* @dev Modifier to make a function callable only when the contract is not paused or when sender is whitelisted.
*/
modifier whenNotPaused() {
require(!paused || whitelist[msg.sender]);
_;
}
/**
* @dev called by the user to unpause at ICO end or by owner, returns token to unlocked state
*/
function unpause() whenPaused public {
require(!crowdsale.isActive() || msg.sender == owner); // Checks that ICO is ended
paused = false;
emit Unpause();
}
/**
* @dev Add wallet address to transfer whitelist (may transfer tokens before ICO ended)
*/
function addToWhitelist(address wallet) public onlyOwner {
require(!whitelist[wallet]);
whitelist[wallet] = true;
emit AddedToWhitelist(wallet);
}
/**
* @dev Delete wallet address to transfer whitelist (may transfer tokens before ICO ended)
*/
function delWhitelist(address wallet) public onlyOwner {
require(whitelist[wallet]);
whitelist[wallet] = false;
emit RemoveWhitelist(wallet);
}
// DELETE IT!
function kill() onlyOwner {
selfdestruct(owner);
}
}
contract BulleonCrowdsale is Claimable, CanReclaimToken {
using SafeMath for uint256;
/* Additionals events */
event AddedToBlacklist(address wallet);
event RemovedFromBlacklist(address wallet);
/* Infomational vars */
string public version = "2.0";
/* ICO params */
address public withdrawWallet = 0xAd74Bd38911fE4C19c95D14b5733372c3978C2D9;
uint256 public endDate = 1546300799; // Monday, 31-Dec-18 23:59:59 UTC
BulleonToken public rewardToken;
// Tokens rate (BUL / ETH) on stage
uint256[] public tokensRate = [
1000, // stage 1
800, // stage 2
600, // stage 3
400, // stage 4
200, // stage 5
100, // stage 6
75, // stage 7
50, // stage 8
25, // stage 9
10 // stage 10
];
// Tokens cap (max sold tokens) on stage
uint256[] public tokensCap = [
760000, // stage 1
760000, // stage 2
760000, // stage 3
760000, // stage 4
760000, // stage 5
760000, // stage 6
760000, // stage 7
760000, // stage 8
760000, // stage 9
759000 // stage 10
];
mapping(address=>bool) public isBlacklisted;
/* ICO stats */
uint256 public totalSold = 329406072304513072322000; // ! Update on publish
uint256 public soldOnStage = 329406072304513072322000; // ! Update on publish
uint8 public currentStage = 0;
/* Bonus params */
uint256 public bonus = 0;
uint256 constant BONUS_COEFF = 1000; // Values should be 10x percents, value 1000 = 100%
mapping(address=>uint256) public investmentsOf; // Investments made by wallet
/**
* @dev Returns crowdsale status (if active returns true).
*/
function isActive() public view returns (bool) {
return !(availableTokens() == 0 || now > endDate);
}
/* ICO stats methods */
/**
* @dev Returns tokens amount cap for current stage.
*/
function stageCap() public view returns(uint256) {
return tokensCap[currentStage].mul(1 ether);
}
/**
* @dev Returns tokens amount available to sell at current stage.
*/
function availableOnStage() public view returns(uint256) {
return stageCap().sub(soldOnStage) > availableTokens() ? availableTokens() : stageCap().sub(soldOnStage);
}
/**
* @dev Returns base rate (BUL/ETH) of current stage.
*/
function stageBaseRate() public view returns(uint256) {
return tokensRate[currentStage];
}
/**
* @dev Returns actual (base + bonus %) rate (BUL/ETH) of current stage.
*/
function stageRate() public view returns(uint256) {
return stageBaseRate().mul(BONUS_COEFF.add(getBonus())).div(BONUS_COEFF);
}
constructor(address token) public {
require(token != 0x0);
rewardToken = BulleonToken(token);
}
function () public payable {
buyTokens(msg.sender);
}
/**
* @dev Main token puchase function
*/
function buyTokens(address beneficiary) public payable {
bool validPurchase = beneficiary != 0x0 && msg.value != 0 && !isBlacklisted[msg.sender];
uint256 currentTokensAmount = availableTokens();
// Check that ICO is Active and purchase tx is valid
require(isActive() && validPurchase);
investmentsOf[msg.sender] = investmentsOf[msg.sender].add(msg.value);
uint256 boughtTokens;
uint256 refundAmount = 0;
// Calculate tokens and refund amount at multiple stage
uint256[2] memory tokensAndRefund = calcMultiStage();
boughtTokens = tokensAndRefund[0];
refundAmount = tokensAndRefund[1];
// Check that bought tokens amount less then current
require(boughtTokens <= currentTokensAmount);
totalSold = totalSold.add(boughtTokens); // Increase stats variable
if(soldOnStage >= stageCap()) {
toNextStage();
}
rewardToken.transfer(beneficiary, boughtTokens);
if (refundAmount > 0)
refundMoney(refundAmount);
withdrawFunds(this.balance);
}
/**
* @dev Forcibility withdraw contract ETH balance.
*/
function forceWithdraw() public onlyOwner {
withdrawFunds(this.balance);
}
/**
* @dev Calculate tokens amount and refund amount at purchase procedure.
*/
function calcMultiStage() internal returns(uint256[2]) {
uint256 stageBoughtTokens;
uint256 undistributedAmount = msg.value;
uint256 _boughtTokens = 0;
uint256 undistributedTokens = availableTokens();
while(undistributedAmount > 0 && undistributedTokens > 0) {
bool needNextStage = false;
stageBoughtTokens = getTokensAmount(undistributedAmount);
if (stageBoughtTokens > availableOnStage()) {
stageBoughtTokens = availableOnStage();
needNextStage = true;
}
_boughtTokens = _boughtTokens.add(stageBoughtTokens);
undistributedTokens = undistributedTokens.sub(stageBoughtTokens);
undistributedAmount = undistributedAmount.sub(getTokensCost(stageBoughtTokens));
soldOnStage = soldOnStage.add(stageBoughtTokens);
if (needNextStage)
toNextStage();
}
return [_boughtTokens,undistributedAmount];
}
/**
* @dev Sets withdraw wallet address. (called by owner)
*/
function setWithdraw(address _withdrawWallet) public onlyOwner {
require(_withdrawWallet != 0x0);
withdrawWallet = _withdrawWallet;
}
/**
* @dev Make partical refund at purchasing procedure
*/
function refundMoney(uint256 refundAmount) internal {
msg.sender.transfer(refundAmount);
}
/**
* @dev Give owner ability to burn some tokens amount at ICO contract
*/
function burnTokens(uint256 amount) public onlyOwner {
rewardToken.burn(amount);
}
/**
* @dev Returns costs of given tokens amount
*/
function getTokensCost(uint256 _tokensAmount) public view returns(uint256) {
return _tokensAmount.div(stageRate());
}
function getTokensAmount(uint256 _amountInWei) public view returns(uint256) {
return _amountInWei.mul(stageRate());
}
/**
* @dev Switch contract to next stage and reset stage stats
*/
function toNextStage() internal {
if (
currentStage < tokensRate.length &&
currentStage < tokensCap.length
) {
currentStage++;
soldOnStage = 0;
}
}
function availableTokens() public view returns(uint256) {
return rewardToken.balanceOf(address(this));
}
function withdrawFunds(uint256 amount) internal {
withdrawWallet.transfer(amount);
}
function kill() public onlyOwner {
require(!isActive()); // Check that ICO is Ended (!= Active)
rewardToken.burn(availableTokens()); // Burn tokens
selfdestruct(owner); // Destruct ICO contract
}
function setBonus(uint256 bonusAmount) public onlyOwner {
require(
bonusAmount < 100 * BONUS_COEFF &&
bonusAmount >= 0
);
bonus = bonusAmount;
}
function getBonus() public view returns(uint256) {
uint256 _bonus = bonus;
uint256 investments = investmentsOf[msg.sender];
if(investments > 50 ether)
_bonus += 250; // 25%
else
if(investments > 20 ether)
_bonus += 200; // 20%
else
if(investments > 10 ether)
_bonus += 150; // 15%
else
if(investments > 5 ether)
_bonus += 100; // 10%
else
if(investments > 1 ether)
_bonus += 50; // 5%
return _bonus;
}
function addBlacklist(address wallet) public onlyOwner {
require(!isBlacklisted[wallet]);
isBlacklisted[wallet] = true;
emit AddedToBlacklist(wallet);
}
function delBlacklist(address wallet) public onlyOwner {
require(isBlacklisted[wallet]);
isBlacklisted[wallet] = false;
emit RemovedFromBlacklist(wallet);
}
} | * @dev Main token puchase function/ Check that ICO is Active and purchase tx is valid Calculate tokens and refund amount at multiple stage Check that bought tokens amount less then current | function buyTokens(address beneficiary) public payable {
bool validPurchase = beneficiary != 0x0 && msg.value != 0 && !isBlacklisted[msg.sender];
uint256 currentTokensAmount = availableTokens();
require(isActive() && validPurchase);
investmentsOf[msg.sender] = investmentsOf[msg.sender].add(msg.value);
uint256 boughtTokens;
uint256 refundAmount = 0;
uint256[2] memory tokensAndRefund = calcMultiStage();
boughtTokens = tokensAndRefund[0];
refundAmount = tokensAndRefund[1];
require(boughtTokens <= currentTokensAmount);
if(soldOnStage >= stageCap()) {
toNextStage();
}
rewardToken.transfer(beneficiary, boughtTokens);
if (refundAmount > 0)
refundMoney(refundAmount);
withdrawFunds(this.balance);
}
| 6,466,090 | [
1,
6376,
1147,
293,
2648,
448,
445,
19,
2073,
716,
467,
3865,
353,
8857,
471,
23701,
2229,
353,
923,
9029,
2430,
471,
16255,
3844,
622,
3229,
6009,
2073,
716,
800,
9540,
2430,
3844,
5242,
1508,
783,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
30143,
5157,
12,
2867,
27641,
74,
14463,
814,
13,
1071,
8843,
429,
288,
203,
1377,
1426,
923,
23164,
273,
27641,
74,
14463,
814,
480,
374,
92,
20,
597,
1234,
18,
1132,
480,
374,
597,
401,
291,
13155,
18647,
63,
3576,
18,
15330,
15533,
203,
1377,
2254,
5034,
783,
5157,
6275,
273,
2319,
5157,
5621,
203,
1377,
2583,
12,
291,
3896,
1435,
597,
923,
23164,
1769,
203,
1377,
2198,
395,
1346,
951,
63,
3576,
18,
15330,
65,
273,
2198,
395,
1346,
951,
63,
3576,
18,
15330,
8009,
1289,
12,
3576,
18,
1132,
1769,
203,
1377,
2254,
5034,
800,
9540,
5157,
31,
203,
1377,
2254,
5034,
16255,
6275,
273,
374,
31,
203,
203,
1377,
2254,
5034,
63,
22,
65,
3778,
2430,
1876,
21537,
273,
7029,
5002,
8755,
5621,
203,
1377,
800,
9540,
5157,
273,
2430,
1876,
21537,
63,
20,
15533,
203,
1377,
16255,
6275,
273,
2430,
1876,
21537,
63,
21,
15533,
203,
1377,
2583,
12,
1075,
9540,
5157,
1648,
783,
5157,
6275,
1769,
203,
203,
203,
1377,
309,
12,
87,
1673,
1398,
8755,
1545,
6009,
4664,
10756,
288,
203,
3639,
358,
2134,
8755,
5621,
203,
1377,
289,
203,
203,
1377,
19890,
1345,
18,
13866,
12,
70,
4009,
74,
14463,
814,
16,
800,
9540,
5157,
1769,
203,
203,
1377,
309,
261,
1734,
1074,
6275,
405,
374,
13,
203,
1850,
16255,
23091,
12,
1734,
1074,
6275,
1769,
203,
203,
1377,
598,
9446,
42,
19156,
12,
2211,
18,
12296,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0xC0Eb85285d83217CD7c891702bcbC0FC401E2D9D
//Contract name: HVNToken
//Balance: 0 Ether
//Verification Date: 9/7/2017
//Transacion Count: 22728
// CODE STARTS HERE
/**
* ERC-20 Standard Token Smart Contract implementation.
*
* Copyright © 2017 by Hive Project Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND (express or implied).
*/
pragma solidity ^0.4.11;
/**
* ERC-20 Standard Token Smart Contract Interface.
*
* Copyright © 2017 by Hive Project Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND (express or implied).
*/
/**
* ERC-20 standard token interface, as defined
* <a href="http://github.com/ethereum/EIPs/issues/20">here</a>.
*/
contract ERC20Interface {
/**
* Get total number of tokens in circulation.
*/
uint256 public totalSupply;
/**
* @dev Get number of tokens currently belonging to given owner.
*
* @param _owner address to get number of tokens currently belonging to the
* owner of
* @return number of tokens currently belonging to the owner of given address
*/
function balanceOf (address _owner) constant returns (uint256 balance);
/**
* @dev Transfer given number of tokens from message sender to given recipient.
*
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/
function transfer (address _to, uint256 _value) returns (bool success);
/**
* @dev Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
*/
function transferFrom (address _from, address _to, uint256 _value)
returns (bool success);
/**
* @dev Allow given spender to transfer given number of tokens from message sender.
*
* @param _spender address to allow the owner of to transfer tokens from
* message sender
* @param _value number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve (address _spender, uint256 _value) returns (bool success);
/**
* @dev Tell how many tokens given spender is currently allowed to transfer from
* given owner.
*
* @param _owner address to get number of tokens allowed to be transferred
* from the owner of
* @param _spender address to get number of tokens allowed to be transferred
* by the owner of
* @return number of tokens given spender is currently allowed to transfer
* from given owner
*/
function allowance (address _owner, address _spender) constant
returns (uint256 remaining);
/**
* @dev Logged when tokens were transferred from one owner to another.
*
* @param _from address of the owner, tokens were transferred from
* @param _to address of the owner, tokens were transferred to
* @param _value number of tokens transferred
*/
event Transfer (address indexed _from, address indexed _to, uint256 _value);
/**
* @dev Logged when owner approved his tokens to be transferred by some spender.
*
* @param _owner owner who approved his tokens to be transferred
* @param _spender spender who were allowed to transfer the tokens belonging
* to the owner
* @param _value number of tokens belonging to the owner, approved to be
* transferred by the spender
*/
event Approval (
address indexed _owner, address indexed _spender, uint256 _value);
}
contract Owned {
address public owner;
address public newOwner;
function Owned() {
owner = msg.sender;
}
modifier ownerOnly {
assert(msg.sender == owner);
_;
}
/**
* @dev Transfers ownership. New owner has to accept in order ownership change to take effect
*/
function transferOwnership(address _newOwner) public ownerOnly {
require(_newOwner != owner);
newOwner = _newOwner;
}
/**
* @dev Accepts transferred ownership
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = 0x0;
}
event OwnerUpdate(address _prevOwner, address _newOwner);
}
/**
* Safe Math Smart Contract.
*
* Copyright © 2017 by Hive Project Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND (express or implied).
*/
/**
* Provides methods to safely add, subtract and multiply uint256 numbers.
*/
contract SafeMath {
/**
* @dev Add two uint256 values, throw in case of overflow.
*
* @param a first value to add
* @param b second value to add
* @return x + y
*/
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
/**
* @dev Subtract one uint256 value from another, throw in case of underflow.
*
* @param a value to subtract from
* @param b value to subtract
* @return a - b
*/
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Multiply two uint256 values, throw in case of overflow.
*
* @param a first value to multiply
* @param b second value to multiply
* @return c = a * b
*/
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
/**
* @dev Divide two uint256 values, throw in case of overflow.
*
* @param a first value to divide
* @param b second value to divide
* @return c = a / b
*/
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
}
/*
* TokenRecepient
*
* Copyright © 2017 by Hive Project Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND (express or implied).
*/
contract TokenRecipient {
/**
* receive approval
*/
function receiveApproval(address _from, uint256 _value, address _to, bytes _extraData);
}
/**
* Standard Token Smart Contract that implements ERC-20 token interface
*/
contract HVNToken is ERC20Interface, SafeMath, Owned {
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
string public constant name = "Hive Project Token";
string public constant symbol = "HVN";
uint8 public constant decimals = 8;
string public version = '0.0.2';
bool public transfersFrozen = false;
/**
* Protection against short address attack
*/
modifier onlyPayloadSize(uint numwords) {
assert(msg.data.length == numwords * 32 + 4);
_;
}
/**
* Check if transfers are on hold - frozen
*/
modifier whenNotFrozen(){
if (transfersFrozen) revert();
_;
}
function HVNToken() ownerOnly {
totalSupply = 50000000000000000;
balances[owner] = totalSupply;
}
/**
* Freeze token transfers.
*/
function freezeTransfers () ownerOnly {
if (!transfersFrozen) {
transfersFrozen = true;
Freeze (msg.sender);
}
}
/**
* Unfreeze token transfers.
*/
function unfreezeTransfers () ownerOnly {
if (transfersFrozen) {
transfersFrozen = false;
Unfreeze (msg.sender);
}
}
/**
* Transfer sender's tokens to a given address
*/
function transfer(address _to, uint256 _value) whenNotFrozen onlyPayloadSize(2) returns (bool success) {
require(_to != 0x0);
balances[msg.sender] = sub(balances[msg.sender], _value);
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer _from's tokens to _to's address
*/
function transferFrom(address _from, address _to, uint256 _value) whenNotFrozen onlyPayloadSize(3) returns (bool success) {
require(_to != 0x0);
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value);
balances[_from] = sub(balances[_from], _value);
balances[_to] += _value;
allowed[_from][msg.sender] = sub(allowed[_from][msg.sender], _value);
Transfer(_from, _to, _value);
return true;
}
/**
* Returns number of tokens owned by given address.
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
/**
* Sets approved amount of tokens for spender.
*/
function approve(address _spender, uint256 _value) returns (bool success) {
require(_value == 0 || allowed[msg.sender][_spender] == 0);
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* Approve and then communicate the approved contract in a single transaction
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Returns number of allowed tokens for given address.
*/
function allowance(address _owner, address _spender) onlyPayloadSize(2) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* Peterson's Law Protection
* Claim tokens
*/
function claimTokens(address _token) ownerOnly {
if (_token == 0x0) {
owner.transfer(this.balance);
return;
}
HVNToken token = HVNToken(_token);
uint balance = token.balanceOf(this);
token.transfer(owner, balance);
Transfer(_token, owner, balance);
}
event Freeze (address indexed owner);
event Unfreeze (address indexed owner);
}
| * ERC-20 standard token interface, as defined/ | contract ERC20Interface {
uint256 public totalSupply;
function balanceOf (address _owner) constant returns (uint256 balance);
function transfer (address _to, uint256 _value) returns (bool success);
function transferFrom (address _from, address _to, uint256 _value)
returns (bool success);
function approve (address _spender, uint256 _value) returns (bool success);
function allowance (address _owner, address _spender) constant
returns (uint256 remaining);
event Transfer (address indexed _from, address indexed _to, uint256 _value);
event Approval (
address indexed _owner, address indexed _spender, uint256 _value);
}
| 915,849 | [
1,
654,
39,
17,
3462,
4529,
1147,
1560,
16,
487,
2553,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
4232,
39,
3462,
1358,
288,
203,
225,
2254,
5034,
1071,
2078,
3088,
1283,
31,
203,
203,
225,
445,
11013,
951,
261,
2867,
389,
8443,
13,
5381,
1135,
261,
11890,
5034,
11013,
1769,
203,
203,
225,
445,
7412,
261,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1135,
261,
6430,
2216,
1769,
203,
203,
225,
445,
7412,
1265,
261,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
13,
203,
225,
1135,
261,
6430,
2216,
1769,
203,
203,
225,
445,
6617,
537,
261,
2867,
389,
87,
1302,
264,
16,
2254,
5034,
389,
1132,
13,
1135,
261,
6430,
2216,
1769,
203,
203,
225,
445,
1699,
1359,
261,
2867,
389,
8443,
16,
1758,
389,
87,
1302,
264,
13,
5381,
203,
225,
1135,
261,
11890,
5034,
4463,
1769,
203,
203,
225,
871,
12279,
261,
2867,
8808,
389,
2080,
16,
1758,
8808,
389,
869,
16,
2254,
5034,
389,
1132,
1769,
203,
203,
225,
871,
1716,
685,
1125,
261,
203,
565,
1758,
8808,
389,
8443,
16,
1758,
8808,
389,
87,
1302,
264,
16,
2254,
5034,
389,
1132,
1769,
203,
203,
203,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.25;
// just ownable contract
contract Ownable {
address public owner;
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) external onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
// Pausable contract which allows children to implement an emergency stop mechanism.
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
// Modifier to make a function callable only when the contract is not paused.
modifier whenNotPaused() {
require(!paused);
_;
}
// Modifier to make a function callable only when the contract is paused.
modifier whenPaused() {
require(paused);
_;
}
// Сalled by the owner to pause, triggers stopped state
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
// Сalled by the owner to unpause, returns to normal state
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
// Interface for pet contract
contract ParentInterface {
function ownerOf(uint256 _tokenId) external view returns (address owner);
function getPet(uint256 _id) external view returns (uint64 birthTime, uint256 genes,uint64 breedTimeout,uint16 quality,address owner);
function totalSupply() public view returns (uint);
}
// Simple utils, which calculate circle seats and grade by quality
contract Utils {
function getGradeByQuailty(uint16 quality) public pure returns (uint8 grade) {
require(quality <= uint16(0xF000));
require(quality >= uint16(0x1000));
if(quality == uint16(0xF000))
return 7;
quality+= uint16(0x1000);
return uint8 ( quality / uint16(0x2000) );
}
function seatsByGrade(uint8 grade) public pure returns(uint8 seats) {
if(grade > 4)
return 1;
seats = 8 - grade - 2;
return seats;
}
}
// Main contract, which calculating queue
contract ReferralQueue {
// ID in circle
uint64 currentReceiverId = 1;
// Circle length
uint64 public circleLength;
// Store queue of referral circle
struct ReferralSeat {
uint64 petId;
uint64 givenPetId;
}
mapping (uint64 => ReferralSeat) public referralCircle;
// Store simple information about each pet: parent parrot and current referral reward
struct PetInfo {
uint64 parentId;
uint256 amount;
}
mapping (uint64 => PetInfo) public petsInfo;
function addPetIntoCircle(uint64 _id, uint8 _seats) internal {
// Adding seats into queue
for(uint8 i=0; i < _seats; i++)
{
ReferralSeat memory _seat = ReferralSeat({
petId: _id,
givenPetId: 0
});
// Increasing circle length and save current seat in circle
circleLength++;
referralCircle[circleLength] = _seat;
}
// Attach the parrot to the current receiver in the circle
// First 3 parrots adding without attaching
if(_id>103) {
referralCircle[currentReceiverId].givenPetId = _id;
// adding new pet into information list
PetInfo memory petInfo = PetInfo({
parentId: referralCircle[currentReceiverId].petId,
amount: 0
});
petsInfo[_id] = petInfo;
// Increace circle receiver ID
currentReceiverId++;
}
}
// Current pet ID in circle for automatical attach
function getCurrentReceiverId() view public returns(uint64 receiverId) {
return referralCircle[currentReceiverId].petId;
}
}
contract Reward is ReferralQueue {
// Getting egg price by id and quality
function getEggPrice(uint64 _petId, uint16 _quality) pure public returns(uint256 price) {
uint64[6] memory egg_prices = [0, 150 finney, 600 finney, 3 ether, 12 ether, 600 finney];
uint8 egg = 2;
if(_quality > 55000)
egg = 1;
if(_quality > 26000 && _quality < 26500)
egg = 3;
if(_quality > 39100 && _quality < 39550)
egg = 3;
if(_quality > 31000 && _quality < 31250)
egg = 4;
if(_quality > 34500 && _quality < 35500)
egg = 5;
price = egg_prices[egg];
uint8 discount = 10;
if(_petId<= 600)
discount = 20;
if(_petId<= 400)
discount = 30;
if(_petId<= 200)
discount = 50;
if(_petId<= 120)
discount = 80;
price = price - (price*discount / 100);
}
// Save rewards for all referral levels
function applyReward(uint64 _petId, uint16 _quality) internal {
uint8[6] memory rewardByLevel = [0,250,120,60,30,15];
uint256 eggPrice = getEggPrice(_petId, _quality);
uint64 _currentPetId = _petId;
// make rewards for 5 levels
for(uint8 level=1; level<=5; level++) {
uint64 _parentId = petsInfo[_currentPetId].parentId;
// if no parent referral - break
if(_parentId == 0)
break;
// increase pet balance
petsInfo[_parentId].amount+= eggPrice * rewardByLevel[level] / 1000;
// get parent id from parent id to move to the next level
_currentPetId = _parentId;
}
}
// Save rewards for all referral levels
function applyRewardByAmount(uint64 _petId, uint256 _price) internal {
uint8[6] memory rewardByLevel = [0,250,120,60,30,15];
uint64 _currentPetId = _petId;
// Make rewards for 5 levels
for(uint8 i=1; i<=5; i++) {
uint64 _parentId = petsInfo[_currentPetId].parentId;
// if no parent referral - break
if(_parentId == 0)
break;
// Increase pet balance
petsInfo[_parentId].amount+= _price * rewardByLevel[i] / 1000;
// Get parent id from parent id to move to the next level
_currentPetId = _parentId;
}
}
}
// Launch it
contract ReferralCircle is Reward, Utils, Pausable {
// Interface link
ParentInterface public parentInterface;
// Limit of manual synchronization repeats
uint8 public syncLimit = 5;
// Pet counter
uint64 public lastPetId = 100;
// Manual sync enabled
bool public petSyncEnabled = true;
// Setting default parent interface
constructor() public {
parentInterface = ParentInterface(0x115f56742474f108AD3470DDD857C31a3f626c3C);
}
// Disable manual synchronization
function disablePetSync() external onlyOwner {
petSyncEnabled = false;
}
// Enable manual synchronization
function enablePetSync() external onlyOwner {
petSyncEnabled = true;
}
// Make synchronization, available for any sender
function sync() external whenNotPaused {
// Checking synchronization status
require(petSyncEnabled);
// Get supply of pets from parent contract
uint64 petSupply = uint64(parentInterface.totalSupply());
require(petSupply > lastPetId);
// Synchronize pets
for(uint8 i=0; i < syncLimit; i++)
{
lastPetId++;
if(lastPetId > petSupply)
{
lastPetId = petSupply;
break;
}
addPet(lastPetId);
}
}
// Change synchronization limit by owner
function setSyncLimit(uint8 _limit) external onlyOwner {
syncLimit = _limit;
}
// Function of manual add pet
function addPet(uint64 _id) internal {
(uint64 birthTime, uint256 genes, uint64 breedTimeout, uint16 quality, address owner) = parentInterface.getPet(_id);
uint16 gradeQuality = quality;
// For first pets - bonus quality in grade calculating
if(_id < 244)
gradeQuality = quality - 13777;
// Calculating seats in circle
uint8 petGrade = getGradeByQuailty(gradeQuality);
uint8 petSeats = seatsByGrade(petGrade);
// Adding pet into circle
addPetIntoCircle(_id, petSeats);
// Save reward for each referral level
applyReward(_id, quality);
}
// Function for automatic add pet
function automaticPetAdd(uint256 _price, uint16 _quality, uint64 _id) external {
require(!petSyncEnabled);
require(msg.sender == address(parentInterface));
lastPetId = _id;
// Calculating seats in circle
uint8 petGrade = getGradeByQuailty(_quality);
uint8 petSeats = seatsByGrade(petGrade);
// Adding pet into circle
addPetIntoCircle(_id, petSeats);
// Save reward for each referral level
applyRewardByAmount(_id, _price);
}
// Function for withdraw reward by pet owner
function withdrawReward(uint64 _petId) external whenNotPaused {
// Get pet information
PetInfo memory petInfo = petsInfo[_petId];
// Get owner of pet from pet contract and check it
(uint64 birthTime, uint256 genes, uint64 breedTimeout, uint16 quality, address petOwner) = parentInterface.getPet(_petId);
require(petOwner == msg.sender);
// Transfer reward
msg.sender.transfer(petInfo.amount);
// Change reward amount in pet information
petInfo.amount = 0;
petsInfo[_petId] = petInfo;
}
// Emergency reward sending by admin
function sendRewardByAdmin(uint64 _petId) external onlyOwner whenNotPaused {
// Get pet information
PetInfo memory petInfo = petsInfo[_petId];
// Get owner of pet from pet contract and check it
(uint64 birthTime, uint256 genes, uint64 breedTimeout, uint16 quality, address petOwner) = parentInterface.getPet(_petId);
// Transfer reward
petOwner.transfer(petInfo.amount);
// Change reward amount in pet information
petInfo.amount = 0;
petsInfo[_petId] = petInfo;
}
// Change parent contract
function setParentAddress(address _address) public whenPaused onlyOwner
{
parentInterface = ParentInterface(_address);
}
// Just refill
function () public payable {}
// Withdraw balance by owner
function withdrawBalance(uint256 summ) external onlyOwner {
owner.transfer(summ);
}
} | Increasing circle length and save current seat in circle | circleLength++;
| 5,542,914 | [
1,
27597,
11730,
12470,
769,
471,
1923,
783,
695,
270,
316,
12470,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5411,
12470,
1782,
9904,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.1;
import "./IERC20.sol";
contract SimpleERC20 is IERC20 {
string public symbol;
string public name;
uint8 public decimals;
uint256 public override totalSupply;
// Owner of this contract
address public owner;
// Balances for each account
mapping(address => uint256) private balances;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint256)) private allowed;
// Functions with this modifier can only be executed by the owner
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
// solhint-disable func-visibility
constructor(string memory _symbol, string memory _name, uint8 _decimals, uint256 _initialBalance) {
owner = msg.sender;
symbol = _symbol;
name = _name;
decimals = _decimals;
balances[owner] = _initialBalance;
totalSupply = _initialBalance;
}
// solhint-enable func-visibility
// What is the balance of a particular account?
function balanceOf(address _owner) external view override returns (uint256 balance) {
return balances[_owner];
}
// Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _amount) external override returns (bool success) {
if (balances[msg.sender] >= _amount && balances[_to] + _amount > balances[_to]) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
// Send _value amount of tokens from address _from to address _to
// The transferFrom method is used for a withdraw workflow, allowing contracts to send
// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
// fees in sub-currencies; the command should fail unless the _from account has
// deliberately authorized the sender of the message via some mechanism; we propose
// these standardized APIs for approval:
function transferFrom(address _from, address _to, uint256 _amount) external override returns (bool success) {
// solhint-disable bracket-align
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& balances[_to] + _amount > balances[_to])
{
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
// solhint-enable bracket-align
}
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _amount) external override returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) external view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
} | Transfer the balance from owner's account to another account | function transfer(address _to, uint256 _amount) external override returns (bool success) {
if (balances[msg.sender] >= _amount && balances[_to] + _amount > balances[_to]) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
return false;
}
}
| 905,290 | [
1,
5912,
326,
11013,
628,
3410,
1807,
2236,
358,
4042,
2236,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
3903,
3849,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
309,
261,
70,
26488,
63,
3576,
18,
15330,
65,
1545,
389,
8949,
597,
324,
26488,
63,
67,
869,
65,
397,
389,
8949,
405,
324,
26488,
63,
67,
869,
5717,
288,
203,
5411,
324,
26488,
63,
3576,
18,
15330,
65,
3947,
389,
8949,
31,
203,
5411,
324,
26488,
63,
67,
869,
65,
1011,
389,
8949,
31,
203,
5411,
12279,
12,
3576,
18,
15330,
16,
389,
869,
16,
389,
8949,
1769,
203,
5411,
327,
638,
31,
203,
5411,
327,
629,
31,
203,
3639,
289,
203,
565,
289,
203,
7010,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/288/0x9007A80247D23Cc5C213A6DAcB385c632c4e19F2/sources/contracts/bridge/SynapseBridge.sol | BRIDGE FUNCTIONS TO HANDLE DIFF ADDRESSES* @notice Relays to nodes that (typically) a wrapped synAsset ERC20 token has been burned and the underlying needs to be redeeemed on the native chain @param to address on other chain to redeem underlying assets to @param chainId which underlying chain to bridge assets onto @param token ERC20 compatible token to deposit into the bridge @param amount Amount in native token decimals to transfer cross-chain pre-fees/ | function redeemV2(
bytes32 to,
uint256 chainId,
ERC20Burnable token,
uint256 amount
) external nonReentrant() whenNotPaused() {
emit TokenRedeemV2(to, chainId, token, amount);
token.burnFrom(msg.sender, amount);
}
| 7,103,837 | [
1,
7192,
734,
7113,
13690,
55,
8493,
24166,
900,
3690,
2246,
11689,
7031,
1090,
55,
225,
4275,
8271,
358,
2199,
716,
261,
12846,
6478,
13,
279,
5805,
6194,
6672,
4232,
39,
3462,
1147,
711,
2118,
18305,
329,
471,
326,
6808,
4260,
358,
506,
283,
20953,
351,
329,
603,
326,
6448,
2687,
225,
358,
1758,
603,
1308,
2687,
358,
283,
24903,
6808,
7176,
358,
225,
2687,
548,
1492,
6808,
2687,
358,
10105,
7176,
10170,
225,
1147,
4232,
39,
3462,
7318,
1147,
358,
443,
1724,
1368,
326,
10105,
225,
3844,
16811,
316,
6448,
1147,
15105,
358,
7412,
6828,
17,
5639,
675,
17,
3030,
281,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
283,
24903,
58,
22,
12,
203,
565,
1731,
1578,
358,
16,
203,
565,
2254,
5034,
2687,
548,
16,
203,
565,
4232,
39,
3462,
38,
321,
429,
1147,
16,
203,
565,
2254,
5034,
3844,
203,
225,
262,
3903,
1661,
426,
8230,
970,
1435,
1347,
1248,
28590,
1435,
288,
203,
565,
3626,
3155,
426,
24903,
58,
22,
12,
869,
16,
2687,
548,
16,
1147,
16,
3844,
1769,
203,
565,
1147,
18,
70,
321,
1265,
12,
3576,
18,
15330,
16,
3844,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-03-04
*/
// File: node_modules\@openzeppelin\contracts\token\ERC20\IERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: node_modules\@openzeppelin\contracts\math\SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: node_modules\@openzeppelin\contracts\utils\Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin\contracts\token\ERC20\SafeERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: node_modules\@openzeppelin\contracts\GSN\Context.sol
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: node_modules\@openzeppelin\contracts\token\ERC20\ERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: @openzeppelin\contracts\token\ERC20\ERC20Burnable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
using SafeMath for uint256;
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
// File: contracts\ENERGY.sol
pragma solidity 0.7.6;
contract ENERGY is ERC20Burnable {
using SafeMath for uint256;
uint256 public constant initialSupply = 89099136 * 10 ** 3;
uint256 public lastWeekTime;
uint256 public weekCount;
//staking start when week count set to 1 -> rewards calculated before just updating week
uint256 public constant totalWeeks = 100;
address public stakingContrAddr;
address public liquidityContrAddr;
uint256 public constant timeStep = 1 weeks;
modifier onlyStaking() {
require(_msgSender() == stakingContrAddr, "Not staking contract");
_;
}
constructor (address _liquidityContrAddr) ERC20("ENERGY", "NRGY") {
//89099.136 coins
_setupDecimals(6);
lastWeekTime = block.timestamp;
liquidityContrAddr = _liquidityContrAddr;
_mint(_msgSender(), initialSupply.mul(4).div(10)); //40%
_mint(liquidityContrAddr, initialSupply.mul(6).div(10)); //60%
}
function mintNewCoins(uint256[3] memory lastWeekRewards) public onlyStaking returns(bool) {
if(weekCount >= 1) {
uint256 newMint = lastWeekRewards[0].add(lastWeekRewards[1]).add(lastWeekRewards[2]);
uint256 liquidityMint = (newMint.mul(20)).div(100);
_mint(liquidityContrAddr, liquidityMint);
_mint(stakingContrAddr, newMint);
} else {
_mint(liquidityContrAddr, initialSupply);
}
return true;
}
//updates only at end of week
function updateWeek() public onlyStaking {
weekCount++;
lastWeekTime = block.timestamp;
}
function updateStakingContract(address _stakingContrAddr) public {
require(stakingContrAddr == address(0), "Staking contract is already set");
stakingContrAddr = _stakingContrAddr;
}
function burnOnUnstake(address account, uint256 amount) public onlyStaking {
_burn(account, amount);
}
function getLastWeekUpdateTime() public view returns(uint256) {
return lastWeekTime;
}
function isMintingCompleted() public view returns(bool) {
if(weekCount > totalWeeks) {
return true;
} else {
return false;
}
}
function isGreaterThanAWeek() public view returns(bool) {
if(block.timestamp > getLastWeekUpdateTime().add(timeStep)) {
return true;
} else {
return false;
}
}
}
// File: contracts\NRGYMarketMaker.sol
pragma solidity 0.7.6;
contract NRGYMarketMaker {
using SafeERC20 for IERC20;
using SafeMath for uint256;
struct UserData {
address user;
bool isActive;
uint256 rewards;
uint256 feeRewards;
uint256 depositTime;
uint256 share;
//update when user came first time or after unstaking to stake
uint256 startedWeek;
//update everytime whenever user comes to unstake
uint256 endedWeek;
mapping(uint256 => uint256) shareByWeekNo;
}
struct FeeRewardData {
uint256 value;
uint256 timeStamp;
uint256 totalStakersAtThatTime;
uint256 weekGiven;
mapping(address => bool) isClaimed;
}
ENERGY public energy;
IERC20 public lpToken;
uint256 public totalShares;
//initially it will be 27000
uint256[] public stakingLimit;
uint256 public constant minStakeForFeeRewards = 25 * 10 ** 6;
uint256 public totalRewards;
uint256 public totalFeeRewards;
uint256 public rewardsAvailableInContract;
uint256 public feeRewardsAvailableInContract;
uint256 public feeRewardsCount;
uint256 public totalStakeUsers;
uint256 public constant percentageDivider = 100;
//10%, 30%, 60%
uint256[3] private rewardPercentages = [10, 30, 60];
//7.5%
uint256 public constant unstakeFees = 75;
//total weeks
uint256 public totalWeeks;
//user informations
mapping(uint256 => address) public userList;
mapping(address => UserData) public userInfo;
mapping (address => bool) public smartContractStakers;
//contract info
mapping(uint256 => uint256) private stakePerWeek;
mapping(uint256 => uint256) private totalSharesByWeek;
mapping(uint256 => uint256[3]) private rewardByWeek;
mapping(uint256 => FeeRewardData) private feeRewardData;
event Staked(address indexed _user, uint256 _amountStaked, uint256 _balanceOf);
event Withdrawn(address indexed _user,
uint256 _amountTransferred,
uint256 _amountUnstaked,
uint256 _shareDeducted,
uint256 _rewardsDeducted,
uint256 _feeRewardsDeducted);
event RewardDistributed(uint256 _weekNo, uint256[3] _lastWeekRewards);
event FeeRewardDistributed(uint256 _amount, uint256 _totalFeeRewards);
constructor(address _energy) {
energy = ENERGY(_energy);
lpToken = IERC20(_energy);
totalWeeks = energy.totalWeeks();
stakingLimit.push(27000 * 10 ** 6);
}
// stake the coins
function stake(uint256 amount) public {
_stake(amount, tx.origin);
}
function stakeOnBehalf(uint256 amount, address _who) public {
_stake(amount, _who);
}
function _stake(uint256 _amount, address _who) internal {
uint256 _weekCount = energy.weekCount();
bool isWeekOver = energy.isGreaterThanAWeek();
if((_weekCount >= 1 && !isWeekOver) || _weekCount == 0) {
require(!isStakingLimitReached(_amount, _weekCount), "Stake limit has been reached");
}
//if week over or week is 0
if(!isWeekOver || _weekCount == 0) {
//add current week stake
stakePerWeek[_weekCount] = getStakeByWeekNo(_weekCount).add(_amount);
// update current week cumulative stake
//store total shares by week no at time of stake
totalSharesByWeek[_weekCount] = totalShares.add(_amount);
userInfo[_who].shareByWeekNo[_weekCount] = getUserShareByWeekNo(_who, _weekCount).add(_amount);
//if current week share is 0 get share for previous week
if(_weekCount == 0) {
if(stakingLimit[0] == totalShares.add(_amount)) {
setStakingLimit(_weekCount, stakingLimit[0]);
energy.mintNewCoins(getRewardsByWeekNo(0));
energy.updateWeek();
}
}
} else/*is week is greater than 1 and is over */ {
//update this week shae by adding previous week share
userInfo[_who].shareByWeekNo[_weekCount.add(1)] = getUserShareByWeekNo(_who, _weekCount).add(_amount);
//update next week stake
stakePerWeek[_weekCount.add(1)] = getStakeByWeekNo(_weekCount.add(1)).add(_amount);
//update next week cumulative stake
//store total shares of next week no at time of stake
totalSharesByWeek[_weekCount.add(1)] = totalShares.add(_amount);
setStakingLimit(_weekCount, totalShares);
energy.updateWeek();
//if week over update followings and greater than 1
/*give rewards only after week end and till 3 more weeks of total weeks */
if(_weekCount <= totalWeeks.add(3)) {
//store rewards generated that week by week no at end of week
//eg: when week 1 is over, it will store rewards generated that week before week changed from 1 to 2
setRewards(_weekCount);
uint256 rewardDistributed = (rewardByWeek[_weekCount][0])
.add(rewardByWeek[_weekCount][1])
.add(rewardByWeek[_weekCount][2]);
totalRewards = totalRewards.add(rewardDistributed);
energy.mintNewCoins(getRewardsByWeekNo(_weekCount));
rewardsAvailableInContract = rewardsAvailableInContract.add(rewardDistributed);
emit RewardDistributed(_weekCount, getRewardsByWeekNo(_weekCount));
}
}
//if user not active, set current week as his start week
if(!getUserStatus(_who)) {
userInfo[_who].isActive = true;
if(getUserShare(_who) < minStakeForFeeRewards) {
userInfo[_who].startedWeek = _weekCount;
userInfo[_who].depositTime = block.timestamp;
}
}
if(!isUserPreviouslyStaked(_who)) {
userList[totalStakeUsers] = _who;
totalStakeUsers++;
smartContractStakers[_who] = true;
userInfo[_who].user = _who;
}
userInfo[_who].share = userInfo[_who].share.add(_amount);
//update total shares in the end
totalShares = totalShares.add(_amount);
//if-> user is directly staking
if(msg.sender == tx.origin) {
// now we can issue shares
lpToken.safeTransferFrom(_who, address(this), _amount);
} else /*through liquity contract */ {
// now we can issue shares
//transfer from liquidty contract
lpToken.safeTransferFrom(msg.sender, address(this), _amount);
}
emit Staked(_who, _amount, claimedBalanceOf(_who));
}
function setStakingLimit(uint256 _weekCount, uint256 _share) internal {
uint256 lastWeekStakingLeft = stakingLimit[_weekCount].sub(getStakeByWeekNo(_weekCount));
// first 4 weeks are: 0,1,2,3
if(_weekCount <= 3) {
//32%
stakingLimit.push((_share.mul(32)).div(percentageDivider));
}
if(_weekCount > 3) {
//0.04%
stakingLimit.push((_share.mul(4)).div(percentageDivider));
}
stakingLimit[_weekCount.add(1)] = stakingLimit[_weekCount.add(1)].add(lastWeekStakingLeft);
}
function setRewards(uint256 _weekCount) internal {
(rewardByWeek[_weekCount][0],
rewardByWeek[_weekCount][1],
rewardByWeek[_weekCount][2]) = calculateRewardsByWeekCount(_weekCount);
}
function calculateRewards() public view returns(uint256 _lastWeekReward, uint256 _secondLastWeekReward, uint256 _thirdLastWeekReward) {
return calculateRewardsByWeekCount(energy.weekCount());
}
function calculateRewardsByWeekCount(uint256 _weekCount) public view returns(uint256 _lastWeekReward, uint256 _secondLastWeekReward, uint256 _thirdLastWeekReward) {
bool isLastWeek = (_weekCount >= totalWeeks);
if(isLastWeek) {
if(_weekCount.sub(totalWeeks) == 0) {
_lastWeekReward = (getStakeByWeekNo(_weekCount).mul(rewardPercentages[0])).div(percentageDivider);
_secondLastWeekReward = (getStakeByWeekNo(_weekCount.sub(1)).mul(rewardPercentages[1])).div(percentageDivider);
_thirdLastWeekReward = (getStakeByWeekNo(_weekCount.sub(2)).mul(rewardPercentages[2])).div(percentageDivider);
} else if(_weekCount.sub(totalWeeks) == 1) {
_secondLastWeekReward = (getStakeByWeekNo(_weekCount.sub(1)).mul(rewardPercentages[1])).div(percentageDivider);
_thirdLastWeekReward = (getStakeByWeekNo(_weekCount.sub(2)).mul(rewardPercentages[2])).div(percentageDivider);
} else if(_weekCount.sub(totalWeeks) == 2) {
_thirdLastWeekReward = (getStakeByWeekNo(_weekCount.sub(2)).mul(rewardPercentages[2])).div(percentageDivider);
}
} else {
if(_weekCount == 1) {
_lastWeekReward = (getStakeByWeekNo(_weekCount).mul(rewardPercentages[0])).div(percentageDivider);
} else if(_weekCount == 2) {
_lastWeekReward = (getStakeByWeekNo(_weekCount).mul(rewardPercentages[0])).div(percentageDivider);
_secondLastWeekReward = (getStakeByWeekNo(_weekCount.sub(1)).mul(rewardPercentages[1])).div(percentageDivider);
} else if(_weekCount >= 3) {
_lastWeekReward = (getStakeByWeekNo(_weekCount).mul(rewardPercentages[0])).div(percentageDivider);
_secondLastWeekReward = (getStakeByWeekNo(_weekCount.sub(1)).mul(rewardPercentages[1])).div(percentageDivider);
_thirdLastWeekReward = (getStakeByWeekNo(_weekCount.sub(2)).mul(rewardPercentages[2])).div(percentageDivider);
}
}
}
function isStakingLimitReached(uint256 _amount, uint256 _weekCount) public view returns(bool) {
return (getStakeByWeekNo(_weekCount).add(_amount) > stakingLimit[_weekCount]);
}
function remainingStakingLimit(uint256 _weekCount) public view returns(uint256) {
return (stakingLimit[_weekCount].sub(getStakeByWeekNo(_weekCount)));
}
function distributeFees(uint256 _amount) public {
uint256 _weekCount = energy.weekCount();
FeeRewardData storage _feeRewardData = feeRewardData[feeRewardsCount];
_feeRewardData.value = _amount;
_feeRewardData.timeStamp = block.timestamp;
_feeRewardData.totalStakersAtThatTime = totalStakeUsers;
_feeRewardData.weekGiven = _weekCount;
feeRewardsCount++;
totalFeeRewards = totalFeeRewards.add(_amount);
feeRewardsAvailableInContract = feeRewardsAvailableInContract.add(_amount);
lpToken.safeTransferFrom(msg.sender, address(this), _amount);
emit FeeRewardDistributed(_amount, totalFeeRewards);
}
///unstake the coins
function unstake(uint256 _amount) public {
UserData storage _user = userInfo[msg.sender];
uint256 _weekCount = energy.weekCount();
//get user rewards till date(week) and add to claimed rewards
userInfo[msg.sender].rewards = _user.rewards
.add(getUserRewardsByWeekNo(msg.sender, _weekCount));
//get user fee rewards till date(week) and add to claimed fee rewards
userInfo[msg.sender].feeRewards = _user.feeRewards.add(_calculateFeeRewards(msg.sender));
require(_amount <= claimedBalanceOf(msg.sender), "Unstake amount is greater than user balance");
//calculate unstake fee
uint256 _fees = (_amount.mul(unstakeFees)).div(1000);
//calulcate amount to transfer to user
uint256 _toTransfer = _amount.sub(_fees);
//burn unstake fees
energy.burnOnUnstake(address(this), _fees);
lpToken.safeTransfer(msg.sender, _toTransfer);
//if amount can be paid from rewards
if(_amount <= getUserTotalRewards(msg.sender)) {
//if amount can be paid from rewards
if(_user.rewards >= _amount) {
_user.rewards = _user.rewards.sub(_amount);
rewardsAvailableInContract = rewardsAvailableInContract.sub(_amount);
emit Withdrawn(msg.sender, _toTransfer, _amount, 0, _amount, 0);
} else/*else take sum of fee rewards and rewards */ {
//get remaining amount less than rewards
uint256 remAmount = _amount.sub(_user.rewards);
rewardsAvailableInContract = rewardsAvailableInContract.sub(_user.rewards);
feeRewardsAvailableInContract = feeRewardsAvailableInContract.sub(remAmount);
emit Withdrawn(msg.sender, _toTransfer, _amount, 0, _user.rewards, remAmount);
//update fee rewards from remaining amount
_user.rewards = 0;
_user.feeRewards = _user.feeRewards.sub(remAmount);
}
} else/* take from total shares*/ {
//get remaining amount less than rewards
uint256 remAmount = _amount.sub(getUserTotalRewards(msg.sender));
rewardsAvailableInContract = rewardsAvailableInContract.sub(_user.rewards);
feeRewardsAvailableInContract = feeRewardsAvailableInContract.sub(_user.feeRewards);
emit Withdrawn(msg.sender, _toTransfer, _amount, remAmount, _user.rewards, _user.feeRewards);
_user.rewards = 0;
_user.feeRewards = 0;
//update user share from remaining amount
_user.share = _user.share.sub(remAmount);
//update total shares
totalShares = totalShares.sub(remAmount);
//update total shares by week no at time of unstake
totalSharesByWeek[_weekCount] = totalSharesByWeek[_weekCount].sub(remAmount);
}
lpToken.safeApprove(address(this), 0);
//set user status to false
_user.isActive = false;
//update user end(unstake) week
_user.endedWeek = _weekCount == 0 ? _weekCount : _weekCount.sub(1);
}
function _calculateFeeRewards(address _who) internal returns(uint256) {
uint256 _accumulatedRewards;
//check if user have minimum share too claim fee rewards
if(getUserShare(_who) >= minStakeForFeeRewards) {
//loop through all the rewards
for(uint256 i = 0; i < feeRewardsCount; i++) {
//if rewards week and timestamp is greater than user deposit time and rewards.
//Also only if user has not claimed particular fee rewards
if(getUserStartedWeek(_who) <= feeRewardData[i].weekGiven
&& getUserLastDepositTime(_who) < feeRewardData[i].timeStamp
&& !feeRewardData[i].isClaimed[_who]) {
_accumulatedRewards = _accumulatedRewards.add(feeRewardData[i].value.div(feeRewardData[i].totalStakersAtThatTime));
feeRewardData[i].isClaimed[_who] = true;
}
}
}
return _accumulatedRewards;
}
/*
* ------------------Getter inteface for user---------------------
*
*/
function getUserUnclaimedFeesRewards(address _who) public view returns(uint256) {
uint256 _accumulatedRewards;
//check if user have minimum share too claim fee rewards
if(getUserShare(_who) >= minStakeForFeeRewards) {
//loop through all the rewards
for(uint256 i = 0; i < feeRewardsCount; i++) {
//if rewards week and timestamp is greater than user deposit time and rewards.
//Also only if user has not claimed particular fee rewards
if(getUserStartedWeek(_who) <= feeRewardData[i].weekGiven
&& getUserLastDepositTime(_who) < feeRewardData[i].timeStamp
&& !feeRewardData[i].isClaimed[_who]) {
_accumulatedRewards = _accumulatedRewards.add(feeRewardData[i].value.div(feeRewardData[i].totalStakersAtThatTime));
}
}
}
return _accumulatedRewards;
}
//return rewards till weekcount passed
function getUserCurrentRewards(address _who) public view returns(uint256) {
uint256 _weekCount = energy.weekCount();
uint256[3] memory thisWeekReward;
(thisWeekReward[0],
thisWeekReward[1],
thisWeekReward[2]) = calculateRewardsByWeekCount(_weekCount);
uint256 userShareAtThatWeek = getUserPercentageShareByWeekNo(_who, _weekCount);
return getUserRewardsByWeekNo(_who, _weekCount)
.add(_calculateRewardByUserShare(thisWeekReward, userShareAtThatWeek))
.add(getUserRewards(_who));
}
//return rewards till one week less than the weekcount passed
//calculate rewards till previous week and deduct rewards claimed at time of unstake
//return rewards available to claim
function getUserRewardsByWeekNo(address _who, uint256 _weekCount) public view returns(uint256) {
uint256 rewardsAccumulated;
uint256 userEndWeek = getUserEndedWeek(_who);
//clculate rewards only if user is active or user share is greater than 1
if(getUserStatus(_who) || (getUserShare(_who) > 0)) {
for(uint256 i = userEndWeek.add(1); i < _weekCount; i++) {
uint256 userShareAtThatWeek = getUserPercentageShareByWeekNo(_who, i);
rewardsAccumulated = rewardsAccumulated.add(_calculateRewardByUserShare(getRewardsByWeekNo(i), userShareAtThatWeek));
}
}
return rewardsAccumulated;
}
function _calculateRewardByUserShare(uint256[3] memory rewardAtThatWeek, uint256 userShareAtThatWeek) internal pure returns(uint256) {
return (((rewardAtThatWeek[0]
.add(rewardAtThatWeek[1])
.add(rewardAtThatWeek[2]))
.mul(userShareAtThatWeek))
.div(percentageDivider.mul(percentageDivider)));
}
function getUserPercentageShareByWeekNo(address _who, uint256 _weekCount) public view returns(uint256) {
return _getUserPercentageShareByValue(getSharesByWeekNo(_weekCount), getUserShareByWeekNo(_who, _weekCount));
}
function _getUserPercentageShareByValue(uint256 _totalShares, uint256 _userShare) internal pure returns(uint256) {
if(_totalShares == 0 || _userShare == 0) {
return 0;
} else {
//two times percentageDivider multiplied because of decimal percentage which are less than 1
return (_userShare.mul(percentageDivider.mul(percentageDivider))).div(_totalShares);
}
}
//give sum of share(staked amount) + rewards is user have a claimed it through unstaking
function claimedBalanceOf(address _who) public view returns(uint256) {
return getUserShare(_who).add(getUserRewards(_who)).add(getUserFeeRewards(_who));
}
function getUserRewards(address _who) public view returns(uint256) {
return userInfo[_who].rewards;
}
function getUserFeeRewards(address _who) public view returns(uint256) {
return userInfo[_who].feeRewards;
}
function getUserTotalRewards(address _who) public view returns(uint256) {
return userInfo[_who].feeRewards.add(userInfo[_who].rewards);
}
function getUserShare(address _who) public view returns(uint256) {
return userInfo[_who].share;
}
function getUserShareByWeekNo(address _who, uint256 _weekCount) public view returns(uint256) {
if(getUserStatus(_who)) {
return (_userShareByWeekNo(_who, _weekCount) > 0 || _weekCount == 0)
? _userShareByWeekNo(_who, _weekCount)
: getUserShareByWeekNo(_who, _weekCount.sub(1));
} else if(getUserShare(_who) > 0) {
return getUserShare(_who);
}
return 0;
}
function _userShareByWeekNo(address _who, uint256 _weekCount) internal view returns(uint256) {
return userInfo[_who].shareByWeekNo[_weekCount];
}
function getUserStatus(address _who) public view returns(bool) {
return userInfo[_who].isActive;
}
function getUserStartedWeek(address _who) public view returns(uint256) {
return userInfo[_who].startedWeek;
}
function getUserEndedWeek(address _who) public view returns(uint256) {
return userInfo[_who].endedWeek;
}
function getUserLastDepositTime(address _who) public view returns(uint256) {
return userInfo[_who].depositTime;
}
function isUserPreviouslyStaked(address _who) public view returns(bool) {
return smartContractStakers[_who];
}
function getUserFeeRewardClaimStatus(address _who, uint256 _index) public view returns(bool) {
return feeRewardData[_index].isClaimed[_who];
}
/*
* ------------------Getter inteface for contract---------------------
*
*/
function getRewardsByWeekNo(uint256 _weekCount) public view returns(uint256[3] memory) {
return rewardByWeek[_weekCount];
}
function getFeeRewardsByIndex(uint256 _index) public view returns(uint256, uint256, uint256, uint256) {
return (feeRewardData[_index].value,
feeRewardData[_index].timeStamp,
feeRewardData[_index].totalStakersAtThatTime,
feeRewardData[_index].weekGiven);
}
function getRewardPercentages() public view returns(uint256[3] memory) {
return rewardPercentages;
}
function getStakeByWeekNo(uint256 _weekCount) public view returns(uint256) {
return stakePerWeek[_weekCount];
}
function getSharesByWeekNo(uint256 _weekCount) public view returns(uint256) {
return totalSharesByWeek[_weekCount];
}
} | initially it will be 27000 | uint256[] public stakingLimit;
| 2,067,753 | [
1,
2738,
6261,
518,
903,
506,
12732,
3784,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
8526,
1071,
384,
6159,
3039,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-03-07
*/
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256){
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b,"Calculation error");
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256){
// Solidity only automatically asserts when dividing by 0
require(b > 0,"Calculation error");
uint256 c = a / b;
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256){
require(b <= a,"Calculation error");
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256){
uint256 c = a + b;
require(c >= a,"Calculation error");
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256){
require(b != 0,"Calculation error");
return a % b;
}
}
/**
* @title IToken
* @dev Contract interface for token contract
*/
contract IToken {
function balanceOf(address) public pure returns (uint256);
function transfer(address, uint256) public pure returns (bool);
function transferFrom(address, address, uint256) public pure returns (bool);
function approve(address , uint256) public pure returns (bool);
}
/**
* @title CLIQWETHLPStaking
* @dev CLIQWETHLP Staking Contract for LP token staking
*/
contract CLIQWETHLPStaking {
using SafeMath for uint256;
address private _owner; // variable for Owner of the Contract.
uint256 private _withdrawTime; // variable to manage withdraw time for Token
uint256 constant public PERIOD_SILVER = 90; // variable constant for time period managemnt
uint256 constant public PERIOD_GOLD = 180; // variable constant for time period managemnt
uint256 constant public PERIOD_PLATINUM = 270; // variable constant for time period managemnt
uint256 constant public WITHDRAW_TIME_SILVER = 45 * 1 days; // variable constant to manage withdraw time lock up
uint256 constant public WITHDRAW_TIME_GOLD = 90 * 1 days; // variable constant to manage withdraw time lock up
uint256 constant public WITHDRAW_TIME_PLATINUM = 135 * 1 days; // variable constant to manage withdraw time lock up
uint256 public TOKEN_REWARD_PERCENT_SILVER = 21788328; // variable constant to manage token reward percentage for silver
uint256 public TOKEN_REWARD_PERCENT_GOLD = 67332005; // variable constant to manage token reward percentage for gold
uint256 public TOKEN_REWARD_PERCENT_PLATINUM = 178233538; // variable constant to manage token reward percentage for platinum
uint256 public TOKEN_PENALTY_PERCENT_SILVER = 10894164; // variable constant to manage token penalty percentage for silver
uint256 public TOKEN_PENALTY_PERCENT_GOLD = 23566201; // variable constant to manage token penalty percentage for gold
uint256 public TOKEN_PENALTY_PERCENT_PLATINUM = 44558384; // variable constant to manage token penalty percentage for platinum
// events to handle staking pause or unpause for token
event Paused();
event Unpaused();
/*
* ---------------------------------------------------------------------------------------------------------------------------
* Functions for owner.
* ---------------------------------------------------------------------------------------------------------------------------
*/
/**
* @dev get address of smart contract owner
* @return address of owner
*/
function getowner() public view returns (address) {
return _owner;
}
/**
* @dev modifier to check if the message sender is owner
*/
modifier onlyOwner() {
require(isOwner(),"You are not authenticate to make this transfer");
_;
}
/**
* @dev Internal function for modifier
*/
function isOwner() internal view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Transfer ownership of the smart contract. For owner only
* @return request status
*/
function transferOwnership(address newOwner) public onlyOwner returns (bool){
_owner = newOwner;
return true;
}
/*
* ---------------------------------------------------------------------------------------------------------------------------
* Functionality of Constructor and Interface
* ---------------------------------------------------------------------------------------------------------------------------
*/
// constructor to declare owner of the contract during time of deploy
constructor() public {
_owner = msg.sender;
}
// Interface declaration for contract
IToken itoken;
// function to set Contract Address for Token Transfer Functions
function setContractAddress(address tokenContractAddress) external onlyOwner returns(bool){
itoken = IToken(tokenContractAddress);
return true;
}
/*
* ----------------------------------------------------------------------------------------------------------------------------
* Owner functions of get value, set value and other Functionality
* ----------------------------------------------------------------------------------------------------------------------------
*/
// function to add token reward in contract
function addTokenReward(uint256 token) external onlyOwner returns(bool){
_ownerTokenAllowance = _ownerTokenAllowance.add(token);
itoken.transferFrom(msg.sender, address(this), token);
return true;
}
// function to withdraw added token reward in contract
function withdrawAddedTokenReward(uint256 token) external onlyOwner returns(bool){
require(token < _ownerTokenAllowance,"Value is not feasible, Please Try Again!!!");
_ownerTokenAllowance = _ownerTokenAllowance.sub(token);
itoken.transfer(msg.sender, token);
return true;
}
// function to get token reward in contract
function getTokenReward() public view returns(uint256){
return _ownerTokenAllowance;
}
// function to pause Token Staking
function pauseTokenStaking() public onlyOwner {
tokenPaused = true;
emit Paused();
}
// function to unpause Token Staking
function unpauseTokenStaking() public onlyOwner {
tokenPaused = false;
emit Unpaused();
}
// function to set values
function setManager(uint256 tokenStakingCount, uint256 tokenTotalDays, address tokenStakingAddress, uint256 tokenStakingStartTime,
uint256 tokenStakingEndTime, uint256 usertokens) external onlyOwner returns(bool){
_tokenStakingCount = tokenStakingCount;
_tokenTotalDays[_tokenStakingCount] = tokenTotalDays;
_tokenStakingAddress[_tokenStakingCount] = tokenStakingAddress;
_tokenStakingId[tokenStakingAddress].push(_tokenStakingCount);
_tokenStakingEndTime[_tokenStakingCount] = tokenStakingEndTime;
_tokenStakingStartTime[_tokenStakingCount] = tokenStakingStartTime;
_usersTokens[_tokenStakingCount] = usertokens;
_TokenTransactionstatus[_tokenStakingCount] = false;
totalStakedToken = totalStakedToken.add(usertokens);
totalTokenStakesInContract = totalTokenStakesInContract.add(usertokens);
return true;
}
// function to set reward percent
function setRewardPercent(uint256 silver, uint256 gold, uint256 platinum) external onlyOwner returns(bool){
require(silver != 0 && gold != 0 && platinum !=0,"Invalid Reward Value or Zero value, Please Try Again!!!");
TOKEN_REWARD_PERCENT_SILVER = silver;
TOKEN_REWARD_PERCENT_GOLD = gold;
TOKEN_REWARD_PERCENT_PLATINUM = platinum;
return true;
}
// function to set penalty percent
function setPenaltyPercent(uint256 silver, uint256 gold, uint256 platinum) external onlyOwner returns(bool){
require(silver != 0 && gold != 0 && platinum !=0,"Invalid Penalty Value or Zero value, Please Try Again!!!");
TOKEN_PENALTY_PERCENT_SILVER = silver;
TOKEN_PENALTY_PERCENT_GOLD = gold;
TOKEN_PENALTY_PERCENT_PLATINUM = platinum;
return true;
}
// function to withdraw token from the contract
function withdrawToken(uint256 amount) external onlyOwner returns(bool){
itoken.transfer(msg.sender,amount);
return true;
}
// function to withdraw ETH from the contract
function withdrawETH() external onlyOwner returns(bool){
msg.sender.transfer(address(this).balance);
return true;
}
/*
* ----------------------------------------------------------------------------------------------------------------------------
* Variable, Mapping for Token Staking Functionality
* ----------------------------------------------------------------------------------------------------------------------------
*/
// mapping for users with id => address Staking Address
mapping (uint256 => address) private _tokenStakingAddress;
// mapping for users with address => id staking id
mapping (address => uint256[]) private _tokenStakingId;
// mapping for users with id => Staking Time
mapping (uint256 => uint256) private _tokenStakingStartTime;
// mapping for users with id => End Time
mapping (uint256 => uint256) private _tokenStakingEndTime;
// mapping for users with id => Tokens
mapping (uint256 => uint256) private _usersTokens;
// mapping for users with id => Status
mapping (uint256 => bool) private _TokenTransactionstatus;
// mapping to keep track of final withdraw value of staked token
mapping(uint256=>uint256) private _finalTokenStakeWithdraw;
// mapping to keep track total number of staking days
mapping(uint256=>uint256) private _tokenTotalDays;
// variable to keep count of Token Staking
uint256 private _tokenStakingCount = 0;
// variable to keep track on reward added by owner
uint256 private _ownerTokenAllowance = 0;
// variable for token time management
uint256 private _tokentime;
// variable for token staking pause and unpause mechanism
bool public tokenPaused = false;
// variable for total Token staked by user
uint256 public totalStakedToken = 0;
// variable for total stake token in contract
uint256 public totalTokenStakesInContract = 0;
// modifier to check the user for staking || Re-enterance Guard
modifier tokenStakeCheck(uint256 tokens, uint256 timePeriod){
require(tokens > 0, "Invalid Token Amount, Please Try Again!!! ");
require(timePeriod == PERIOD_SILVER || timePeriod == PERIOD_GOLD || timePeriod == PERIOD_PLATINUM, "Enter the Valid Time Period and Try Again !!!");
_;
}
/*
* ------------------------------------------------------------------------------------------------------------------------------
* Functions for Token Staking Functionality
* ------------------------------------------------------------------------------------------------------------------------------
*/
// function to performs staking for user tokens for a specific period of time
function stakeToken(uint256 tokens, uint256 time) public tokenStakeCheck(tokens, time) returns(bool){
require(tokenPaused == false, "Staking is Paused, Please try after staking get unpaused!!!");
_tokentime = now + (time * 1 days);
_tokenStakingCount = _tokenStakingCount +1;
_tokenTotalDays[_tokenStakingCount] = time;
_tokenStakingAddress[_tokenStakingCount] = msg.sender;
_tokenStakingId[msg.sender].push(_tokenStakingCount);
_tokenStakingEndTime[_tokenStakingCount] = _tokentime;
_tokenStakingStartTime[_tokenStakingCount] = now;
_usersTokens[_tokenStakingCount] = tokens;
_TokenTransactionstatus[_tokenStakingCount] = false;
totalStakedToken = totalStakedToken.add(tokens);
totalTokenStakesInContract = totalTokenStakesInContract.add(tokens);
itoken.transferFrom(msg.sender, address(this), tokens);
return true;
}
// function to get staking count for token
function getTokenStakingCount() public view returns(uint256){
return _tokenStakingCount;
}
// function to get total Staked tokens
function getTotalStakedToken() public view returns(uint256){
return totalStakedToken;
}
// function to calculate reward for the message sender for token
function getTokenRewardDetailsByStakingId(uint256 id) public view returns(uint256){
if(_tokenTotalDays[id] == PERIOD_SILVER) {
return (_usersTokens[id]*TOKEN_REWARD_PERCENT_SILVER/100000000);
} else if(_tokenTotalDays[id] == PERIOD_GOLD) {
return (_usersTokens[id]*TOKEN_REWARD_PERCENT_GOLD/100000000);
} else if(_tokenTotalDays[id] == PERIOD_PLATINUM) {
return (_usersTokens[id]*TOKEN_REWARD_PERCENT_PLATINUM/100000000);
} else{
return 0;
}
}
// function to calculate penalty for the message sender for token
function getTokenPenaltyDetailByStakingId(uint256 id) public view returns(uint256){
if(_tokenStakingEndTime[id] > now){
if(_tokenTotalDays[id]==PERIOD_SILVER){
return (_usersTokens[id]*TOKEN_PENALTY_PERCENT_SILVER/100000000);
} else if(_tokenTotalDays[id] == PERIOD_GOLD) {
return (_usersTokens[id]*TOKEN_PENALTY_PERCENT_GOLD/100000000);
} else if(_tokenTotalDays[id] == PERIOD_PLATINUM) {
return (_usersTokens[id]*TOKEN_PENALTY_PERCENT_PLATINUM/100000000);
} else {
return 0;
}
} else{
return 0;
}
}
// function for withdrawing staked tokens
function withdrawStakedTokens(uint256 stakingId) public returns(bool) {
require(_tokenStakingAddress[stakingId] == msg.sender,"No staked token found on this address and ID");
require(_TokenTransactionstatus[stakingId] != true,"Either tokens are already withdrawn or blocked by admin");
if(_tokenTotalDays[stakingId] == PERIOD_SILVER){
require(now >= _tokenStakingStartTime[stakingId] + WITHDRAW_TIME_SILVER, "Unable to Withdraw Staked token before 45 days of staking start time, Please Try Again Later!!!");
_TokenTransactionstatus[stakingId] = true;
if(now >= _tokenStakingEndTime[stakingId]){
_finalTokenStakeWithdraw[stakingId] = _usersTokens[stakingId].add(getTokenRewardDetailsByStakingId(stakingId));
itoken.transfer(msg.sender,_finalTokenStakeWithdraw[stakingId]);
totalTokenStakesInContract = totalTokenStakesInContract.sub(_usersTokens[stakingId]);
} else {
_finalTokenStakeWithdraw[stakingId] = _usersTokens[stakingId].add(getTokenPenaltyDetailByStakingId(stakingId));
itoken.transfer(msg.sender,_finalTokenStakeWithdraw[stakingId]);
totalTokenStakesInContract = totalTokenStakesInContract.sub(_usersTokens[stakingId]);
}
} else if(_tokenTotalDays[stakingId] == PERIOD_GOLD){
require(now >= _tokenStakingStartTime[stakingId] + WITHDRAW_TIME_GOLD, "Unable to Withdraw Staked token before 90 days of staking start time, Please Try Again Later!!!");
_TokenTransactionstatus[stakingId] = true;
if(now >= _tokenStakingEndTime[stakingId]){
_finalTokenStakeWithdraw[stakingId] = _usersTokens[stakingId].add(getTokenRewardDetailsByStakingId(stakingId));
itoken.transfer(msg.sender,_finalTokenStakeWithdraw[stakingId]);
totalTokenStakesInContract = totalTokenStakesInContract.sub(_usersTokens[stakingId]);
} else {
_finalTokenStakeWithdraw[stakingId] = _usersTokens[stakingId].add(getTokenPenaltyDetailByStakingId(stakingId));
itoken.transfer(msg.sender,_finalTokenStakeWithdraw[stakingId]);
totalTokenStakesInContract = totalTokenStakesInContract.sub(_usersTokens[stakingId]);
}
} else if(_tokenTotalDays[stakingId] == PERIOD_PLATINUM){
require(now >= _tokenStakingStartTime[stakingId] + WITHDRAW_TIME_PLATINUM, "Unable to Withdraw Staked token before 135 days of staking start time, Please Try Again Later!!!");
_TokenTransactionstatus[stakingId] = true;
if(now >= _tokenStakingEndTime[stakingId]){
_finalTokenStakeWithdraw[stakingId] = _usersTokens[stakingId].add(getTokenRewardDetailsByStakingId(stakingId));
itoken.transfer(msg.sender,_finalTokenStakeWithdraw[stakingId]);
totalTokenStakesInContract = totalTokenStakesInContract.sub(_usersTokens[stakingId]);
} else {
_finalTokenStakeWithdraw[stakingId] = _usersTokens[stakingId].add(getTokenPenaltyDetailByStakingId(stakingId));
itoken.transfer(msg.sender,_finalTokenStakeWithdraw[stakingId]);
totalTokenStakesInContract = totalTokenStakesInContract.sub(_usersTokens[stakingId]);
}
} else {
return false;
}
return true;
}
// function to get Final Withdraw Staked value for token
function getFinalTokenStakeWithdraw(uint256 id) public view returns(uint256){
return _finalTokenStakeWithdraw[id];
}
// function to get total token stake in contract
function getTotalTokenStakesInContract() public view returns(uint256){
return totalTokenStakesInContract;
}
/*
* -------------------------------------------------------------------------------------------------------------------------------
* Get Functions for Stake Token Functionality
* -------------------------------------------------------------------------------------------------------------------------------
*/
// function to get Token Staking address by id
function getTokenStakingAddressById(uint256 id) external view returns (address){
require(id <= _tokenStakingCount,"Unable to reterive data on specified id, Please try again!!");
return _tokenStakingAddress[id];
}
// function to get Token staking id by address
function getTokenStakingIdByAddress(address add) external view returns(uint256[] memory){
require(add != address(0),"Invalid Address, Pleae Try Again!!!");
return _tokenStakingId[add];
}
// function to get Token Staking Starting time by id
function getTokenStakingStartTimeById(uint256 id) external view returns(uint256){
require(id <= _tokenStakingCount,"Unable to reterive data on specified id, Please try again!!");
return _tokenStakingStartTime[id];
}
// function to get Token Staking Ending time by id
function getTokenStakingEndTimeById(uint256 id) external view returns(uint256){
require(id <= _tokenStakingCount,"Unable to reterive data on specified id, Please try again!!");
return _tokenStakingEndTime[id];
}
// function to get Token Staking Total Days by Id
function getTokenStakingTotalDaysById(uint256 id) external view returns(uint256){
require(id <= _tokenStakingCount,"Unable to reterive data on specified id, Please try again!!");
return _tokenTotalDays[id];
}
// function to get Staking tokens by id
function getStakingTokenById(uint256 id) external view returns(uint256){
require(id <= _tokenStakingCount,"Unable to reterive data on specified id, Please try again!!");
return _usersTokens[id];
}
// function to get Token lockstatus by id
function getTokenLockStatus(uint256 id) external view returns(bool){
require(id <= _tokenStakingCount,"Unable to reterive data on specified id, Please try again!!");
return _TokenTransactionstatus[id];
}
} | function to set reward percent | function setRewardPercent(uint256 silver, uint256 gold, uint256 platinum) external onlyOwner returns(bool){
require(silver != 0 && gold != 0 && platinum !=0,"Invalid Reward Value or Zero value, Please Try Again!!!");
TOKEN_REWARD_PERCENT_SILVER = silver;
TOKEN_REWARD_PERCENT_GOLD = gold;
TOKEN_REWARD_PERCENT_PLATINUM = platinum;
return true;
}
| 2,348,613 | [
1,
915,
358,
444,
19890,
5551,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
444,
17631,
1060,
8410,
12,
11890,
5034,
17714,
502,
16,
2254,
5034,
20465,
16,
2254,
5034,
29838,
267,
379,
13,
3903,
1338,
5541,
1135,
12,
6430,
15329,
203,
565,
2583,
12,
25119,
502,
480,
374,
597,
20465,
480,
374,
597,
29838,
267,
379,
480,
20,
10837,
1941,
534,
359,
1060,
1445,
578,
12744,
460,
16,
7801,
6161,
5495,
530,
8548,
4442,
1769,
203,
377,
14275,
67,
862,
21343,
67,
3194,
19666,
67,
2320,
48,
2204,
273,
17714,
502,
31,
203,
377,
14275,
67,
862,
21343,
67,
3194,
19666,
67,
43,
11846,
273,
20465,
31,
203,
377,
14275,
67,
862,
21343,
67,
3194,
19666,
67,
6253,
789,
706,
2799,
273,
29838,
267,
379,
31,
203,
377,
327,
638,
31,
203,
225,
289,
203,
21281,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/interfaces/IERC165.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
import "@openzeppelin/contracts/interfaces/IERC2981.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./utils/HasNoEther.sol";
contract JamMarketplace is HasNoEther, Pausable, ReentrancyGuard {
using SafeMath for uint256;
// Represents an auction on an NFT
struct Auction {
address seller;
uint128 price;
address erc20Address; // erc20Address, address(0) if place a price with (wei)
address nftAddress;
uint256 tokenId;
uint64 startedAt;
}
uint256 withdrawDuration = 14 days;
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public ownerCut;
// The total amount of royalty cut which cannot be reclaimed by the owner of the contract
mapping(address => uint256) private _totalRoyaltyCut;
// Map from an NFT to its corresponding auction.
mapping(address => mapping(uint256 => Auction)) public auctions;
// mapping royaltyCut amount for each (address, erc20Address) pair,
// erc20Address = address(0) mean it value is wei
mapping(address => mapping(address => uint256)) private royaltyCuts;
mapping(address => mapping(address => uint256)) private lastWithdraws;
event AuctionCreated(
address indexed nftAddress,
uint256 indexed tokenId,
uint256 price,
address seller,
address erc20Address
);
event AuctionSuccessful(
address indexed nftAddress,
uint256 indexed tokenId,
uint256 price,
address winner
);
event AuctionCancelled(address indexed nftAddress, uint256 indexed tokenId);
// Modifiers to check that inputs can be safely stored with a certain
// number of bits. We use constants and multiple modifiers to save gas.
modifier canBeStoredWith64Bits(uint256 _value) {
require(
_value <= type(uint64).max,
"JamMarketplace: cannot be stored with 64 bits"
);
_;
}
modifier canBeStoredWith128Bits(uint256 _value) {
require(
_value < type(uint128).max,
"JamMarketplace: cannot be stored with 128 bits"
);
_;
}
constructor(uint256 _ownerCut) {
require(
_ownerCut <= 10000,
"JamMarketplace: owner cut cannot exceed 100%"
);
ownerCut = _ownerCut;
}
function updateOwnerCut(uint256 _ownerCut) public onlyOwner {
require(
_ownerCut <= 10000,
"JamMarketplace: owner cut cannot exceed 100%"
);
ownerCut = _ownerCut;
}
function _computeCut(uint256 _price) internal view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our entry functions carefully cap the maximum values for
// currency (at 128-bits), and ownerCut <= 10000 (see the require()
// statement in the ClockAuction constructor). The result of this
// function is always guaranteed to be <= _price.
return (_price * ownerCut) / 10000;
}
function _isOnAuction(Auction storage _auction)
internal
view
returns (bool)
{
return (_auction.startedAt > 0);
}
function _getNftContract(address _nftAddress)
internal
pure
returns (IERC721)
{
IERC721 candidateContract = IERC721(_nftAddress);
return candidateContract;
}
function _supportIERC2981(address _nftAddress)
internal
view
returns (bool)
{
bool success;
success = ERC165Checker.supportsERC165(_nftAddress);
if (success) {
success = IERC165(_nftAddress).supportsInterface(
type(IERC2981).interfaceId
);
}
return success;
}
function _getERC2981(address _nftAddress) internal pure returns (IERC2981) {
IERC2981 candidateContract = IERC2981(_nftAddress);
return candidateContract;
}
function _getERC20Contract(address _erc20Address)
internal
pure
returns (IERC20)
{
IERC20 candidateContract = IERC20(_erc20Address);
return candidateContract;
}
function _owns(
address _nftAddress,
address _claimant,
uint256 _tokenId
) internal view returns (bool) {
IERC721 _nftContract = _getNftContract(_nftAddress);
return (_nftContract.ownerOf(_tokenId) == _claimant);
}
function _transfer(
address _nftAddress,
address _receiver,
uint256 _tokenId
) internal {
IERC721 _nftContract = _getNftContract(_nftAddress);
// It will throw if transfer fails
_nftContract.transferFrom(address(this), _receiver, _tokenId);
}
function _addAuction(
address _nftAddress,
uint256 _tokenId,
Auction memory _auction,
address _seller
) internal {
auctions[_nftAddress][_tokenId] = _auction;
emit AuctionCreated(
_nftAddress,
_tokenId,
uint256(_auction.price),
_seller,
address(_auction.erc20Address)
);
}
function _escrow(
address _nftAddress,
address _owner,
uint256 _tokenId
) internal {
IERC721 _nftContract = _getNftContract(_nftAddress);
// It will throw if transfer fails
_nftContract.transferFrom(_owner, address(this), _tokenId);
}
/// @dev Removes an auction from the list of open auctions.
/// @param _tokenId - ID of NFT on auction.
function _removeAuction(address _nftAddress, uint256 _tokenId) internal {
delete auctions[_nftAddress][_tokenId];
}
/// @dev Cancels an auction unconditionally.
function _cancelAuction(
address _nftAddress,
uint256 _tokenId,
address _seller
) internal {
_removeAuction(_nftAddress, _tokenId);
_transfer(_nftAddress, _seller, _tokenId);
emit AuctionCancelled(_nftAddress, _tokenId);
}
function getAuction(address _nftAddress, uint256 _tokenId)
external
view
returns (
address seller,
uint256 price,
address erc20Address,
uint256 startedAt
)
{
Auction storage _auction = auctions[_nftAddress][_tokenId];
require(_isOnAuction(_auction), "JamMarketplace: not on auction");
return (
_auction.seller,
_auction.price,
_auction.erc20Address,
_auction.startedAt
);
}
function getWithdrawInfo(address[] memory _contractAddress)
external
view
returns (
address[] memory contractAddress,
uint256[] memory balances,
uint256[] memory lastWithdraw
)
{
uint256[] memory _balances = new uint256[](_contractAddress.length);
uint256[] memory _lastWithdraw = new uint256[](_contractAddress.length);
for (uint256 i = 0; i < _contractAddress.length; i += 1) {
address ad = _contractAddress[i];
uint256 balance = royaltyCuts[msg.sender][ad];
_balances[i] = balance;
uint256 lw = lastWithdraws[msg.sender][ad];
_lastWithdraw[i] = lw;
}
return (_contractAddress, balances, lastWithdraw);
}
/// @dev Create an auction.
/// @param _nftAddress - Address of the NFT.
/// @param _tokenId - ID of the NFT.
/// @param _price - Price of erc20 address.
/// @param _erc20Address - Address of price need to be list on.
function createAuction(
address _nftAddress,
uint256 _tokenId,
uint256 _price,
address _erc20Address
) external whenNotPaused canBeStoredWith128Bits(_price) {
address _seller = msg.sender;
require(
_owns(_nftAddress, _seller, _tokenId),
"JamMarketplace: only owner can create auction"
);
_escrow(_nftAddress, _seller, _tokenId);
Auction memory _auction = Auction(
_seller,
uint128(_price),
_erc20Address,
_nftAddress,
_tokenId,
uint64(block.timestamp)
);
_addAuction(_nftAddress, _tokenId, _auction, _seller);
}
/// @dev Cancels an auction.
/// @param _nftAddress - Address of the NFT.
/// @param _tokenId - ID of the NFT on auction to cancel.
function cancelAuction(address _nftAddress, uint256 _tokenId) external {
Auction storage _auction = auctions[_nftAddress][_tokenId];
require(_isOnAuction(_auction), "JamMarketplace: not on auction");
require(
msg.sender == _auction.seller,
"JamMarketplace: only seller can cancel auction"
);
_cancelAuction(_nftAddress, _tokenId, _auction.seller);
}
/// @dev Cancels an auction when the contract is paused.
/// Only the owner may do this, and NFTs are returned to
/// the seller. This should only be used in emergencies.
/// @param _nftAddress - Address of the NFT.
/// @param _tokenId - ID of the NFT on auction to cancel.
function cancelAuctionWhenPaused(address _nftAddress, uint256 _tokenId)
external
whenPaused
onlyOwner
{
Auction storage _auction = auctions[_nftAddress][_tokenId];
require(_isOnAuction(_auction), "JamMarketplace: not on auction");
_cancelAuction(_nftAddress, _tokenId, _auction.seller);
}
function buy(address _nftAddress, uint256 _tokenId)
external
payable
whenNotPaused
{
Auction memory auction = auctions[_nftAddress][_tokenId];
require(
auction.erc20Address == address(0),
"JamMarketplace: cannot buy this item with native token"
);
// _bid will throw if the bid or funds transfer fails
_buy(_nftAddress, _tokenId, msg.value);
_transfer(_nftAddress, msg.sender, _tokenId);
}
function buyByERC20(
address _nftAddress,
uint256 _tokenId,
uint256 _maxPrice
) external whenNotPaused nonReentrant {
Auction storage _auction = auctions[_nftAddress][_tokenId];
require(
_auction.erc20Address != address(0),
"JamMarketplace: can only be paid with native token"
);
require(_isOnAuction(_auction), "JamMarketplace: not on auction");
uint256 _price = _auction.price;
require(_price <= _maxPrice, "JamMarketplace: item price is too high");
uint256 tokenId = _tokenId;
address _erc20Address = _auction.erc20Address;
IERC20 erc20Contract = _getERC20Contract(_erc20Address);
uint256 _allowance = erc20Contract.allowance(msg.sender, address(this));
require(_allowance >= _price, "JamMarketplace: not enough allowance");
address _seller = _auction.seller;
uint256 _auctioneerCut = _computeCut(_price);
uint256 _sellerProceeds = _price - _auctioneerCut;
bool success = erc20Contract.transferFrom(
msg.sender,
address(this),
_price
);
require(success, "JamMarketplace: not enough balance");
erc20Contract.transfer(_seller, _sellerProceeds);
if (_supportIERC2981(_nftAddress)) {
IERC2981 royaltyContract = _getERC2981(_nftAddress);
(address firstOwner, uint256 amount) = royaltyContract.royaltyInfo(
tokenId,
_auctioneerCut
);
require(
amount < _auctioneerCut,
"JamMarketplace: royalty amount must be less than auctioneer cut"
);
_totalRoyaltyCut[_erc20Address] = _totalRoyaltyCut[_erc20Address]
.add(amount);
royaltyCuts[firstOwner][_erc20Address] = royaltyCuts[firstOwner][
_erc20Address
].add(amount);
}
_transfer(_nftAddress, msg.sender, _tokenId);
_removeAuction(_nftAddress, _tokenId);
}
/// @dev Computes the price and transfers winnings.
/// Does NOT transfer ownership of token.
function _buy(
address _nftAddress,
uint256 _tokenId,
uint256 _bidAmount
) internal returns (uint256) {
// Get a reference to the auction struct
Auction storage _auction = auctions[_nftAddress][_tokenId];
require(_isOnAuction(_auction), "JamMarketplace: not on auction");
uint256 _price = _auction.price;
require(
_bidAmount >= _price,
"JamMarketplace: bid amount cannot be less than price"
);
address _seller = _auction.seller;
_removeAuction(_nftAddress, _tokenId);
if (_price > 0) {
// Calculate the auctioneer's cut.
// (NOTE: _computeCut() is guaranteed to return a
// value <= price, so this subtraction can't go negative.)
uint256 _auctioneerCut = _computeCut(_price);
uint256 _sellerProceeds = _price - _auctioneerCut;
payable(_seller).transfer(_sellerProceeds);
if (_supportIERC2981(_nftAddress)) {
IERC2981 royaltyContract = _getERC2981(_nftAddress);
(address firstOwner, uint256 amount) = royaltyContract
.royaltyInfo(_tokenId, _auctioneerCut);
require(
amount < _auctioneerCut,
"JamMarketplace: royalty amount must be less than auctioneer cut"
);
_totalRoyaltyCut[address(0)] = _totalRoyaltyCut[address(0)].add(
amount
);
royaltyCuts[firstOwner][address(0)] = royaltyCuts[firstOwner][
address(0)
].add(amount);
}
}
if (_bidAmount > _price) {
// Calculate any excess funds included with the bid. If the excess
// is anything worth worrying about, transfer it back to bidder.
// NOTE: We checked above that the bid amount is greater than or
// equal to the price so this cannot underflow.
uint256 _bidExcess = _bidAmount - _price;
// Return the funds. Similar to the previous transfer, this is
// not susceptible to a re-entry attack because the auction is
// removed before any transfers occur.
payable(msg.sender).transfer(_bidExcess);
}
// Tell the world!
emit AuctionSuccessful(_nftAddress, _tokenId, _price, msg.sender);
return _price;
}
function withdraw(address _erc20Address) public {
uint256 lastWithdraw = lastWithdraws[msg.sender][_erc20Address];
require(
lastWithdraw + withdrawDuration <= block.timestamp,
"JamMarketplace: only withdraw after 14 days before previous withdraw"
);
uint256 royaltyCut = royaltyCuts[msg.sender][_erc20Address];
require(royaltyCut > 0, "JamMarketplace: no royalty cut to withdraw");
royaltyCuts[msg.sender][_erc20Address] = 0;
_totalRoyaltyCut[_erc20Address] = _totalRoyaltyCut[_erc20Address].sub(
royaltyCut
);
lastWithdraws[msg.sender][_erc20Address] = block.timestamp;
if (_erc20Address == address(0)) {
payable(msg.sender).transfer(royaltyCut);
} else {
IERC20 erc20Contract = _getERC20Contract(_erc20Address);
bool success = erc20Contract.transfer(msg.sender, royaltyCut);
require(success, "JamMarketplace: transfer failed");
}
}
// function reclaimEther() external override onlyOwner {
// (bool success, ) = payable(owner()).call{
// value: address(this).balance.sub(_totalRoyaltyCut[address(0)])
// }("");
// require(success, "JamMarketplace: reclaim Ether failed");
// }
function reclaimERC20(address _erc20Address) external onlyOwner {
IERC20 erc20Contract = _getERC20Contract(_erc20Address);
erc20Contract.transfer(
owner(),
erc20Contract.balanceOf(address(this)).sub(
_totalRoyaltyCut[_erc20Address]
)
);
}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
}
| Represents an auction on an NFT | contract JamMarketplace is HasNoEther, Pausable, ReentrancyGuard {
using SafeMath for uint256;
struct Auction {
address seller;
uint128 price;
address nftAddress;
uint256 tokenId;
uint64 startedAt;
}
uint256 withdrawDuration = 14 days;
mapping(address => mapping(address => uint256)) private lastWithdraws;
event AuctionCreated(
address indexed nftAddress,
uint256 indexed tokenId,
uint256 price,
address seller,
address erc20Address
);
event AuctionSuccessful(
address indexed nftAddress,
uint256 indexed tokenId,
uint256 price,
address winner
);
event AuctionCancelled(address indexed nftAddress, uint256 indexed tokenId);
uint256 public ownerCut;
mapping(address => uint256) private _totalRoyaltyCut;
mapping(address => mapping(uint256 => Auction)) public auctions;
mapping(address => mapping(address => uint256)) private royaltyCuts;
modifier canBeStoredWith64Bits(uint256 _value) {
require(
_value <= type(uint64).max,
"JamMarketplace: cannot be stored with 64 bits"
);
_;
}
modifier canBeStoredWith128Bits(uint256 _value) {
require(
_value < type(uint128).max,
"JamMarketplace: cannot be stored with 128 bits"
);
_;
}
constructor(uint256 _ownerCut) {
require(
_ownerCut <= 10000,
"JamMarketplace: owner cut cannot exceed 100%"
);
ownerCut = _ownerCut;
}
function updateOwnerCut(uint256 _ownerCut) public onlyOwner {
require(
_ownerCut <= 10000,
"JamMarketplace: owner cut cannot exceed 100%"
);
ownerCut = _ownerCut;
}
function _computeCut(uint256 _price) internal view returns (uint256) {
return (_price * ownerCut) / 10000;
}
function _isOnAuction(Auction storage _auction)
internal
view
returns (bool)
{
return (_auction.startedAt > 0);
}
function _getNftContract(address _nftAddress)
internal
pure
returns (IERC721)
{
IERC721 candidateContract = IERC721(_nftAddress);
return candidateContract;
}
function _supportIERC2981(address _nftAddress)
internal
view
returns (bool)
{
bool success;
success = ERC165Checker.supportsERC165(_nftAddress);
if (success) {
success = IERC165(_nftAddress).supportsInterface(
type(IERC2981).interfaceId
);
}
return success;
}
function _supportIERC2981(address _nftAddress)
internal
view
returns (bool)
{
bool success;
success = ERC165Checker.supportsERC165(_nftAddress);
if (success) {
success = IERC165(_nftAddress).supportsInterface(
type(IERC2981).interfaceId
);
}
return success;
}
function _getERC2981(address _nftAddress) internal pure returns (IERC2981) {
IERC2981 candidateContract = IERC2981(_nftAddress);
return candidateContract;
}
function _getERC20Contract(address _erc20Address)
internal
pure
returns (IERC20)
{
IERC20 candidateContract = IERC20(_erc20Address);
return candidateContract;
}
function _owns(
address _nftAddress,
address _claimant,
uint256 _tokenId
) internal view returns (bool) {
IERC721 _nftContract = _getNftContract(_nftAddress);
return (_nftContract.ownerOf(_tokenId) == _claimant);
}
function _transfer(
address _nftAddress,
address _receiver,
uint256 _tokenId
) internal {
IERC721 _nftContract = _getNftContract(_nftAddress);
_nftContract.transferFrom(address(this), _receiver, _tokenId);
}
function _addAuction(
address _nftAddress,
uint256 _tokenId,
Auction memory _auction,
address _seller
) internal {
auctions[_nftAddress][_tokenId] = _auction;
emit AuctionCreated(
_nftAddress,
_tokenId,
uint256(_auction.price),
_seller,
address(_auction.erc20Address)
);
}
function _escrow(
address _nftAddress,
address _owner,
uint256 _tokenId
) internal {
IERC721 _nftContract = _getNftContract(_nftAddress);
_nftContract.transferFrom(_owner, address(this), _tokenId);
}
function _removeAuction(address _nftAddress, uint256 _tokenId) internal {
delete auctions[_nftAddress][_tokenId];
}
function _cancelAuction(
address _nftAddress,
uint256 _tokenId,
address _seller
) internal {
_removeAuction(_nftAddress, _tokenId);
_transfer(_nftAddress, _seller, _tokenId);
emit AuctionCancelled(_nftAddress, _tokenId);
}
function getAuction(address _nftAddress, uint256 _tokenId)
external
view
returns (
address seller,
uint256 price,
address erc20Address,
uint256 startedAt
)
{
Auction storage _auction = auctions[_nftAddress][_tokenId];
require(_isOnAuction(_auction), "JamMarketplace: not on auction");
return (
_auction.seller,
_auction.price,
_auction.erc20Address,
_auction.startedAt
);
}
function getWithdrawInfo(address[] memory _contractAddress)
external
view
returns (
address[] memory contractAddress,
uint256[] memory balances,
uint256[] memory lastWithdraw
)
{
uint256[] memory _balances = new uint256[](_contractAddress.length);
uint256[] memory _lastWithdraw = new uint256[](_contractAddress.length);
for (uint256 i = 0; i < _contractAddress.length; i += 1) {
address ad = _contractAddress[i];
uint256 balance = royaltyCuts[msg.sender][ad];
_balances[i] = balance;
uint256 lw = lastWithdraws[msg.sender][ad];
_lastWithdraw[i] = lw;
}
return (_contractAddress, balances, lastWithdraw);
}
function getWithdrawInfo(address[] memory _contractAddress)
external
view
returns (
address[] memory contractAddress,
uint256[] memory balances,
uint256[] memory lastWithdraw
)
{
uint256[] memory _balances = new uint256[](_contractAddress.length);
uint256[] memory _lastWithdraw = new uint256[](_contractAddress.length);
for (uint256 i = 0; i < _contractAddress.length; i += 1) {
address ad = _contractAddress[i];
uint256 balance = royaltyCuts[msg.sender][ad];
_balances[i] = balance;
uint256 lw = lastWithdraws[msg.sender][ad];
_lastWithdraw[i] = lw;
}
return (_contractAddress, balances, lastWithdraw);
}
function createAuction(
address _nftAddress,
uint256 _tokenId,
uint256 _price,
address _erc20Address
) external whenNotPaused canBeStoredWith128Bits(_price) {
address _seller = msg.sender;
require(
_owns(_nftAddress, _seller, _tokenId),
"JamMarketplace: only owner can create auction"
);
_escrow(_nftAddress, _seller, _tokenId);
Auction memory _auction = Auction(
_seller,
uint128(_price),
_erc20Address,
_nftAddress,
_tokenId,
uint64(block.timestamp)
);
_addAuction(_nftAddress, _tokenId, _auction, _seller);
}
function cancelAuction(address _nftAddress, uint256 _tokenId) external {
Auction storage _auction = auctions[_nftAddress][_tokenId];
require(_isOnAuction(_auction), "JamMarketplace: not on auction");
require(
msg.sender == _auction.seller,
"JamMarketplace: only seller can cancel auction"
);
_cancelAuction(_nftAddress, _tokenId, _auction.seller);
}
function cancelAuctionWhenPaused(address _nftAddress, uint256 _tokenId)
external
whenPaused
onlyOwner
{
Auction storage _auction = auctions[_nftAddress][_tokenId];
require(_isOnAuction(_auction), "JamMarketplace: not on auction");
_cancelAuction(_nftAddress, _tokenId, _auction.seller);
}
function buy(address _nftAddress, uint256 _tokenId)
external
payable
whenNotPaused
{
Auction memory auction = auctions[_nftAddress][_tokenId];
require(
auction.erc20Address == address(0),
"JamMarketplace: cannot buy this item with native token"
);
_buy(_nftAddress, _tokenId, msg.value);
_transfer(_nftAddress, msg.sender, _tokenId);
}
function buyByERC20(
address _nftAddress,
uint256 _tokenId,
uint256 _maxPrice
) external whenNotPaused nonReentrant {
Auction storage _auction = auctions[_nftAddress][_tokenId];
require(
_auction.erc20Address != address(0),
"JamMarketplace: can only be paid with native token"
);
require(_isOnAuction(_auction), "JamMarketplace: not on auction");
uint256 _price = _auction.price;
require(_price <= _maxPrice, "JamMarketplace: item price is too high");
uint256 tokenId = _tokenId;
address _erc20Address = _auction.erc20Address;
IERC20 erc20Contract = _getERC20Contract(_erc20Address);
uint256 _allowance = erc20Contract.allowance(msg.sender, address(this));
require(_allowance >= _price, "JamMarketplace: not enough allowance");
address _seller = _auction.seller;
uint256 _auctioneerCut = _computeCut(_price);
uint256 _sellerProceeds = _price - _auctioneerCut;
bool success = erc20Contract.transferFrom(
msg.sender,
address(this),
_price
);
require(success, "JamMarketplace: not enough balance");
erc20Contract.transfer(_seller, _sellerProceeds);
if (_supportIERC2981(_nftAddress)) {
IERC2981 royaltyContract = _getERC2981(_nftAddress);
(address firstOwner, uint256 amount) = royaltyContract.royaltyInfo(
tokenId,
_auctioneerCut
);
require(
amount < _auctioneerCut,
"JamMarketplace: royalty amount must be less than auctioneer cut"
);
_totalRoyaltyCut[_erc20Address] = _totalRoyaltyCut[_erc20Address]
.add(amount);
royaltyCuts[firstOwner][_erc20Address] = royaltyCuts[firstOwner][
_erc20Address
].add(amount);
}
_transfer(_nftAddress, msg.sender, _tokenId);
_removeAuction(_nftAddress, _tokenId);
}
function buyByERC20(
address _nftAddress,
uint256 _tokenId,
uint256 _maxPrice
) external whenNotPaused nonReentrant {
Auction storage _auction = auctions[_nftAddress][_tokenId];
require(
_auction.erc20Address != address(0),
"JamMarketplace: can only be paid with native token"
);
require(_isOnAuction(_auction), "JamMarketplace: not on auction");
uint256 _price = _auction.price;
require(_price <= _maxPrice, "JamMarketplace: item price is too high");
uint256 tokenId = _tokenId;
address _erc20Address = _auction.erc20Address;
IERC20 erc20Contract = _getERC20Contract(_erc20Address);
uint256 _allowance = erc20Contract.allowance(msg.sender, address(this));
require(_allowance >= _price, "JamMarketplace: not enough allowance");
address _seller = _auction.seller;
uint256 _auctioneerCut = _computeCut(_price);
uint256 _sellerProceeds = _price - _auctioneerCut;
bool success = erc20Contract.transferFrom(
msg.sender,
address(this),
_price
);
require(success, "JamMarketplace: not enough balance");
erc20Contract.transfer(_seller, _sellerProceeds);
if (_supportIERC2981(_nftAddress)) {
IERC2981 royaltyContract = _getERC2981(_nftAddress);
(address firstOwner, uint256 amount) = royaltyContract.royaltyInfo(
tokenId,
_auctioneerCut
);
require(
amount < _auctioneerCut,
"JamMarketplace: royalty amount must be less than auctioneer cut"
);
_totalRoyaltyCut[_erc20Address] = _totalRoyaltyCut[_erc20Address]
.add(amount);
royaltyCuts[firstOwner][_erc20Address] = royaltyCuts[firstOwner][
_erc20Address
].add(amount);
}
_transfer(_nftAddress, msg.sender, _tokenId);
_removeAuction(_nftAddress, _tokenId);
}
function _buy(
address _nftAddress,
uint256 _tokenId,
uint256 _bidAmount
) internal returns (uint256) {
Auction storage _auction = auctions[_nftAddress][_tokenId];
require(_isOnAuction(_auction), "JamMarketplace: not on auction");
uint256 _price = _auction.price;
require(
_bidAmount >= _price,
"JamMarketplace: bid amount cannot be less than price"
);
address _seller = _auction.seller;
_removeAuction(_nftAddress, _tokenId);
if (_price > 0) {
uint256 _auctioneerCut = _computeCut(_price);
uint256 _sellerProceeds = _price - _auctioneerCut;
payable(_seller).transfer(_sellerProceeds);
if (_supportIERC2981(_nftAddress)) {
IERC2981 royaltyContract = _getERC2981(_nftAddress);
(address firstOwner, uint256 amount) = royaltyContract
.royaltyInfo(_tokenId, _auctioneerCut);
require(
amount < _auctioneerCut,
"JamMarketplace: royalty amount must be less than auctioneer cut"
);
_totalRoyaltyCut[address(0)] = _totalRoyaltyCut[address(0)].add(
amount
);
royaltyCuts[firstOwner][address(0)] = royaltyCuts[firstOwner][
address(0)
].add(amount);
}
}
if (_bidAmount > _price) {
uint256 _bidExcess = _bidAmount - _price;
payable(msg.sender).transfer(_bidExcess);
}
return _price;
}
function _buy(
address _nftAddress,
uint256 _tokenId,
uint256 _bidAmount
) internal returns (uint256) {
Auction storage _auction = auctions[_nftAddress][_tokenId];
require(_isOnAuction(_auction), "JamMarketplace: not on auction");
uint256 _price = _auction.price;
require(
_bidAmount >= _price,
"JamMarketplace: bid amount cannot be less than price"
);
address _seller = _auction.seller;
_removeAuction(_nftAddress, _tokenId);
if (_price > 0) {
uint256 _auctioneerCut = _computeCut(_price);
uint256 _sellerProceeds = _price - _auctioneerCut;
payable(_seller).transfer(_sellerProceeds);
if (_supportIERC2981(_nftAddress)) {
IERC2981 royaltyContract = _getERC2981(_nftAddress);
(address firstOwner, uint256 amount) = royaltyContract
.royaltyInfo(_tokenId, _auctioneerCut);
require(
amount < _auctioneerCut,
"JamMarketplace: royalty amount must be less than auctioneer cut"
);
_totalRoyaltyCut[address(0)] = _totalRoyaltyCut[address(0)].add(
amount
);
royaltyCuts[firstOwner][address(0)] = royaltyCuts[firstOwner][
address(0)
].add(amount);
}
}
if (_bidAmount > _price) {
uint256 _bidExcess = _bidAmount - _price;
payable(msg.sender).transfer(_bidExcess);
}
return _price;
}
function _buy(
address _nftAddress,
uint256 _tokenId,
uint256 _bidAmount
) internal returns (uint256) {
Auction storage _auction = auctions[_nftAddress][_tokenId];
require(_isOnAuction(_auction), "JamMarketplace: not on auction");
uint256 _price = _auction.price;
require(
_bidAmount >= _price,
"JamMarketplace: bid amount cannot be less than price"
);
address _seller = _auction.seller;
_removeAuction(_nftAddress, _tokenId);
if (_price > 0) {
uint256 _auctioneerCut = _computeCut(_price);
uint256 _sellerProceeds = _price - _auctioneerCut;
payable(_seller).transfer(_sellerProceeds);
if (_supportIERC2981(_nftAddress)) {
IERC2981 royaltyContract = _getERC2981(_nftAddress);
(address firstOwner, uint256 amount) = royaltyContract
.royaltyInfo(_tokenId, _auctioneerCut);
require(
amount < _auctioneerCut,
"JamMarketplace: royalty amount must be less than auctioneer cut"
);
_totalRoyaltyCut[address(0)] = _totalRoyaltyCut[address(0)].add(
amount
);
royaltyCuts[firstOwner][address(0)] = royaltyCuts[firstOwner][
address(0)
].add(amount);
}
}
if (_bidAmount > _price) {
uint256 _bidExcess = _bidAmount - _price;
payable(msg.sender).transfer(_bidExcess);
}
return _price;
}
function _buy(
address _nftAddress,
uint256 _tokenId,
uint256 _bidAmount
) internal returns (uint256) {
Auction storage _auction = auctions[_nftAddress][_tokenId];
require(_isOnAuction(_auction), "JamMarketplace: not on auction");
uint256 _price = _auction.price;
require(
_bidAmount >= _price,
"JamMarketplace: bid amount cannot be less than price"
);
address _seller = _auction.seller;
_removeAuction(_nftAddress, _tokenId);
if (_price > 0) {
uint256 _auctioneerCut = _computeCut(_price);
uint256 _sellerProceeds = _price - _auctioneerCut;
payable(_seller).transfer(_sellerProceeds);
if (_supportIERC2981(_nftAddress)) {
IERC2981 royaltyContract = _getERC2981(_nftAddress);
(address firstOwner, uint256 amount) = royaltyContract
.royaltyInfo(_tokenId, _auctioneerCut);
require(
amount < _auctioneerCut,
"JamMarketplace: royalty amount must be less than auctioneer cut"
);
_totalRoyaltyCut[address(0)] = _totalRoyaltyCut[address(0)].add(
amount
);
royaltyCuts[firstOwner][address(0)] = royaltyCuts[firstOwner][
address(0)
].add(amount);
}
}
if (_bidAmount > _price) {
uint256 _bidExcess = _bidAmount - _price;
payable(msg.sender).transfer(_bidExcess);
}
return _price;
}
emit AuctionSuccessful(_nftAddress, _tokenId, _price, msg.sender);
function withdraw(address _erc20Address) public {
uint256 lastWithdraw = lastWithdraws[msg.sender][_erc20Address];
require(
lastWithdraw + withdrawDuration <= block.timestamp,
"JamMarketplace: only withdraw after 14 days before previous withdraw"
);
uint256 royaltyCut = royaltyCuts[msg.sender][_erc20Address];
require(royaltyCut > 0, "JamMarketplace: no royalty cut to withdraw");
royaltyCuts[msg.sender][_erc20Address] = 0;
_totalRoyaltyCut[_erc20Address] = _totalRoyaltyCut[_erc20Address].sub(
royaltyCut
);
lastWithdraws[msg.sender][_erc20Address] = block.timestamp;
if (_erc20Address == address(0)) {
payable(msg.sender).transfer(royaltyCut);
IERC20 erc20Contract = _getERC20Contract(_erc20Address);
bool success = erc20Contract.transfer(msg.sender, royaltyCut);
require(success, "JamMarketplace: transfer failed");
}
}
function withdraw(address _erc20Address) public {
uint256 lastWithdraw = lastWithdraws[msg.sender][_erc20Address];
require(
lastWithdraw + withdrawDuration <= block.timestamp,
"JamMarketplace: only withdraw after 14 days before previous withdraw"
);
uint256 royaltyCut = royaltyCuts[msg.sender][_erc20Address];
require(royaltyCut > 0, "JamMarketplace: no royalty cut to withdraw");
royaltyCuts[msg.sender][_erc20Address] = 0;
_totalRoyaltyCut[_erc20Address] = _totalRoyaltyCut[_erc20Address].sub(
royaltyCut
);
lastWithdraws[msg.sender][_erc20Address] = block.timestamp;
if (_erc20Address == address(0)) {
payable(msg.sender).transfer(royaltyCut);
IERC20 erc20Contract = _getERC20Contract(_erc20Address);
bool success = erc20Contract.transfer(msg.sender, royaltyCut);
require(success, "JamMarketplace: transfer failed");
}
}
} else {
function reclaimERC20(address _erc20Address) external onlyOwner {
IERC20 erc20Contract = _getERC20Contract(_erc20Address);
erc20Contract.transfer(
owner(),
erc20Contract.balanceOf(address(this)).sub(
_totalRoyaltyCut[_erc20Address]
)
);
}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
}
| 7,327,326 | [
1,
23869,
87,
392,
279,
4062,
603,
392,
423,
4464,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
804,
301,
3882,
24577,
353,
4393,
2279,
41,
1136,
16,
21800,
16665,
16,
868,
8230,
12514,
16709,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
203,
565,
1958,
432,
4062,
288,
203,
3639,
1758,
29804,
31,
203,
3639,
2254,
10392,
6205,
31,
203,
3639,
1758,
290,
1222,
1887,
31,
203,
3639,
2254,
5034,
1147,
548,
31,
203,
3639,
2254,
1105,
5746,
861,
31,
203,
565,
289,
203,
203,
565,
2254,
5034,
598,
9446,
5326,
273,
5045,
4681,
31,
203,
203,
203,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
1142,
1190,
9446,
87,
31,
203,
203,
565,
871,
432,
4062,
6119,
12,
203,
3639,
1758,
8808,
290,
1222,
1887,
16,
203,
3639,
2254,
5034,
8808,
1147,
548,
16,
203,
3639,
2254,
5034,
6205,
16,
203,
3639,
1758,
29804,
16,
203,
3639,
1758,
6445,
71,
3462,
1887,
203,
565,
11272,
203,
203,
565,
871,
432,
4062,
14277,
12,
203,
3639,
1758,
8808,
290,
1222,
1887,
16,
203,
3639,
2254,
5034,
8808,
1147,
548,
16,
203,
3639,
2254,
5034,
6205,
16,
203,
3639,
1758,
5657,
1224,
203,
565,
11272,
203,
203,
565,
871,
432,
4062,
21890,
12,
2867,
8808,
290,
1222,
1887,
16,
2254,
5034,
8808,
1147,
548,
1769,
203,
203,
565,
2254,
5034,
1071,
3410,
15812,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
4963,
54,
13372,
15006,
15812,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
11890,
5034,
516,
432,
4062,
3719,
1071,
279,
4062,
87,
31,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import "hardhat/console.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Module } from "../core/Module.sol";
import { IMembership } from "../interfaces/IMembership.sol";
import { IModulePayroll } from "../interfaces/IModulePayroll.sol";
/**
* @title Payroll Module
* @notice The Payroll module enables the payment of monthly, weekly, annual bonuses and dividends by managing the payroll list of DAO members. It provides a quick way to help managers create module proposals.
*/
contract Payroll is Module, IModulePayroll {
using Strings for uint256;
using Address for address payable;
// MemberId => (PayrollPeriod => PayrollDetail[])
mapping(uint256 => mapping(PayrollPeriod => PayrollDetail[]))
private _payrolls;
mapping(bytes32 => PayrollKeys) private _payrollIds;
string[] private _payrollTypes = [
"Salary",
"Bonus",
"Commission",
"Dividend",
"Other"
];
string[] private _payrollPeriods = [
"Monthly",
"Quarterly",
"Yearly",
"OneTime"
];
constructor(
address membership,
uint256[] memory operators,
uint256 delay
) Module("Payroll", "Payroll Module V1", membership, operators, delay) {}
/**
* @dev Get Payroll
* Get compensation plans of a member
*/
function getPayroll(uint256 memberId, PayrollPeriod period)
public
view
returns (PayrollDetail[] memory)
{
return _payrolls[memberId][period];
}
/**
* @dev Add Payroll
* Add a compensation plan for a member
*/
function addPayroll(uint256 memberId, PayrollDetail calldata payroll)
public
onlyOperator
{
_payrolls[memberId][payroll.period].push(payroll);
emit PayrollAdded(memberId, payroll);
}
/**
* @dev Schedule Payroll
* Adding a member's compensation proposal to the compensation cycle
*/
function schedulePayroll(uint256 memberId, PayrollPeriod period)
public
onlyOperator
returns (bytes32 _proposalId)
{
PayrollDetail[] memory payrolls = getPayroll(memberId, period);
address[] memory targets = new address[](payrolls.length);
uint256[] memory values = new uint256[](payrolls.length);
bytes[] memory calldatas = new bytes[](payrolls.length);
string memory description = string(
abi.encodePacked(
_payrollPeriods[uint256(period)],
" Payroll for #",
memberId.toString(),
" (",
_payrollTypes[uint256(payrolls[0].paytype)],
") ",
"@",
block.timestamp.toString()
)
);
address memberWallet = getAddressByMemberId(memberId);
for (uint256 i = 0; i < payrolls.length; ++i) {
PayrollDetail memory payroll = payrolls[i];
targets[i] = address(this);
values[i] = payroll.amount;
// TODO: use byte4(func selector) to reduce the size of calldata
calldatas[i] = abi.encodeWithSignature(
"execTransfer(uint256,address,address[],uint256[])",
memberId,
memberWallet,
payroll.tokens.addresses,
payroll.tokens.amounts
);
}
bytes32 _referId = keccak256(abi.encode(memberId, period));
_payrollIds[_referId] = PayrollKeys(memberId, period);
_proposalId = propose(targets, values, calldatas, description, _referId);
emit PayrollScheduled(memberId, _proposalId);
}
function _beforeExecute(bytes32 id, bytes32 referId)
internal
virtual
override
{
super._beforeExecute(id, referId);
PayrollKeys memory _keys = _payrollIds[referId];
PayrollDetail[] memory payrolls = _payrolls[_keys.memberId][_keys.period];
uint256 _eth;
uint256 _balance = address(timelock).balance;
address[] memory _tokens;
uint256[] memory _amounts;
// TODO: support pull multiple tokens
for (uint256 i = 0; i < payrolls.length; ++i) {
PayrollDetail memory payroll = payrolls[i];
_eth += payroll.amount;
}
pullPayments(_balance < _eth ? _eth - _balance : 0, _tokens, _amounts);
}
/**
* @dev Exec Transfer
* Hook method for payroll proposals
*/
function execTransfer(
uint256 memberId,
address payable account,
address[] calldata tokens,
uint256[] calldata amounts
) external payable onlyTimelock {
if (msg.value > 0) {
account.sendValue(msg.value);
}
for (uint256 i = 0; i < tokens.length; i++) {
if (IERC20(tokens[i]).balanceOf(address(timelock)) >= amounts[i]) {
IERC20(tokens[i]).transferFrom(
address(timelock),
address(account),
amounts[i]
);
}
}
emit PayrollExecuted(account, memberId, msg.value);
}
}
| TODO: support pull multiple tokens | function _beforeExecute(bytes32 id, bytes32 referId)
internal
virtual
override
{
super._beforeExecute(id, referId);
PayrollKeys memory _keys = _payrollIds[referId];
PayrollDetail[] memory payrolls = _payrolls[_keys.memberId][_keys.period];
uint256 _eth;
uint256 _balance = address(timelock).balance;
address[] memory _tokens;
uint256[] memory _amounts;
for (uint256 i = 0; i < payrolls.length; ++i) {
PayrollDetail memory payroll = payrolls[i];
_eth += payroll.amount;
}
pullPayments(_balance < _eth ? _eth - _balance : 0, _tokens, _amounts);
}
| 952,405 | [
1,
6241,
30,
2865,
6892,
3229,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
389,
5771,
5289,
12,
3890,
1578,
612,
16,
1731,
1578,
8884,
548,
13,
203,
565,
2713,
203,
565,
5024,
203,
565,
3849,
203,
225,
288,
203,
565,
2240,
6315,
5771,
5289,
12,
350,
16,
8884,
548,
1769,
203,
203,
565,
13838,
2693,
2396,
3778,
389,
2452,
273,
389,
10239,
2693,
2673,
63,
266,
586,
548,
15533,
203,
565,
13838,
2693,
6109,
8526,
3778,
8843,
2693,
87,
273,
389,
10239,
2693,
87,
63,
67,
2452,
18,
5990,
548,
6362,
67,
2452,
18,
6908,
15533,
203,
565,
2254,
5034,
389,
546,
31,
203,
565,
2254,
5034,
389,
12296,
273,
1758,
12,
8584,
292,
975,
2934,
12296,
31,
203,
565,
1758,
8526,
3778,
389,
7860,
31,
203,
565,
2254,
5034,
8526,
3778,
389,
8949,
87,
31,
203,
203,
565,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
8843,
2693,
87,
18,
2469,
31,
965,
77,
13,
288,
203,
1377,
13838,
2693,
6109,
3778,
8843,
2693,
273,
8843,
2693,
87,
63,
77,
15533,
203,
1377,
389,
546,
1011,
8843,
2693,
18,
8949,
31,
203,
565,
289,
203,
203,
565,
6892,
23725,
24899,
12296,
411,
389,
546,
692,
389,
546,
300,
389,
12296,
294,
374,
16,
389,
7860,
16,
389,
8949,
87,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.24;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @title Escrow (based on openzeppelin version with one function to withdraw funds to the wallet)
* @dev Base escrow contract, holds funds destinated to a payee until they
* withdraw them. The contract that uses the escrow as its payment method
* should be its owner, and provide public methods redirecting to the escrow's
* deposit and withdraw.
*/
contract Escrow is Ownable {
using SafeMath for uint256;
event Deposited(address indexed payee, uint256 weiAmount);
event Withdrawn(address indexed payee, uint256 weiAmount);
mapping(address => uint256) private deposits;
/**
* @dev Stores the sent amount as credit to be withdrawn.
* @param _payee The destination address of the funds.
*/
function deposit(address _payee) public onlyOwner payable {
uint256 amount = msg.value;
deposits[_payee] = deposits[_payee].add(amount);
emit Deposited(_payee, amount);
}
/**
* @dev Withdraw accumulated balance for a payee.
* @param _payee The address whose funds will be withdrawn and transferred to.
* @return Amount withdrawn
*/
function withdraw(address _payee) public onlyOwner returns(uint256) {
uint256 payment = deposits[_payee];
assert(address(this).balance >= payment);
deposits[_payee] = 0;
_payee.transfer(payment);
emit Withdrawn(_payee, payment);
return payment;
}
/**
* @dev Withdraws the wallet's funds.
* @param _wallet address the funds will be transferred to.
*/
function beneficiaryWithdraw(address _wallet) public onlyOwner {
uint256 _amount = address(this).balance;
_wallet.transfer(_amount);
emit Withdrawn(_wallet, _amount);
}
/**
* @dev Returns the deposited amount of the given address.
* @param _payee address of the payee of which to return the deposted amount.
* @return Deposited amount by the address given as argument.
*/
function depositsOf(address _payee) public view returns(uint256) {
return deposits[_payee];
}
}
/**
* @title PullPayment (based on openzeppelin version with one function to withdraw funds to the wallet)
* @dev Base contract supporting async send for pull payments. Inherit from this
* contract and use asyncTransfer instead of send or transfer.
*/
contract PullPayment {
Escrow private escrow;
constructor() public {
escrow = new Escrow();
}
/**
* @dev Returns the credit owed to an address.
* @param _dest The creditor's address.
* @return Deposited amount by the address given as argument.
*/
function payments(address _dest) public view returns(uint256) {
return escrow.depositsOf(_dest);
}
/**
* @dev Withdraw accumulated balance, called by payee.
* @param _payee The address whose funds will be withdrawn and transferred to.
* @return Amount withdrawn
*/
function _withdrawPayments(address _payee) internal returns(uint256) {
uint256 payment = escrow.withdraw(_payee);
return payment;
}
/**
* @dev Called by the payer to store the sent amount as credit to be pulled.
* @param _dest The destination address of the funds.
* @param _amount The amount to transfer.
*/
function _asyncTransfer(address _dest, uint256 _amount) internal {
escrow.deposit.value(_amount)(_dest);
}
/**
* @dev Withdraws the wallet's funds.
* @param _wallet address the funds will be transferred to.
*/
function _withdrawFunds(address _wallet) internal {
escrow.beneficiaryWithdraw(_wallet);
}
}
/** @title VestedCrowdsale
* @dev Extension of Crowdsale to allow a vested distribution of tokens
* Users have to individually claim their tokens
*/
contract VestedCrowdsale {
using SafeMath for uint256;
mapping (address => uint256) public withdrawn;
mapping (address => uint256) public contributions;
mapping (address => uint256) public contributionsRound;
uint256 public vestedTokens;
/**
* @dev Gives how much a user is allowed to withdraw at the current moment
* @param _beneficiary The address of the user asking how much he's allowed
* to withdraw
* @return Amount _beneficiary is allowed to withdraw
*/
function getWithdrawableAmount(address _beneficiary) public view returns(uint256) {
uint256 step = _getVestingStep(_beneficiary);
uint256 valueByStep = _getValueByStep(_beneficiary);
uint256 result = step.mul(valueByStep).sub(withdrawn[_beneficiary]);
return result;
}
/**
* @dev Gives the step of the vesting (starts from 0 to steps)
* @param _beneficiary The address of the user asking how much he's allowed
* to withdraw
* @return The vesting step for _beneficiary
*/
function _getVestingStep(address _beneficiary) internal view returns(uint8) {
require(contributions[_beneficiary] != 0);
require(contributionsRound[_beneficiary] > 0 && contributionsRound[_beneficiary] < 4);
uint256 march31 = 1554019200;
uint256 april30 = 1556611200;
uint256 may31 = 1559289600;
uint256 june30 = 1561881600;
uint256 july31 = 1564560000;
uint256 sept30 = 1569830400;
uint256 contributionRound = contributionsRound[_beneficiary];
// vesting for private sale contributors
if (contributionRound == 1) {
if (block.timestamp < march31) {
return 0;
}
if (block.timestamp < june30) {
return 1;
}
if (block.timestamp < sept30) {
return 2;
}
return 3;
}
// vesting for pre ico contributors
if (contributionRound == 2) {
if (block.timestamp < april30) {
return 0;
}
if (block.timestamp < july31) {
return 1;
}
return 2;
}
// vesting for ico contributors
if (contributionRound == 3) {
if (block.timestamp < may31) {
return 0;
}
return 1;
}
}
/**
* @dev Gives the amount a user is allowed to withdraw by step
* @param _beneficiary The address of the user asking how much he's allowed
* to withdraw
* @return How much a user is allowed to withdraw by step
*/
function _getValueByStep(address _beneficiary) internal view returns(uint256) {
require(contributions[_beneficiary] != 0);
require(contributionsRound[_beneficiary] > 0 && contributionsRound[_beneficiary] < 4);
uint256 contributionRound = contributionsRound[_beneficiary];
uint256 amount;
uint256 rate;
if (contributionRound == 1) {
rate = 416700;
amount = contributions[_beneficiary].mul(rate).mul(25).div(100);
return amount;
} else if (contributionRound == 2) {
rate = 312500;
amount = contributions[_beneficiary].mul(rate).mul(25).div(100);
return amount;
}
rate = 250000;
amount = contributions[_beneficiary].mul(rate).mul(25).div(100);
return amount;
}
}
/**
* @title Whitelist
* @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions.
* This simplifies the implementation of "user permissions".
*/
contract Whitelist is Ownable {
// Whitelisted address
mapping(address => bool) public whitelist;
event AddedBeneficiary(address indexed _beneficiary);
event RemovedBeneficiary(address indexed _beneficiary);
/**
* @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing.
* @param _beneficiaries Addresses to be added to the whitelist
*/
function addAddressToWhitelist(address[] _beneficiaries) public onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
whitelist[_beneficiaries[i]] = true;
emit AddedBeneficiary(_beneficiaries[i]);
}
}
/**
* @dev Adds list of address to whitelist. Not overloaded due to limitations with truffle testing.
* @param _beneficiary Address to be added to the whitelist
*/
function addToWhitelist(address _beneficiary) public onlyOwner {
whitelist[_beneficiary] = true;
emit AddedBeneficiary(_beneficiary);
}
/**
* @dev Removes single address from whitelist.
* @param _beneficiary Address to be removed to the whitelist
*/
function removeFromWhitelist(address _beneficiary) public onlyOwner {
whitelist[_beneficiary] = false;
emit RemovedBeneficiary(_beneficiary);
}
}
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The address which you want to send tokens from
* @param value uint256 The amount of token to be burned
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
/**
* @title DSLACrowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether
*/
contract DSLACrowdsale is VestedCrowdsale, Whitelist, Pausable, PullPayment {
// struct to store ico rounds details
struct IcoRound {
uint256 rate;
uint256 individualFloor;
uint256 individualCap;
uint256 softCap;
uint256 hardCap;
}
// mapping ico rounds
mapping (uint256 => IcoRound) public icoRounds;
// The token being sold
ERC20Burnable private _token;
// Address where funds are collected
address private _wallet;
// Amount of wei raised
uint256 private totalContributionAmount;
// Tokens to sell = 5 Billions * 10^18 = 5 * 10^27 = 5000000000000000000000000000
uint256 public constant TOKENSFORSALE = 5000000000000000000000000000;
// Current ico round
uint256 public currentIcoRound;
// Distributed Tokens
uint256 public distributedTokens;
// Amount of wei raised from other currencies
uint256 public weiRaisedFromOtherCurrencies;
// Refund period on
bool public isRefunding = false;
// Finalized crowdsale off
bool public isFinalized = false;
// Refunding deadline
uint256 public refundDeadline;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor(address wallet, ERC20Burnable token) public {
require(wallet != address(0) && token != address(0));
icoRounds[1] = IcoRound(
416700,
3 ether,
600 ether,
0,
1200 ether
);
icoRounds[2] = IcoRound(
312500,
12 ether,
5000 ether,
0,
6000 ether
);
icoRounds[3] = IcoRound(
250000,
3 ether,
30 ether,
7200 ether,
17200 ether
);
_wallet = wallet;
_token = token;
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _contributor Address performing the token purchase
*/
function buyTokens(address _contributor) public payable {
require(whitelist[_contributor]);
uint256 contributionAmount = msg.value;
_preValidatePurchase(_contributor, contributionAmount, currentIcoRound);
totalContributionAmount = totalContributionAmount.add(contributionAmount);
uint tokenAmount = _handlePurchase(contributionAmount, currentIcoRound, _contributor);
emit TokensPurchased(msg.sender, _contributor, contributionAmount, tokenAmount);
_forwardFunds();
}
/**
* @dev Function to go to the next round
* @return True bool when round is incremented
*/
function goToNextRound() public onlyOwner returns(bool) {
require(currentIcoRound >= 0 && currentIcoRound < 3);
currentIcoRound = currentIcoRound + 1;
return true;
}
/**
* @dev Manually adds a contributor's contribution for private presale period
* @param _contributor The address of the contributor
* @param _contributionAmount Amount of wei contributed
*/
function addPrivateSaleContributors(address _contributor, uint256 _contributionAmount)
public onlyOwner
{
uint privateSaleRound = 1;
_preValidatePurchase(_contributor, _contributionAmount, privateSaleRound);
totalContributionAmount = totalContributionAmount.add(_contributionAmount);
addToWhitelist(_contributor);
_handlePurchase(_contributionAmount, privateSaleRound, _contributor);
}
/**
* @dev Manually adds a contributor's contribution with other currencies
* @param _contributor The address of the contributor
* @param _contributionAmount Amount of wei contributed
* @param _round contribution round
*/
function addOtherCurrencyContributors(address _contributor, uint256 _contributionAmount, uint256 _round)
public onlyOwner
{
_preValidatePurchase(_contributor, _contributionAmount, _round);
weiRaisedFromOtherCurrencies = weiRaisedFromOtherCurrencies.add(_contributionAmount);
addToWhitelist(_contributor);
_handlePurchase(_contributionAmount, _round, _contributor);
}
/**
* @dev Function to close refunding period
* @return True bool
*/
function closeRefunding() public returns(bool) {
require(isRefunding);
require(block.timestamp > refundDeadline);
isRefunding = false;
_withdrawFunds(wallet());
return true;
}
/**
* @dev Function to close the crowdsale
* @return True bool
*/
function closeCrowdsale() public onlyOwner returns(bool) {
require(currentIcoRound > 0 && currentIcoRound < 4);
currentIcoRound = 4;
return true;
}
/**
* @dev Function to finalize the crowdsale
* @param _burn bool burn unsold tokens when true
* @return True bool
*/
function finalizeCrowdsale(bool _burn) public onlyOwner returns(bool) {
require(currentIcoRound == 4 && !isRefunding);
if (raisedFunds() < icoRounds[3].softCap) {
isRefunding = true;
refundDeadline = block.timestamp + 4 weeks;
return true;
}
require(!isFinalized);
_withdrawFunds(wallet());
isFinalized = true;
if (_burn) {
_burnUnsoldTokens();
} else {
_withdrawUnsoldTokens();
}
return true;
}
/**
* @dev Investors can claim refunds here if crowdsale is unsuccessful
*/
function claimRefund() public {
require(isRefunding);
require(block.timestamp <= refundDeadline);
require(payments(msg.sender) > 0);
uint256 payment = _withdrawPayments(msg.sender);
totalContributionAmount = totalContributionAmount.sub(payment);
}
/**
* @dev Allows the sender to claim the tokens he is allowed to withdraw
*/
function claimTokens() public {
require(getWithdrawableAmount(msg.sender) != 0);
uint256 amount = getWithdrawableAmount(msg.sender);
withdrawn[msg.sender] = withdrawn[msg.sender].add(amount);
_deliverTokens(msg.sender, amount);
}
/**
* @dev returns the token being sold
* @return the token being sold
*/
function token() public view returns(ERC20Burnable) {
return _token;
}
/**
* @dev returns the wallet address that collects the funds
* @return the address where funds are collected
*/
function wallet() public view returns(address) {
return _wallet;
}
/**
* @dev Returns the total of raised funds
* @return total amount of raised funds
*/
function raisedFunds() public view returns(uint256) {
return totalContributionAmount.add(weiRaisedFromOtherCurrencies);
}
// -----------------------------------------
// Internal interface
// -----------------------------------------
/**
* @dev Source of tokens. Override this method to modify the way in which
* the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount)
internal
{
_token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds()
internal
{
if (currentIcoRound == 2 || currentIcoRound == 3) {
_asyncTransfer(msg.sender, msg.value);
} else {
_wallet.transfer(msg.value);
}
}
/**
* @dev Gets tokens allowed to deliver in the given round
* @param _tokenAmount total amount of tokens involved in the purchase
* @param _round Round in which the purchase is happening
* @return Returns the amount of tokens allowed to deliver
*/
function _getTokensToDeliver(uint _tokenAmount, uint _round)
internal pure returns(uint)
{
require(_round > 0 && _round < 4);
uint deliverPercentage = _round.mul(25);
return _tokenAmount.mul(deliverPercentage).div(100);
}
/**
* @dev Handles token purchasing
* @param _contributor Address performing the token purchase
* @param _contributionAmount Value in wei involved in the purchase
* @param _round Round in which the purchase is happening
* @return Returns the amount of tokens purchased
*/
function _handlePurchase(uint _contributionAmount, uint _round, address _contributor)
internal returns(uint) {
uint256 soldTokens = distributedTokens.add(vestedTokens);
uint256 tokenAmount = _getTokenAmount(_contributionAmount, _round);
require(tokenAmount.add(soldTokens) <= TOKENSFORSALE);
contributions[_contributor] = contributions[_contributor].add(_contributionAmount);
contributionsRound[_contributor] = _round;
uint tokensToDeliver = _getTokensToDeliver(tokenAmount, _round);
uint tokensToVest = tokenAmount.sub(tokensToDeliver);
distributedTokens = distributedTokens.add(tokensToDeliver);
vestedTokens = vestedTokens.add(tokensToVest);
_deliverTokens(_contributor, tokensToDeliver);
return tokenAmount;
}
/**
* @dev Validation of an incoming purchase.
* @param _contributor Address performing the token purchase
* @param _contributionAmount Value in wei involved in the purchase
* @param _round Round in which the purchase is happening
*/
function _preValidatePurchase(address _contributor, uint256 _contributionAmount, uint _round)
internal view
{
require(_contributor != address(0));
require(currentIcoRound > 0 && currentIcoRound < 4);
require(_round > 0 && _round < 4);
require(contributions[_contributor] == 0);
require(_contributionAmount >= icoRounds[_round].individualFloor);
require(_contributionAmount < icoRounds[_round].individualCap);
require(_doesNotExceedHardCap(_contributionAmount, _round));
}
/**
* @dev define the way in which ether is converted to tokens.
* @param _contributionAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _contributionAmount
*/
function _getTokenAmount(uint256 _contributionAmount, uint256 _round)
internal view returns(uint256)
{
uint256 _rate = icoRounds[_round].rate;
return _contributionAmount.mul(_rate);
}
/**
* @dev Checks if current round hardcap will not be exceeded by a new contribution
* @param _contributionAmount purchase amount in Wei
* @param _round Round in which the purchase is happening
* @return true when current hardcap is not exceeded, false if exceeded
*/
function _doesNotExceedHardCap(uint _contributionAmount, uint _round)
internal view returns(bool)
{
uint roundHardCap = icoRounds[_round].hardCap;
return totalContributionAmount.add(_contributionAmount) <= roundHardCap;
}
/**
* @dev Function to burn unsold tokens
*/
function _burnUnsoldTokens()
internal
{
uint256 tokensToBurn = TOKENSFORSALE.sub(vestedTokens).sub(distributedTokens);
_token.burn(tokensToBurn);
}
/**
* @dev Transfer the unsold tokens to the funds collecting address
*/
function _withdrawUnsoldTokens()
internal {
uint256 tokensToWithdraw = TOKENSFORSALE.sub(vestedTokens).sub(distributedTokens);
_token.transfer(_wallet, tokensToWithdraw);
}
} | * @title DSLACrowdsale @dev Crowdsale is a base contract for managing a token crowdsale, allowing investors to purchase tokens with ether/ struct to store ico rounds details | contract DSLACrowdsale is VestedCrowdsale, Whitelist, Pausable, PullPayment {
struct IcoRound {
uint256 rate;
uint256 individualFloor;
uint256 individualCap;
uint256 softCap;
uint256 hardCap;
}
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
mapping (uint256 => IcoRound) public icoRounds;
ERC20Burnable private _token;
address private _wallet;
uint256 private totalContributionAmount;
uint256 public constant TOKENSFORSALE = 5000000000000000000000000000;
uint256 public currentIcoRound;
uint256 public distributedTokens;
uint256 public weiRaisedFromOtherCurrencies;
bool public isRefunding = false;
bool public isFinalized = false;
uint256 public refundDeadline;
event TokensPurchased(
constructor(address wallet, ERC20Burnable token) public {
require(wallet != address(0) && token != address(0));
icoRounds[1] = IcoRound(
416700,
3 ether,
600 ether,
0,
1200 ether
);
icoRounds[2] = IcoRound(
312500,
12 ether,
5000 ether,
0,
6000 ether
);
icoRounds[3] = IcoRound(
250000,
3 ether,
30 ether,
7200 ether,
17200 ether
);
_wallet = wallet;
_token = token;
}
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address _contributor) public payable {
require(whitelist[_contributor]);
uint256 contributionAmount = msg.value;
_preValidatePurchase(_contributor, contributionAmount, currentIcoRound);
totalContributionAmount = totalContributionAmount.add(contributionAmount);
uint tokenAmount = _handlePurchase(contributionAmount, currentIcoRound, _contributor);
emit TokensPurchased(msg.sender, _contributor, contributionAmount, tokenAmount);
_forwardFunds();
}
function goToNextRound() public onlyOwner returns(bool) {
require(currentIcoRound >= 0 && currentIcoRound < 3);
currentIcoRound = currentIcoRound + 1;
return true;
}
function addPrivateSaleContributors(address _contributor, uint256 _contributionAmount)
public onlyOwner
{
uint privateSaleRound = 1;
_preValidatePurchase(_contributor, _contributionAmount, privateSaleRound);
totalContributionAmount = totalContributionAmount.add(_contributionAmount);
addToWhitelist(_contributor);
_handlePurchase(_contributionAmount, privateSaleRound, _contributor);
}
function addOtherCurrencyContributors(address _contributor, uint256 _contributionAmount, uint256 _round)
public onlyOwner
{
_preValidatePurchase(_contributor, _contributionAmount, _round);
weiRaisedFromOtherCurrencies = weiRaisedFromOtherCurrencies.add(_contributionAmount);
addToWhitelist(_contributor);
_handlePurchase(_contributionAmount, _round, _contributor);
}
function closeRefunding() public returns(bool) {
require(isRefunding);
require(block.timestamp > refundDeadline);
isRefunding = false;
_withdrawFunds(wallet());
return true;
}
function closeCrowdsale() public onlyOwner returns(bool) {
require(currentIcoRound > 0 && currentIcoRound < 4);
currentIcoRound = 4;
return true;
}
function finalizeCrowdsale(bool _burn) public onlyOwner returns(bool) {
require(currentIcoRound == 4 && !isRefunding);
if (raisedFunds() < icoRounds[3].softCap) {
isRefunding = true;
refundDeadline = block.timestamp + 4 weeks;
return true;
}
require(!isFinalized);
_withdrawFunds(wallet());
isFinalized = true;
if (_burn) {
_burnUnsoldTokens();
_withdrawUnsoldTokens();
}
return true;
}
function finalizeCrowdsale(bool _burn) public onlyOwner returns(bool) {
require(currentIcoRound == 4 && !isRefunding);
if (raisedFunds() < icoRounds[3].softCap) {
isRefunding = true;
refundDeadline = block.timestamp + 4 weeks;
return true;
}
require(!isFinalized);
_withdrawFunds(wallet());
isFinalized = true;
if (_burn) {
_burnUnsoldTokens();
_withdrawUnsoldTokens();
}
return true;
}
function finalizeCrowdsale(bool _burn) public onlyOwner returns(bool) {
require(currentIcoRound == 4 && !isRefunding);
if (raisedFunds() < icoRounds[3].softCap) {
isRefunding = true;
refundDeadline = block.timestamp + 4 weeks;
return true;
}
require(!isFinalized);
_withdrawFunds(wallet());
isFinalized = true;
if (_burn) {
_burnUnsoldTokens();
_withdrawUnsoldTokens();
}
return true;
}
} else {
function claimRefund() public {
require(isRefunding);
require(block.timestamp <= refundDeadline);
require(payments(msg.sender) > 0);
uint256 payment = _withdrawPayments(msg.sender);
totalContributionAmount = totalContributionAmount.sub(payment);
}
function claimTokens() public {
require(getWithdrawableAmount(msg.sender) != 0);
uint256 amount = getWithdrawableAmount(msg.sender);
withdrawn[msg.sender] = withdrawn[msg.sender].add(amount);
_deliverTokens(msg.sender, amount);
}
function token() public view returns(ERC20Burnable) {
return _token;
}
function wallet() public view returns(address) {
return _wallet;
}
function raisedFunds() public view returns(uint256) {
return totalContributionAmount.add(weiRaisedFromOtherCurrencies);
}
function _deliverTokens(address _beneficiary, uint256 _tokenAmount)
internal
{
_token.transfer(_beneficiary, _tokenAmount);
}
function _forwardFunds()
internal
{
if (currentIcoRound == 2 || currentIcoRound == 3) {
_asyncTransfer(msg.sender, msg.value);
_wallet.transfer(msg.value);
}
}
function _forwardFunds()
internal
{
if (currentIcoRound == 2 || currentIcoRound == 3) {
_asyncTransfer(msg.sender, msg.value);
_wallet.transfer(msg.value);
}
}
} else {
function _getTokensToDeliver(uint _tokenAmount, uint _round)
internal pure returns(uint)
{
require(_round > 0 && _round < 4);
uint deliverPercentage = _round.mul(25);
return _tokenAmount.mul(deliverPercentage).div(100);
}
function _handlePurchase(uint _contributionAmount, uint _round, address _contributor)
internal returns(uint) {
uint256 soldTokens = distributedTokens.add(vestedTokens);
uint256 tokenAmount = _getTokenAmount(_contributionAmount, _round);
require(tokenAmount.add(soldTokens) <= TOKENSFORSALE);
contributions[_contributor] = contributions[_contributor].add(_contributionAmount);
contributionsRound[_contributor] = _round;
uint tokensToDeliver = _getTokensToDeliver(tokenAmount, _round);
uint tokensToVest = tokenAmount.sub(tokensToDeliver);
distributedTokens = distributedTokens.add(tokensToDeliver);
vestedTokens = vestedTokens.add(tokensToVest);
_deliverTokens(_contributor, tokensToDeliver);
return tokenAmount;
}
function _preValidatePurchase(address _contributor, uint256 _contributionAmount, uint _round)
internal view
{
require(_contributor != address(0));
require(currentIcoRound > 0 && currentIcoRound < 4);
require(_round > 0 && _round < 4);
require(contributions[_contributor] == 0);
require(_contributionAmount >= icoRounds[_round].individualFloor);
require(_contributionAmount < icoRounds[_round].individualCap);
require(_doesNotExceedHardCap(_contributionAmount, _round));
}
function _getTokenAmount(uint256 _contributionAmount, uint256 _round)
internal view returns(uint256)
{
uint256 _rate = icoRounds[_round].rate;
return _contributionAmount.mul(_rate);
}
function _doesNotExceedHardCap(uint _contributionAmount, uint _round)
internal view returns(bool)
{
uint roundHardCap = icoRounds[_round].hardCap;
return totalContributionAmount.add(_contributionAmount) <= roundHardCap;
}
function _burnUnsoldTokens()
internal
{
uint256 tokensToBurn = TOKENSFORSALE.sub(vestedTokens).sub(distributedTokens);
_token.burn(tokensToBurn);
}
function _withdrawUnsoldTokens()
internal {
uint256 tokensToWithdraw = TOKENSFORSALE.sub(vestedTokens).sub(distributedTokens);
_token.transfer(_wallet, tokensToWithdraw);
}
} | 12,543,417 | [
1,
29387,
2226,
492,
2377,
5349,
225,
385,
492,
2377,
5349,
353,
279,
1026,
6835,
364,
30632,
279,
1147,
276,
492,
2377,
5349,
16,
15632,
2198,
395,
1383,
358,
23701,
2430,
598,
225,
2437,
19,
1958,
358,
1707,
277,
2894,
21196,
3189,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
28053,
2226,
492,
2377,
5349,
353,
776,
3149,
39,
492,
2377,
5349,
16,
3497,
7523,
16,
21800,
16665,
16,
14899,
6032,
288,
203,
565,
1958,
467,
2894,
11066,
288,
203,
3639,
2254,
5034,
4993,
31,
203,
3639,
2254,
5034,
7327,
42,
5807,
31,
203,
3639,
2254,
5034,
7327,
4664,
31,
203,
3639,
2254,
5034,
8971,
4664,
31,
203,
3639,
2254,
5034,
7877,
4664,
31,
203,
565,
289,
203,
203,
203,
3639,
1758,
8808,
5405,
343,
14558,
16,
203,
3639,
1758,
8808,
27641,
74,
14463,
814,
16,
203,
3639,
2254,
5034,
460,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
11272,
203,
203,
565,
2874,
261,
11890,
5034,
516,
467,
2894,
11066,
13,
1071,
277,
2894,
54,
9284,
31,
203,
565,
4232,
39,
3462,
38,
321,
429,
3238,
389,
2316,
31,
203,
565,
1758,
3238,
389,
19177,
31,
203,
565,
2254,
5034,
3238,
2078,
442,
4027,
6275,
31,
203,
565,
2254,
5034,
1071,
5381,
14275,
55,
7473,
5233,
900,
273,
1381,
12648,
12648,
12648,
3784,
31,
203,
565,
2254,
5034,
1071,
783,
45,
2894,
11066,
31,
203,
565,
2254,
5034,
1071,
16859,
5157,
31,
203,
565,
2254,
5034,
1071,
732,
77,
12649,
5918,
1265,
8290,
2408,
14695,
31,
203,
565,
1426,
1071,
353,
1957,
14351,
273,
629,
31,
203,
565,
1426,
1071,
29200,
1235,
273,
629,
31,
203,
565,
2254,
5034,
1071,
16255,
15839,
31,
203,
565,
871,
13899,
10262,
343,
8905,
12,
203,
565,
3885,
12,
2867,
9230,
16,
4232,
39,
3462,
38,
321,
429,
1147,
13,
1071,
288,
203,
3639,
2583,
12,
2
] |
pragma solidity ^0.4.18;
/**
*@title ERC721 interface
*/
contract ERC721 {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function transfer(address _to, uint256 _tokenId) public;
function approve(address _to, uint256 _tokenId) public;
function takeOwnership(uint256 _tokenId) public;
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC721Token
* Generic implementation for the required functionality of the ERC721 standard
*/
contract CryptoMayorToken is ERC721, Ownable, Pausable {
using SafeMath for uint256;
// Total amount of tokens
uint256 private totalTokens;
uint256[] private listed;
uint256 public devOwed;
uint256 public cityPoolTotal;
uint256 public landmarkPoolTotal;
uint256 public otherPoolTotal;
uint256 public lastPurchase;
// Token Data
mapping (uint256 => Token) private tokens;
// Mapping from token ID to owner
mapping (uint256 => address) private tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private tokenApprovals;
// Mapping from owner to list of owned token IDs
mapping (address => uint256[]) private ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private ownedTokensIndex;
// Balances from % payouts.
mapping (address => uint256) private payoutBalances;
// Events
event Purchased(uint256 indexed _tokenId, address indexed _owner, uint256 _purchasePrice);
// Purchasing Caps for Determining Next Pool Cut
uint256 private firstCap = 0.5 ether;
uint256 private secondCap = 1.0 ether;
uint256 private thirdCap = 3.0 ether;
uint256 private finalCap = 5.0 ether;
// Percentages
uint256 public feePercentage = 5;
uint256 public dividendCutPercentage = 100; // 100 / 10000
uint256 public dividendDecreaseFactor = 2;
uint256 public powermayorCutPercentage = 1;
uint256 public mayorCutPercentage = 1;
uint256 public cityPoolCutPercentage = 15;
// Mayors
uint256 private powermayorTokenId = 10000000;
uint256 private CITY = 1;
uint256 private LANDMARK = 2;
uint256 private OTHER = 3;
// Struct to store Token Data
struct Token {
uint256 price; // Current price of the item.
uint256 lastPrice; // lastPrice this was sold for, used for adding to pool.
uint256 payout; // The percent of the pool rewarded.
uint256 withdrawn; // The amount of Eth this token has withdrawn from the pool.
address owner; // Current owner of the item.
uint256 mayorTokenId; // Current mayor of the token - 1% mayorCut
uint8 kind; // 1 - city, 2 - landmark, 3 - other
address[5] previousOwners;
}
/**
* @dev createListing Adds new ERC721 Token
* @param _tokenId uint256 ID of new token
* @param _price uint256 starting price in wei
* @param _payoutPercentage uint256 payout percentage (divisible by 10)
* @param _owner address of new owner
*/
function createToken(uint256 _tokenId, uint256 _price, uint256 _lastPrice, uint256 _payoutPercentage, uint8 _kind, uint256 _mayorTokenId, address _owner) onlyOwner() public {
require(_price > 0);
require(_lastPrice < _price);
// make sure token hasn't been used yet
require(tokens[_tokenId].price == 0);
// check for kinds
require(_kind > 0 && _kind <= 3);
// create new token
Token storage newToken = tokens[_tokenId];
newToken.owner = _owner;
newToken.price = _price;
newToken.lastPrice = _lastPrice;
newToken.payout = _payoutPercentage;
newToken.kind = _kind;
newToken.mayorTokenId = _mayorTokenId;
newToken.previousOwners = [address(this), address(this), address(this), address(this), address(this)];
// store token in storage
listed.push(_tokenId);
// mint new token
_mint(_owner, _tokenId);
}
function createMultiple (uint256[] _itemIds, uint256[] _prices, uint256[] _lastPrices, uint256[] _payouts, uint8[] _kinds, uint256[] _mayorTokenIds, address[] _owners) onlyOwner() external {
for (uint256 i = 0; i < _itemIds.length; i++) {
createToken(_itemIds[i], _prices[i], _lastPrices[i], _payouts[i], _kinds[i], _mayorTokenIds[i], _owners[i]);
}
}
/**
* @dev Determines next price of token
* @param _price uint256 ID of current price
*/
function getNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < firstCap) {
return _price.mul(200).div(100 - feePercentage);
} else if (_price < secondCap) {
return _price.mul(135).div(100 - feePercentage);
} else if (_price < thirdCap) {
return _price.mul(125).div(100 - feePercentage);
} else if (_price < finalCap) {
return _price.mul(117).div(100 - feePercentage);
} else {
return _price.mul(115).div(100 - feePercentage);
}
}
function calculatePoolCut (uint256 _price) public view returns (uint256 _poolCut) {
if (_price < firstCap) {
return _price.mul(10).div(100);
} else if (_price < secondCap) {
return _price.mul(9).div(100);
} else if (_price < thirdCap) {
return _price.mul(8).div(100);
} else if (_price < finalCap) {
return _price.mul(7).div(100);
} else {
return _price.mul(5).div(100);
}
}
/**
* @dev Purchase toekn from previous owner
* @param _tokenId uint256 of token
*/
function purchase(uint256 _tokenId) public
payable
isNotContract(msg.sender)
{
require(!paused);
// get data from storage
Token storage token = tokens[_tokenId];
uint256 price = token.price;
address oldOwner = token.owner;
// revert checks
require(price > 0);
require(msg.value >= price);
require(oldOwner != msg.sender);
// Calculate pool cut for taxes.
uint256 priceDelta = price.sub(token.lastPrice);
uint256 poolCut = calculatePoolCut(priceDelta);
_updatePools(token.kind, poolCut);
uint256 fee = price.mul(feePercentage).div(100);
devOwed = devOwed.add(fee);
// Dividends
uint256 taxesPaid = _payDividendsAndMayors(token, price);
_shiftPreviousOwners(token, msg.sender);
transferToken(oldOwner, msg.sender, _tokenId);
// Transfer payment to old owner minus the developer's and pool's cut.
// Calculate the winnings for the previous owner.
uint256 finalPayout = price.sub(fee).sub(poolCut).sub(taxesPaid);
// set new prices
token.lastPrice = price;
token.price = getNextPrice(price);
// raise event
Purchased(_tokenId, msg.sender, price);
if (oldOwner != address(this)) {
oldOwner.transfer(finalPayout);
}
// Calculate overspending
uint256 excess = msg.value - price;
if (excess > 0) {
// Refund overspending
msg.sender.transfer(excess);
}
// set last purchase price to storage
lastPurchase = now;
}
/// @dev Shift the 6 most recent buyers, and add the new buyer
/// to the front.
/// @param _newOwner The buyer to add to the front of the recent
/// buyers list.
function _shiftPreviousOwners(Token storage _token, address _newOwner) private {
_token.previousOwners[4] = _token.previousOwners[3];
_token.previousOwners[3] = _token.previousOwners[2];
_token.previousOwners[2] = _token.previousOwners[1];
_token.previousOwners[1] = _token.previousOwners[0];
_token.previousOwners[0] = _newOwner;
}
function _updatePools(uint8 _kind, uint256 _poolCut) internal {
uint256 poolCutToMain = _poolCut.mul(cityPoolCutPercentage).div(100);
if (_kind == CITY) {
cityPoolTotal += _poolCut;
} else if (_kind == LANDMARK) {
cityPoolTotal += poolCutToMain;
landmarkPoolTotal += _poolCut.sub(poolCutToMain);
} else if (_kind == OTHER) {
cityPoolTotal += poolCutToMain;
otherPoolTotal += _poolCut.sub(poolCutToMain);
}
}
// 1%, 0.5%, 0.25%, 0.125%, 0.0625%
function _payDividendsAndMayors(Token _token, uint256 _price) private returns (uint256 paid) {
uint256 dividend0 = _price.mul(dividendCutPercentage).div(10000);
uint256 dividend1 = dividend0.div(dividendDecreaseFactor);
uint256 dividend2 = dividend1.div(dividendDecreaseFactor);
uint256 dividend3 = dividend2.div(dividendDecreaseFactor);
uint256 dividend4 = dividend3.div(dividendDecreaseFactor);
// Pay first dividend.
if (_token.previousOwners[0] != address(this)) {_token.previousOwners[0].transfer(dividend0); paid = paid.add(dividend0);}
if (_token.previousOwners[1] != address(this)) {_token.previousOwners[1].transfer(dividend1); paid = paid.add(dividend1);}
if (_token.previousOwners[2] != address(this)) {_token.previousOwners[2].transfer(dividend2); paid = paid.add(dividend2);}
if (_token.previousOwners[3] != address(this)) {_token.previousOwners[3].transfer(dividend3); paid = paid.add(dividend3);}
if (_token.previousOwners[4] != address(this)) {_token.previousOwners[4].transfer(dividend4); paid = paid.add(dividend4);}
uint256 tax = _price.mul(1).div(100);
if (tokens[powermayorTokenId].owner != address(0)) {
tokens[powermayorTokenId].owner.transfer(tax);
paid = paid.add(tax);
}
if (tokens[_token.mayorTokenId].owner != address(0)) {
tokens[_token.mayorTokenId].owner.transfer(tax);
paid = paid.add(tax);
}
}
/**
* @dev Transfer Token from Previous Owner to New Owner
* @param _from previous owner address
* @param _to new owner address
* @param _tokenId uint256 ID of token
*/
function transferToken(address _from, address _to, uint256 _tokenId) internal {
// check token exists
require(tokenExists(_tokenId));
// make sure previous owner is correct
require(tokens[_tokenId].owner == _from);
require(_to != address(0));
require(_to != address(this));
// pay any unpaid payouts to previous owner of token
updateSinglePayout(_from, _tokenId);
// clear approvals linked to this token
clearApproval(_from, _tokenId);
// remove token from previous owner
removeToken(_from, _tokenId);
// update owner and add token to new owner
tokens[_tokenId].owner = _to;
addToken(_to, _tokenId);
//raise event
Transfer(_from, _to, _tokenId);
}
/**
* @dev Withdraw dev's cut
*/
function withdraw() onlyOwner public {
owner.transfer(devOwed);
devOwed = 0;
}
/**
* @dev Updates the payout for the token the owner has
* @param _owner address of token owner
*/
function updatePayout(address _owner) public {
uint256[] memory ownerTokens = ownedTokens[_owner];
uint256 owed;
for (uint256 i = 0; i < ownerTokens.length; i++) {
uint256 totalOwed;
if (tokens[ownerTokens[i]].kind == CITY) {
totalOwed = cityPoolTotal * tokens[ownerTokens[i]].payout / 10000;
} else if (tokens[ownerTokens[i]].kind == LANDMARK) {
totalOwed = landmarkPoolTotal * tokens[ownerTokens[i]].payout / 10000;
} else if (tokens[ownerTokens[i]].kind == OTHER) {
totalOwed = otherPoolTotal * tokens[ownerTokens[i]].payout / 10000;
}
uint256 totalTokenOwed = totalOwed.sub(tokens[ownerTokens[i]].withdrawn);
owed += totalTokenOwed;
tokens[ownerTokens[i]].withdrawn += totalTokenOwed;
}
payoutBalances[_owner] += owed;
}
function priceOf(uint256 _tokenId) public view returns (uint256) {
return tokens[_tokenId].price;
}
/**
* @dev Update a single toekn payout for transfers.
* @param _owner Address of the owner of the token.
* @param _tokenId Unique Id of the token.
**/
function updateSinglePayout(address _owner, uint256 _tokenId) internal {
uint256 totalOwed;
if (tokens[_tokenId].kind == CITY) {
totalOwed = cityPoolTotal * tokens[_tokenId].payout / 10000;
} else if (tokens[_tokenId].kind == LANDMARK) {
totalOwed = landmarkPoolTotal * tokens[_tokenId].payout / 10000;
} else if (tokens[_tokenId].kind == OTHER) {
totalOwed = otherPoolTotal * tokens[_tokenId].payout / 10000;
}
uint256 totalTokenOwed = totalOwed.sub(tokens[_tokenId].withdrawn);
tokens[_tokenId].withdrawn += totalTokenOwed;
payoutBalances[_owner] += totalTokenOwed;
}
/**
* @dev Owner can withdraw their accumulated payouts
* @param _owner address of token owner
*/
function withdrawRent(address _owner) public {
require(_owner != address(0));
updatePayout(_owner);
uint256 payout = payoutBalances[_owner];
payoutBalances[_owner] = 0;
_owner.transfer(payout);
}
function getRentOwed(address _owner) public view returns (uint256 owed) {
require(_owner != address(0));
updatePayout(_owner);
return payoutBalances[_owner];
}
/**
* @dev Return all token data
* @param _tokenId uint256 of token
*/
function getToken (uint256 _tokenId) external view
returns (address _owner, uint256 _price, uint256 _lastPrice, uint256 _nextPrice, uint256 _payout, uint8 _kind, uint256 _mayorTokenId, address[5] _previosOwners)
{
Token memory token = tokens[_tokenId];
return (token.owner, token.price, token.lastPrice, getNextPrice(token.price), token.payout, token.kind, token.mayorTokenId, token.previousOwners);
}
/**
* @dev Determines if token exists by checking it's price
* @param _tokenId uint256 ID of token
*/
function tokenExists (uint256 _tokenId) public view returns (bool _exists) {
return tokens[_tokenId].price > 0;
}
/**
* @dev Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/**
* @dev Guarantees msg.sender is not a contract
* @param _buyer address of person buying token
*/
modifier isNotContract(address _buyer) {
uint size;
assembly { size := extcodesize(_buyer) }
require(size == 0);
_;
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return totalTokens;
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
return ownedTokens[_owner].length;
}
/**
* @dev Gets the list of tokens owned by a given address
* @param _owner address to query the tokens of
* @return uint256[] representing the list of tokens owned by the passed address
*/
function tokensOf(address _owner) public view returns (uint256[]) {
return ownedTokens[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Gets the approved address to take ownership of a given token ID
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved to take ownership of the given token ID
*/
function approvedFor(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) {
clearApprovalAndTransfer(msg.sender, _to, _tokenId);
}
/**
* @dev Approves another address to claim for the ownership of the given token ID
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) {
address owner = ownerOf(_tokenId);
require(_to != owner);
if (approvedFor(_tokenId) != 0 || _to != 0) {
tokenApprovals[_tokenId] = _to;
Approval(owner, _to, _tokenId);
}
}
/**
* @dev Claims the ownership of a given token ID
* @param _tokenId uint256 ID of the token being claimed by the msg.sender
*/
function takeOwnership(uint256 _tokenId) public {
require(isApprovedFor(msg.sender, _tokenId));
clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId);
}
/**
* @dev Tells whether the msg.sender is approved for the given token ID or not
* This function is not private so it can be extended in further implementations like the operatable ERC721
* @param _owner address of the owner to query the approval of
* @param _tokenId uint256 ID of the token to query the approval of
* @return bool whether the msg.sender is approved for the given token ID or not
*/
function isApprovedFor(address _owner, uint256 _tokenId) internal view returns (bool) {
return approvedFor(_tokenId) == _owner;
}
/**
* @dev Internal function to clear current approval and transfer the ownership of a given token ID
* @param _from address which you want to send tokens from
* @param _to address which you want to transfer the token to
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal isNotContract(_to) {
require(_to != address(0));
require(_to != ownerOf(_tokenId));
require(ownerOf(_tokenId) == _from);
clearApproval(_from, _tokenId);
updateSinglePayout(_from, _tokenId);
removeToken(_from, _tokenId);
addToken(_to, _tokenId);
Transfer(_from, _to, _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) private {
require(ownerOf(_tokenId) == _owner);
tokenApprovals[_tokenId] = 0;
Approval(_owner, 0, _tokenId);
}
/**
* @dev Mint token function
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addToken(_to, _tokenId);
Transfer(0x0, _to, _tokenId);
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addToken(address _to, uint256 _tokenId) private {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
tokens[_tokenId].owner = _to;
uint256 length = balanceOf(_to);
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
totalTokens = totalTokens.add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeToken(address _from, uint256 _tokenId) private {
require(ownerOf(_tokenId) == _from);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = balanceOf(_from).sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
tokenOwner[_tokenId] = 0;
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
totalTokens = totalTokens.sub(1);
}
function name() public pure returns (string _name) {
return "CryptoMayor.io";
}
function symbol() public pure returns (string _symbol) {
return "CMC";
}
function setFeePercentage(uint256 _newFee) onlyOwner public {
require(_newFee <= 5);
require(_newFee >= 3);
feePercentage = _newFee;
}
function setMainPoolCutPercentage(uint256 _newFee) onlyOwner public {
require(_newFee <= 30);
require(_newFee >= 5);
cityPoolCutPercentage = _newFee;
}
function setDividendCutPercentage(uint256 _newFee) onlyOwner public {
require(_newFee <= 200);
require(_newFee >= 50);
dividendCutPercentage = _newFee;
}
// Migration
OldContract oldContract;
function setOldContract(address _addr) onlyOwner public {
oldContract = OldContract(_addr);
}
function populateFromOldContract(uint256[] _ids) onlyOwner public {
for (uint256 i = 0; i < _ids.length; i++) {
// Can't rewrite tokens
if (tokens[_ids[i]].price == 0) {
address _owner;
uint256 _price;
uint256 _lastPrice;
uint256 _nextPrice;
uint256 _payout;
uint8 _kind;
uint256 _mayorTokenId;
(_owner, _price, _lastPrice, _nextPrice, _payout, _kind, _mayorTokenId) = oldContract.getToken(_ids[i]);
createToken(_ids[i], _price, _lastPrice, _payout, _kind, _mayorTokenId, _owner);
}
}
}
}
interface OldContract {
function getToken (uint256 _tokenId) external view
returns (address _owner, uint256 _price, uint256 _lastPrice, uint256 _nextPrice, uint256 _payout, uint8 _kind, uint256 _mayorTokenId);
} | * @dev Update a single toekn payout for transfers. @param _owner Address of the owner of the token. @param _tokenId Unique Id of the token./ | function updateSinglePayout(address _owner, uint256 _tokenId) internal {
uint256 totalOwed;
if (tokens[_tokenId].kind == CITY) {
totalOwed = cityPoolTotal * tokens[_tokenId].payout / 10000;
totalOwed = landmarkPoolTotal * tokens[_tokenId].payout / 10000;
totalOwed = otherPoolTotal * tokens[_tokenId].payout / 10000;
}
uint256 totalTokenOwed = totalOwed.sub(tokens[_tokenId].withdrawn);
tokens[_tokenId].withdrawn += totalTokenOwed;
payoutBalances[_owner] += totalTokenOwed;
}
| 6,707,187 | [
1,
1891,
279,
2202,
358,
3839,
82,
293,
2012,
364,
29375,
18,
225,
389,
8443,
5267,
434,
326,
3410,
434,
326,
1147,
18,
225,
389,
2316,
548,
14584,
3124,
434,
326,
1147,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
1089,
5281,
52,
2012,
12,
2867,
389,
8443,
16,
2254,
5034,
389,
2316,
548,
13,
2713,
288,
203,
565,
2254,
5034,
2078,
3494,
329,
31,
203,
540,
203,
565,
309,
261,
7860,
63,
67,
2316,
548,
8009,
9224,
422,
385,
4107,
13,
288,
203,
1377,
2078,
3494,
329,
273,
12797,
2864,
5269,
380,
2430,
63,
67,
2316,
548,
8009,
84,
2012,
342,
12619,
31,
203,
1377,
2078,
3494,
329,
273,
19193,
3355,
2864,
5269,
380,
2430,
63,
67,
2316,
548,
8009,
84,
2012,
342,
12619,
31,
203,
1377,
2078,
3494,
329,
273,
1308,
2864,
5269,
380,
2430,
63,
67,
2316,
548,
8009,
84,
2012,
342,
12619,
31,
203,
565,
289,
203,
203,
565,
2254,
5034,
2078,
1345,
3494,
329,
273,
2078,
3494,
329,
18,
1717,
12,
7860,
63,
67,
2316,
548,
8009,
1918,
9446,
82,
1769,
203,
540,
203,
565,
2430,
63,
67,
2316,
548,
8009,
1918,
9446,
82,
1011,
2078,
1345,
3494,
329,
31,
203,
565,
293,
2012,
38,
26488,
63,
67,
8443,
65,
1011,
2078,
1345,
3494,
329,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
contract ERC20Token{
//ERC20 base standard
uint256 public totalSupply;
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
// From https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable{
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// Put the additional safe module here, safe math and pausable
// From https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/lifecycle/Pausable.sol
// And https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol
contract Safe is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
// Check if it is safe to add two numbers
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint c = a + b;
assert(c >= a && c >= b);
return c;
}
// Check if it is safe to subtract two numbers
function safeSubtract(uint256 a, uint256 b) internal pure returns (uint256) {
uint c = a - b;
assert(b <= a && c <= a);
return c;
}
// Check if it is safe to multiply two numbers
function safeMultiply(uint256 a, uint256 b) internal pure returns (uint256) {
uint c = a * b;
assert(a == 0 || (c / a) == b);
return c;
}
// reject any ether
function () public payable {
require(msg.value == 0);
}
}
// Adapted from zeppelin-solidity's BasicToken, StandardToken and BurnableToken contracts
// https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20/BasicToken.sol
// https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20/StandardToken.sol
// https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20/BurnableToken.sol
contract imaxChainToken is Safe, ERC20Token {
string public constant name = 'Inverstment Management Asset Exchange'; // Set the token name for display
string public constant symbol = 'IMAX'; // Set the token symbol for display
uint8 public constant decimals = 18; // Set the number of decimals for display
uint256 public constant INITIAL_SUPPLY = 1e9 * 10**uint256(decimals);
uint256 public totalSupply;
string public version = '1';
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
mapping (address => uint256) freeze;
event Burn(address indexed burner, uint256 value);
modifier whenNotFreeze() {
require(freeze[msg.sender]==0);
_;
}
function imaxChainToken() public {
totalSupply = INITIAL_SUPPLY; // Set the total supply
balances[msg.sender] = INITIAL_SUPPLY; // Creator address is assigned all
Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
function transfer(address _to, uint256 _value) whenNotPaused whenNotFreeze public returns (bool success) {
require(_to != address(this));
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = safeSubtract(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) whenNotPaused whenNotFreeze public returns (bool success) {
require(_to != address(this));
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = safeSubtract(balances[_from],_value);
balances[_to] = safeAdd(balances[_to],_value);
allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) whenNotFreeze public returns (bool success) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) whenNotFreeze public returns (bool) {
allowed[msg.sender][_spender] = safeAdd(allowed[msg.sender][_spender],_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) whenNotFreeze public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = safeSubtract(oldValue,_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function updateFreeze(address account) onlyOwner public returns(bool success){
if (freeze[account]==0){
freeze[account]=1;
}else{
freeze[account]=0;
}
return true;
}
function freezeOf(address account) public view returns (uint256 status) {
return freeze[account];
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = safeSubtract(balances[burner],_value);
totalSupply = safeSubtract(totalSupply, _value);
Burn(burner, _value);
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { revert(); }
return true;
}
} | Set the token symbol for display
| string public constant symbol = 'IMAX'; | 5,936,304 | [
1,
694,
326,
1147,
3273,
364,
2562,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
533,
1071,
5381,
3273,
273,
296,
3445,
2501,
13506,
4766,
282,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "openzeppelin-solidity/contracts/access/Roles.sol";
// import '../../node_modules/@openzeppelin/contracts/access/Ownable.sol';
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import './CallerContractInterface.sol';
contract EthPriceOracle is Roles { // is Ownable deleted
using Roles for Roles.Role;
Roles.Role private owners;
Roles.Role private oracles;
uint256 private randNonce = 0;
uint256 private modulus = 1000;
uint private numOracles = 0;
uint private THRESHOLD = 0;
mapping(uint256 => bool) pendingRequests;
struct Response {
address oracleAddress;
address callerAddress;
uint256 ethPrice;
}
mapping (uint256=>Response[]) public requestIdToResponse;
event GetLatestEthPriceEvent(address callerAddress, uint256 id);
event SetLatestEthPriceEvent(uint256 ethPrice, address callerAddress);
event AddOracleEvent(address oracleAddress);
event RemoveOracleEvent(address oracleAddress);
constructor (address _owner) public {
owners.add(_owner);
}
function addOracle (address _oracle) public {
require(owners.has(msg.sender), "Not an owner!");
require(!oracles.has(_oracle), "Already an oracle!");
oracles.add(_oracle);
numOracles++;
emit AddOracleEvent(_oracle);
}
function removeOracle (address _oracle) public {
require(owners.has(msg.sender), "Not an owner!");
require(oracles.has(_oracle), "Not an oracle!");
require(numOracles > 1, "Do not remove the last oracle!");
oracles.remove(_oracle);
numOracles--;
emit RemoveOracleEvent(_oracle);
}
function getLatestEthPrice() public returns (uint256) {
randNonce++;
uint256 id = uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender, randNonce))) % modulus;
pendingRequests[id] = true;
emit GetLatestEthPriceEvent(msg.sender, id);
return id;
}
function setLatestEthPrice(
uint256 _ethPrice,
address _callerAddress,
uint256 _id
) public { // onlyOwner removed
require(oracles.has(msg.sender), "Not an oracle!");
require(pendingRequests[_id], 'This request is not in my pending list.');
Response memory resp;
resp = Response(msg.sender, _callerAddress, _ethPrice);
requestIdToResponse[_id].push(resp);
uint numResponses = requestIdToResponse[_id].length;
if (numResponses == THRESHOLD) {
uint computedEthPrice = 0;
for (uint f=0; f < requestIdToResponse[_id].length; f++) {
computedEthPrice = computedEthPrice.add(requestIdToResponse[_id][f].ethPrice);
}
computedEthPrice = computedEthPrice.div(numResponses);
delete pendingRequests[_id];
delete requestIdToResponse[_id];
CallerContractInterface callerContractInstance;
callerContractInstance = CallerContractInterface(_callerAddress);
callerContractInstance.callback(computedEthPrice, _id);
emit SetLatestEthPriceEvent(computedEthPrice, _callerAddress);
}
}
}
| is Ownable deleted
| contract EthPriceOracle is Roles { | 2,544,927 | [
1,
291,
14223,
6914,
4282,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
512,
451,
5147,
23601,
353,
19576,
288,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xaBCce6b19154F60091D458d3A23EF5aaF0B2BAf2/sources/Tsukiko.sol | Buy FeeSell FeeOriginal Fee | contract Tsukiko is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "Tsukiko ";
string private constant _symbol = "$KIKO";
uint8 private constant _decimals = 9;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _feeOnBuy = 0;
uint256 private _taxOnBuy = 10;
uint256 private _feeOnSell = 0;
uint256 private _taxOnSell = 40;
uint256 public totalFees;
uint256 private _redisFee = _feeOnSell;
uint256 private _taxFee = _taxOnSell;
uint256 private _previousredisFee = _redisFee;
uint256 private _previoustaxFee = _taxFee;
mapping(address => uint256) private cooldown;
address payable private _developmentWalletAddress = payable(0xb140B347F508E6aDEaD32Cca4A7ec5109E58f652);
address payable private _marketingWalletAddress = payable(0xb140B347F508E6aDEaD32Cca4A7ec5109E58f652);
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = true;
uint256 public _maxTxAmount = 20000000 * 10**9;
uint256 public _maxWalletSize = 20000000 * 10**9;
uint256 public _swapTokensAtAmount = 10000 * 10**9;
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_developmentWalletAddress] = true;
_isExcludedFromFee[_marketingWalletAddress] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
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;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function tokenFromReflection(uint256 rAmount)
private
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function removeAllFee() private {
if (_redisFee == 0 && _taxFee == 0) return;
_previousredisFee = _redisFee;
_previoustaxFee = _taxFee;
_redisFee = 0;
_taxFee = 0;
}
function restoreAllFee() private {
_redisFee = _previousredisFee;
_taxFee = _previoustaxFee;
}
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");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _feeOnBuy;
_taxFee = _taxOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _feeOnSell;
_taxFee = _taxOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
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");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _feeOnBuy;
_taxFee = _taxOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _feeOnSell;
_taxFee = _taxOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
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");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _feeOnBuy;
_taxFee = _taxOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _feeOnSell;
_taxFee = _taxOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
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");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _feeOnBuy;
_taxFee = _taxOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _feeOnSell;
_taxFee = _taxOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
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");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _feeOnBuy;
_taxFee = _taxOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _feeOnSell;
_taxFee = _taxOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
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");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _feeOnBuy;
_taxFee = _taxOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _feeOnSell;
_taxFee = _taxOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
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");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _feeOnBuy;
_taxFee = _taxOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _feeOnSell;
_taxFee = _taxOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
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");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _feeOnBuy;
_taxFee = _taxOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _feeOnSell;
_taxFee = _taxOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
} else {
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");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _feeOnBuy;
_taxFee = _taxOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _feeOnSell;
_taxFee = _taxOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
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");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _feeOnBuy;
_taxFee = _taxOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _feeOnSell;
_taxFee = _taxOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_developmentWalletAddress.transfer(amount.div(2));
_marketingWalletAddress.transfer(amount.div(2));
}
function setTrading(bool _tradingOpen) public onlyOwner {
tradingOpen = _tradingOpen;
}
function manualswap() external {
require(_msgSender() == _developmentWalletAddress || _msgSender() == _marketingWalletAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _developmentWalletAddress || _msgSender() == _marketingWalletAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _redisFee, _taxFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(
uint256 tAmount,
uint256 redisFee,
uint256 taxFee
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(redisFee).div(100);
uint256 tTeam = tAmount.mul(taxFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tTeam,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner {
_feeOnBuy = redisFeeOnBuy;
_feeOnSell = redisFeeOnSell;
_taxOnBuy = taxFeeOnBuy;
_taxOnSell = taxFeeOnSell;
totalFees = _feeOnBuy + _feeOnSell + _taxOnBuy + _taxOnSell;
require(totalFees <= 100, "Must keep fees at 100% or less");
}
function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner {
_swapTokensAtAmount = swapTokensAtAmount;
}
function toggleSwap(bool _swapEnabled) public onlyOwner {
swapEnabled = _swapEnabled;
}
function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner {
_maxTxAmount = maxTxAmount;
}
function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner {
_maxWalletSize = maxWalletSize;
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFee[accounts[i]] = excluded;
}
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFee[accounts[i]] = excluded;
}
}
} | 3,688,721 | [
1,
38,
9835,
30174,
55,
1165,
30174,
8176,
30174,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
24709,
19445,
27113,
353,
1772,
16,
467,
654,
39,
3462,
16,
14223,
6914,
288,
203,
7010,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
7010,
565,
533,
3238,
5381,
389,
529,
273,
315,
17218,
19445,
27113,
13636,
7010,
565,
533,
3238,
5381,
389,
7175,
273,
4662,
47,
45,
47,
51,
14432,
7010,
565,
2254,
28,
3238,
5381,
389,
31734,
273,
2468,
31,
203,
7010,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
86,
5460,
329,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
88,
5460,
329,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
1265,
14667,
31,
203,
565,
2254,
5034,
3238,
5381,
4552,
273,
4871,
11890,
5034,
12,
20,
1769,
203,
203,
565,
2254,
5034,
3238,
5381,
389,
88,
5269,
273,
15088,
3784,
380,
1728,
636,
29,
31,
7010,
565,
2254,
5034,
3238,
389,
86,
5269,
273,
261,
6694,
300,
261,
6694,
738,
389,
88,
5269,
10019,
203,
565,
2254,
5034,
3238,
389,
88,
14667,
5269,
31,
203,
7010,
565,
2254,
5034,
3238,
389,
21386,
1398,
38,
9835,
273,
374,
31,
21281,
565,
2254,
5034,
3238,
389,
8066,
1398,
38,
9835,
273,
1728,
31,
27699,
7010,
565,
2254,
5034,
3238,
389,
21386,
1398,
55,
1165,
273,
374,
31,
7010,
565,
2254,
5034,
3238,
389,
8066,
1398,
55,
1165,
273,
8063,
31,
21281,
203,
565,
2254,
5034,
1071,
2078,
2954,
281,
31,
203,
2
] |
./full_match/43114/0x0Db20d1643112fA00C4D3DDB58369Ad26c1F7c1d/sources/contracts/Strategy.sol | Internal, sets the tranche token and checks that it's supported | function _setAndCheckTrancheToken(uint256 trancheId, address token)
internal
virtual
{
require(_approvedTokens.contains(token), "Not an approved token");
_accounts[trancheId].trancheToken = token;
}
| 4,499,923 | [
1,
3061,
16,
1678,
326,
13637,
18706,
1147,
471,
4271,
716,
518,
1807,
3260,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
542,
31151,
17730,
18706,
1345,
12,
11890,
5034,
13637,
18706,
548,
16,
1758,
1147,
13,
203,
3639,
2713,
203,
3639,
5024,
203,
565,
288,
203,
3639,
2583,
24899,
25990,
5157,
18,
12298,
12,
2316,
3631,
315,
1248,
392,
20412,
1147,
8863,
203,
3639,
389,
13739,
63,
13171,
18706,
548,
8009,
13171,
18706,
1345,
273,
1147,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.24;
/*
* @author Ivan Borisov ([email protected]) (Github.com/pillardevelopment)
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
interface ERC20 {
function transfer (address _beneficiary, uint256 _tokenAmount) external returns (bool);
function transferFromICO(address _to, uint256 _value) external returns(bool);
function balanceOf(address who) external view returns (uint256);
}
contract Ownable {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
}
/*********************************************************************************************************************
* @dev see https://github.com/ethereum/EIPs/issues/20 */
/*************************************************************************************************************/
contract WhalesburgCrowdsale is Ownable {
using SafeMath for uint256;
ERC20 public token;
address public constant multisig = 0x5ac618ca87b61c1434325b6d60141c90f32590df;
address constant bounty = 0x5ac618ca87b61c1434325b6d60141c90f32590df;
address constant privateInvestors = 0x5ac618ca87b61c1434325b6d60141c90f32590df;
address developers = 0xd7dadf6149FF75f76f36423CAD1E24c81847E85d;
address constant founders = 0xd7dadf6149FF75f76f36423CAD1E24c81847E85d;
uint256 public startICO = 1527989629; // Sunday, 03-Jun-18 16:00:00 UTC
uint256 public endICO = 1530633600; // Tuesday, 03-Jul-18 16:00:00 UTC
uint256 constant privateSaleTokens = 46988857;
uint256 constant foundersReserve = 10000000;
uint256 constant developmentReserve = 20500000;
uint256 constant bountyReserve = 3500000;
uint256 public individualRoundCap = 1250000000000000000;
uint256 public constant hardCap = 1365000067400000000000; // 1365.0000674 ether
uint256 public investors;
uint256 public membersWhiteList;
uint256 public constant buyPrice = 71800000000000; // 0.0000718 Ether
bool public isFinalized = false;
bool public distribute = false;
uint256 public weisRaised;
mapping (address => bool) public onChain;
mapping (address => bool) whitelist;
mapping (address => uint256) public moneySpent;
address[] tokenHolders;
event Finalized();
event Authorized(address wlCandidate, uint256 timestamp);
event Revoked(address wlCandidate, uint256 timestamp);
constructor(ERC20 _token) public {
require(_token != address(0));
token = _token;
}
function setVestingAddress(address _newDevPool) public onlyOwner {
developers = _newDevPool;
}
function distributionTokens() public onlyOwner {
require(!distribute);
token.transferFromICO(bounty, bountyReserve*1e18);
token.transferFromICO(privateInvestors, privateSaleTokens*1e18);
token.transferFromICO(developers, developmentReserve*1e18);
token.transferFromICO(founders, foundersReserve*1e18);
distribute = true;
}
/******************-- WhiteList --***************************/
function authorize(address _beneficiary) public onlyOwner {
require(_beneficiary != address(0x0));
require(!isWhitelisted(_beneficiary));
whitelist[_beneficiary] = true;
membersWhiteList++;
emit Authorized(_beneficiary, now);
}
function addManyAuthorizeToWhitelist(address[] _beneficiaries) public onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
authorize(_beneficiaries[i]);
}
}
function revoke(address _beneficiary) public onlyOwner {
whitelist[_beneficiary] = false;
emit Revoked(_beneficiary, now);
}
function isWhitelisted(address who) public view returns(bool) {
return whitelist[who];
}
function finalize() onlyOwner public {
require(!isFinalized);
require(now >= endICO || weisRaised >= hardCap);
emit Finalized();
isFinalized = true;
token.transferFromICO(owner, token.balanceOf(this));
}
/***************************--Payable --*********************************************/
function () public payable {
if(isWhitelisted(msg.sender)) {
require(now >= startICO && now < endICO);
currentSaleLimit();
moneySpent[msg.sender] = moneySpent[msg.sender].add(msg.value);
require(moneySpent[msg.sender] <= individualRoundCap);
sell(msg.sender, msg.value);
weisRaised = weisRaised.add(msg.value);
require(weisRaised <= hardCap);
multisig.transfer(msg.value);
} else {
revert();
}
}
function currentSaleLimit() private {
if(now >= startICO && now < startICO+7200) {
individualRoundCap = 1250000000000000000; // 1.25 ETH
}
else if(now >= startICO+7200 && now < startICO+14400) {
individualRoundCap = 3750000000000000000; // 3.75 ETH
}
else if(now >= startICO+14400 && now < endICO) {
individualRoundCap = hardCap; // 1365 ether
}
else {
revert();
}
}
function sell(address _investor, uint256 amount) private {
uint256 _amount = amount.mul(1e18).div(buyPrice);
token.transferFromICO(_investor, _amount);
if (!onChain[msg.sender]) {
tokenHolders.push(msg.sender);
onChain[msg.sender] = true;
}
investors = tokenHolders.length;
}
} | ********************************************************************************************************************************************************************************************************************************/ | contract WhalesburgCrowdsale is Ownable {
using SafeMath for uint256;
ERC20 public token;
address public constant multisig = 0x5ac618ca87b61c1434325b6d60141c90f32590df;
address constant bounty = 0x5ac618ca87b61c1434325b6d60141c90f32590df;
address constant privateInvestors = 0x5ac618ca87b61c1434325b6d60141c90f32590df;
address developers = 0xd7dadf6149FF75f76f36423CAD1E24c81847E85d;
address constant founders = 0xd7dadf6149FF75f76f36423CAD1E24c81847E85d;
uint256 constant privateSaleTokens = 46988857;
uint256 constant foundersReserve = 10000000;
uint256 constant developmentReserve = 20500000;
uint256 constant bountyReserve = 3500000;
uint256 public individualRoundCap = 1250000000000000000;
uint256 public investors;
uint256 public membersWhiteList;
bool public isFinalized = false;
bool public distribute = false;
uint256 public weisRaised;
mapping (address => bool) public onChain;
mapping (address => bool) whitelist;
mapping (address => uint256) public moneySpent;
address[] tokenHolders;
event Finalized();
event Authorized(address wlCandidate, uint256 timestamp);
event Revoked(address wlCandidate, uint256 timestamp);
constructor(ERC20 _token) public {
require(_token != address(0));
token = _token;
}
function setVestingAddress(address _newDevPool) public onlyOwner {
developers = _newDevPool;
}
function distributionTokens() public onlyOwner {
require(!distribute);
token.transferFromICO(bounty, bountyReserve*1e18);
token.transferFromICO(privateInvestors, privateSaleTokens*1e18);
token.transferFromICO(developers, developmentReserve*1e18);
token.transferFromICO(founders, foundersReserve*1e18);
distribute = true;
}
function authorize(address _beneficiary) public onlyOwner {
require(_beneficiary != address(0x0));
require(!isWhitelisted(_beneficiary));
whitelist[_beneficiary] = true;
membersWhiteList++;
emit Authorized(_beneficiary, now);
}
function addManyAuthorizeToWhitelist(address[] _beneficiaries) public onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
authorize(_beneficiaries[i]);
}
}
function addManyAuthorizeToWhitelist(address[] _beneficiaries) public onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
authorize(_beneficiaries[i]);
}
}
function revoke(address _beneficiary) public onlyOwner {
whitelist[_beneficiary] = false;
emit Revoked(_beneficiary, now);
}
function isWhitelisted(address who) public view returns(bool) {
return whitelist[who];
}
function finalize() onlyOwner public {
require(!isFinalized);
require(now >= endICO || weisRaised >= hardCap);
emit Finalized();
isFinalized = true;
token.transferFromICO(owner, token.balanceOf(this));
}
function () public payable {
if(isWhitelisted(msg.sender)) {
require(now >= startICO && now < endICO);
currentSaleLimit();
moneySpent[msg.sender] = moneySpent[msg.sender].add(msg.value);
require(moneySpent[msg.sender] <= individualRoundCap);
sell(msg.sender, msg.value);
weisRaised = weisRaised.add(msg.value);
require(weisRaised <= hardCap);
multisig.transfer(msg.value);
revert();
}
}
function () public payable {
if(isWhitelisted(msg.sender)) {
require(now >= startICO && now < endICO);
currentSaleLimit();
moneySpent[msg.sender] = moneySpent[msg.sender].add(msg.value);
require(moneySpent[msg.sender] <= individualRoundCap);
sell(msg.sender, msg.value);
weisRaised = weisRaised.add(msg.value);
require(weisRaised <= hardCap);
multisig.transfer(msg.value);
revert();
}
}
} else {
function currentSaleLimit() private {
if(now >= startICO && now < startICO+7200) {
}
else if(now >= startICO+7200 && now < startICO+14400) {
}
else if(now >= startICO+14400 && now < endICO) {
}
else {
revert();
}
}
function currentSaleLimit() private {
if(now >= startICO && now < startICO+7200) {
}
else if(now >= startICO+7200 && now < startICO+14400) {
}
else if(now >= startICO+14400 && now < endICO) {
}
else {
revert();
}
}
function currentSaleLimit() private {
if(now >= startICO && now < startICO+7200) {
}
else if(now >= startICO+7200 && now < startICO+14400) {
}
else if(now >= startICO+14400 && now < endICO) {
}
else {
revert();
}
}
function currentSaleLimit() private {
if(now >= startICO && now < startICO+7200) {
}
else if(now >= startICO+7200 && now < startICO+14400) {
}
else if(now >= startICO+14400 && now < endICO) {
}
else {
revert();
}
}
function currentSaleLimit() private {
if(now >= startICO && now < startICO+7200) {
}
else if(now >= startICO+7200 && now < startICO+14400) {
}
else if(now >= startICO+14400 && now < endICO) {
}
else {
revert();
}
}
function sell(address _investor, uint256 amount) private {
uint256 _amount = amount.mul(1e18).div(buyPrice);
token.transferFromICO(_investor, _amount);
if (!onChain[msg.sender]) {
tokenHolders.push(msg.sender);
onChain[msg.sender] = true;
}
investors = tokenHolders.length;
}
function sell(address _investor, uint256 amount) private {
uint256 _amount = amount.mul(1e18).div(buyPrice);
token.transferFromICO(_investor, _amount);
if (!onChain[msg.sender]) {
tokenHolders.push(msg.sender);
onChain[msg.sender] = true;
}
investors = tokenHolders.length;
}
} | 10,727,159 | [
1,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
3497,
5408,
70,
295,
75,
39,
492,
2377,
5349,
353,
14223,
6914,
288,
203,
202,
9940,
14060,
10477,
364,
2254,
5034,
31,
203,
202,
203,
202,
654,
39,
3462,
1071,
1147,
31,
203,
202,
203,
202,
2867,
1071,
5381,
22945,
360,
273,
374,
92,
25,
1077,
26,
2643,
5353,
11035,
70,
9498,
71,
3461,
5026,
1578,
25,
70,
26,
72,
26,
1611,
9803,
71,
9349,
74,
1578,
6162,
20,
2180,
31,
203,
202,
2867,
5381,
324,
592,
93,
273,
374,
92,
25,
1077,
26,
2643,
5353,
11035,
70,
9498,
71,
3461,
5026,
1578,
25,
70,
26,
72,
26,
1611,
9803,
71,
9349,
74,
1578,
6162,
20,
2180,
31,
203,
202,
2867,
5381,
3238,
3605,
395,
1383,
273,
374,
92,
25,
1077,
26,
2643,
5353,
11035,
70,
9498,
71,
3461,
5026,
1578,
25,
70,
26,
72,
26,
1611,
9803,
71,
9349,
74,
1578,
6162,
20,
2180,
31,
203,
202,
2867,
21701,
273,
374,
7669,
27,
72,
361,
74,
26,
26262,
2246,
5877,
74,
6669,
74,
23,
1105,
4366,
39,
1880,
21,
41,
3247,
71,
28,
2643,
9462,
41,
7140,
72,
31,
203,
202,
2867,
5381,
1392,
414,
273,
374,
7669,
27,
72,
361,
74,
26,
26262,
2246,
5877,
74,
6669,
74,
23,
1105,
4366,
39,
1880,
21,
41,
3247,
71,
28,
2643,
9462,
41,
7140,
72,
31,
203,
202,
203,
203,
202,
11890,
5034,
5381,
3238,
30746,
5157,
273,
1059,
8148,
5482,
7140,
27,
31,
203,
202,
11890,
5034,
5381,
1392,
414,
607,
6527,
273,
2130,
11706,
31,
203,
202,
11890,
5034,
5381,
17772,
2
] |
./full_match/8453/0x266c8f8cdA4360506b8D32Dc5C4102350a069aCD/sources/project_/contracts/Max-20-UUPS-LZ.sol | @dev This declines the push-pull method of onlyDev() | function declineDeveloper()
external
onlyRole(PENDING_DEVS) {
contractRoles.remove(PENDING_DEVS, msg.sender);
}
| 11,561,658 | [
1,
2503,
3496,
1465,
326,
1817,
17,
13469,
707,
434,
1338,
8870,
1435,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
3496,
558,
28145,
1435,
203,
565,
3903,
203,
565,
1338,
2996,
12,
25691,
67,
1639,
14640,
13,
288,
203,
565,
6835,
6898,
18,
4479,
12,
25691,
67,
1639,
14640,
16,
1234,
18,
15330,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x499afBC7aE808e51e48A29FD30e80DfC5B1F2e56/sources/contracts/ajna/interfaces/rewards/IRewardsManagerState.sol | * @title Rewards Manager State/ | interface IRewardsManagerState {
function isBucketUpdated(
address pool_,
uint256 bucketIndex_,
uint256 epoch_
) external view returns (bool);
function isEpochClaimed(
uint256 tokenId_,
uint256 epoch_
) external view returns (bool);
function rewardsClaimed(
uint256 epoch_
) external view returns (uint256);
function updateRewardsClaimed(
uint256 epoch_
) external view returns (uint256);
function getStakeInfo(
uint256 tokenId_
) external view returns (address owner_, address pool_, uint256 lastClaimedEpoch_);
function getBucketStateStakeInfo(
uint256 tokenId_,
uint256 bucketId_
) external view returns (uint256, uint256);
}
| 9,342,878 | [
1,
17631,
14727,
8558,
3287,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
15908,
359,
14727,
1318,
1119,
288,
203,
203,
565,
445,
353,
4103,
7381,
12,
203,
3639,
1758,
2845,
67,
16,
203,
3639,
2254,
5034,
2783,
1016,
67,
16,
203,
3639,
2254,
5034,
7632,
67,
203,
565,
262,
3903,
1476,
1135,
261,
6430,
1769,
203,
203,
565,
445,
353,
14638,
9762,
329,
12,
203,
3639,
2254,
5034,
1147,
548,
67,
16,
203,
3639,
2254,
5034,
7632,
67,
203,
565,
262,
3903,
1476,
1135,
261,
6430,
1769,
203,
203,
565,
445,
283,
6397,
9762,
329,
12,
203,
3639,
2254,
5034,
7632,
67,
203,
565,
262,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
1089,
17631,
14727,
9762,
329,
12,
203,
3639,
2254,
5034,
7632,
67,
203,
565,
262,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
21491,
911,
966,
12,
203,
3639,
2254,
5034,
1147,
548,
67,
203,
565,
262,
3903,
1476,
1135,
261,
2867,
3410,
67,
16,
1758,
2845,
67,
16,
2254,
5034,
1142,
9762,
329,
14638,
67,
1769,
203,
203,
565,
445,
22862,
1119,
510,
911,
966,
12,
203,
3639,
2254,
5034,
1147,
548,
67,
16,
203,
3639,
2254,
5034,
2783,
548,
67,
203,
565,
262,
3903,
1476,
1135,
261,
11890,
5034,
16,
2254,
5034,
1769,
203,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.2;
/*
*
* This file is part of Pass DAO.
*
* The Token Manager smart contract is used for the management of tokens
* by a client smart contract (the Dao). Defines the functions to set new funding rules,
* create or reward tokens, check token balances, send tokens and send
* tokens on behalf of a 3rd party and the corresponding approval process.
*
*/
/// @title Token Manager smart contract of the Pass Decentralized Autonomous Organisation
contract PassTokenManagerInterface {
struct fundingData {
// True if public funding without a main partner
bool publicCreation;
// The address which sets partners and manages the funding in case of private funding
address mainPartner;
// The maximum amount (in wei) of the funding
uint maxAmountToFund;
// The actual funded amount (in wei)
uint fundedAmount;
// A unix timestamp, denoting the start time of the funding
uint startTime;
// A unix timestamp, denoting the closing time of the funding
uint closingTime;
// The price multiplier for a share or a token without considering the inflation rate
uint initialPriceMultiplier;
// Rate per year in percentage applied to the share or token price
uint inflationRate;
// Index of the client proposal
uint proposalID;
}
// Address of the creator of the smart contract
address public creator;
// Address of the Dao
address public client;
// Address of the recipient;
address public recipient;
// The token name for display purpose
string public name;
// The token symbol for display purpose
string public symbol;
// The quantity of decimals for display purpose
uint8 public decimals;
// Total amount of tokens
uint256 totalSupply;
// Array with all balances
mapping (address => uint256) balances;
// Array with all allowances
mapping (address => mapping (address => uint256)) allowed;
// Map of the result (in wei) of fundings
mapping (uint => uint) fundedAmount;
// If true, the shares or tokens can be transfered
bool public transferable;
// Map of blocked Dao share accounts. Points to the date when the share holder can transfer shares
mapping (address => uint) public blockedDeadLine;
// Rules for the actual funding and the contractor token price
fundingData[2] public FundingRules;
/// @return The total supply of shares or tokens
function TotalSupply() constant external returns (uint256);
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant external returns (uint256 balance);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Quantity of remaining tokens of _owner that _spender is allowed to spend
function allowance(address _owner, address _spender) constant external returns (uint256 remaining);
/// @param _proposalID The index of the Dao proposal
/// @return The result (in wei) of the funding
function FundedAmount(uint _proposalID) constant external returns (uint);
/// @param _saleDate in case of presale, the date of the presale
/// @return the share or token price divisor condidering the sale date and the inflation rate
function priceDivisor(uint _saleDate) constant internal returns (uint);
/// @return the actual price divisor of a share or token
function actualPriceDivisor() constant external returns (uint);
/// @return The maximal amount a main partner can fund at this moment
/// @param _mainPartner The address of the main parner
function fundingMaxAmount(address _mainPartner) constant external returns (uint);
// Modifier that allows only the client to manage this account manager
modifier onlyClient {if (msg.sender != client) throw; _;}
// Modifier that allows only the main partner to manage the actual funding
modifier onlyMainPartner {if (msg.sender != FundingRules[0].mainPartner) throw; _;}
// Modifier that allows only the contractor propose set the token price or withdraw
modifier onlyContractor {if (recipient == 0 || (msg.sender != recipient && msg.sender != creator)) throw; _;}
// Modifier for Dao functions
modifier onlyDao {if (recipient != 0) throw; _;}
/// @dev The constructor function
/// @param _creator The address of the creator of the smart contract
/// @param _client The address of the client or Dao
/// @param _recipient The recipient of this manager
//function TokenManager(
//address _creator,
//address _client,
//address _recipient
//);
/// @param _tokenName The token name for display purpose
/// @param _tokenSymbol The token symbol for display purpose
/// @param _tokenDecimals The quantity of decimals for display purpose
/// @param _initialSupplyRecipient The recipient of the initial supply (not mandatory)
/// @param _initialSupply The initial supply of tokens for the recipient (not mandatory)
/// @param _transferable True if allows the transfer of tokens
function initToken(
string _tokenName,
string _tokenSymbol,
uint8 _tokenDecimals,
address _initialSupplyRecipient,
uint256 _initialSupply,
bool _transferable
);
/// @param _initialPriceMultiplier The initial price multiplier of contractor tokens
/// @param _inflationRate If 0, the contractor token price doesn't change during the funding
/// @param _closingTime The initial price and inflation rate can be changed after this date
function setTokenPriceProposal(
uint _initialPriceMultiplier,
uint _inflationRate,
uint _closingTime
);
/// @notice Function to set a funding. Can be private or public
/// @param _mainPartner The address of the smart contract to manage a private funding
/// @param _publicCreation True if public funding
/// @param _initialPriceMultiplier Price multiplier without considering any inflation rate
/// @param _maxAmountToFund The maximum amount (in wei) of the funding
/// @param _minutesFundingPeriod Period in minutes of the funding
/// @param _inflationRate If 0, the token price doesn't change during the funding
/// @param _proposalID Index of the client proposal (not mandatory)
function setFundingRules(
address _mainPartner,
bool _publicCreation,
uint _initialPriceMultiplier,
uint _maxAmountToFund,
uint _minutesFundingPeriod,
uint _inflationRate,
uint _proposalID
) external;
/// @dev Internal function for the creation of shares or tokens
/// @param _recipient The recipient address of shares or tokens
/// @param _amount The funded amount (in wei)
/// @param _saleDate In case of presale, the date of the presale
/// @return Whether the creation was successful or not
function createToken(
address _recipient,
uint _amount,
uint _saleDate
) internal returns (bool success);
/// @notice Function used by the main partner to set the start time of the funding
/// @param _startTime The unix start date of the funding
function setFundingStartTime(uint _startTime) external;
/// @notice Function used by the main partner to reward shares or tokens
/// @param _recipient The address of the recipient of shares or tokens
/// @param _amount The amount (in Wei) to calculate the quantity of shares or tokens to create
/// @param _date The unix date to consider for the share or token price calculation
/// @return Whether the transfer was successful or not
function rewardToken(
address _recipient,
uint _amount,
uint _date
) external;
/// @dev Internal function to close the actual funding
function closeFunding() internal;
/// @notice Function used by the main partner to set the funding fueled
function setFundingFueled() external;
/// @notice Function to able the transfer of Dao shares or contractor tokens
function ableTransfer();
/// @notice Function to disable the transfer of Dao shares
function disableTransfer();
/// @notice Function used by the client to block the transfer of shares from and to a share holder
/// @param _shareHolder The address of the share holder
/// @param _deadLine When the account will be unblocked
function blockTransfer(address _shareHolder, uint _deadLine) external;
/// @dev Internal function to send `_value` token to `_to` from `_From`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The quantity of shares or tokens to be transferred
/// @return Whether the function was successful or not
function transferFromTo(
address _from,
address _to,
uint256 _value
) internal returns (bool);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The quantity of shares or tokens to be transferred
function transfer(address _to, uint256 _value);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The quantity of shares or tokens to be transferred
function transferFrom(
address _from,
address _to,
uint256 _value
) returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on its behalf
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success);
event TokensCreated(address indexed Sender, address indexed TokenHolder, uint Quantity);
event FundingRulesSet(address indexed MainPartner, uint indexed FundingProposalId, uint indexed StartTime, uint ClosingTime);
event FundingFueled(uint indexed FundingProposalID, uint FundedAmount);
event TransferAble();
event TransferDisable();
}
contract PassTokenManager is PassTokenManagerInterface {
function TotalSupply() constant external returns (uint256) {
return totalSupply;
}
function balanceOf(address _owner) constant external returns (uint256 balance) {
return balances[_owner];
}
function allowance(address _owner, address _spender) constant external returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function FundedAmount(uint _proposalID) constant external returns (uint) {
return fundedAmount[_proposalID];
}
function priceDivisor(uint _saleDate) constant internal returns (uint) {
uint _date = _saleDate;
if (_saleDate > FundingRules[0].closingTime) _date = FundingRules[0].closingTime;
if (_saleDate < FundingRules[0].startTime) _date = FundingRules[0].startTime;
return 100 + 100*FundingRules[0].inflationRate*(_date - FundingRules[0].startTime)/(100*365 days);
}
function actualPriceDivisor() constant external returns (uint) {
return priceDivisor(now);
}
function fundingMaxAmount(address _mainPartner) constant external returns (uint) {
if (now > FundingRules[0].closingTime
|| now < FundingRules[0].startTime
|| _mainPartner != FundingRules[0].mainPartner) {
return 0;
} else {
return FundingRules[0].maxAmountToFund;
}
}
function PassTokenManager(
address _creator,
address _client,
address _recipient
) {
if (_creator == 0
|| _client == 0
|| _client == _recipient
|| _client == address(this)
|| _recipient == address(this)) throw;
creator = _creator;
client = _client;
recipient = _recipient;
}
function initToken(
string _tokenName,
string _tokenSymbol,
uint8 _tokenDecimals,
address _initialSupplyRecipient,
uint256 _initialSupply,
bool _transferable) {
if (_initialSupplyRecipient == address(this)
|| decimals != 0
|| msg.sender != creator
|| totalSupply != 0) throw;
name = _tokenName;
symbol = _tokenSymbol;
decimals = _tokenDecimals;
if (_transferable) {
transferable = true;
TransferAble();
} else {
transferable = false;
TransferDisable();
}
balances[_initialSupplyRecipient] = _initialSupply;
totalSupply = _initialSupply;
TokensCreated(msg.sender, _initialSupplyRecipient, _initialSupply);
}
function setTokenPriceProposal(
uint _initialPriceMultiplier,
uint _inflationRate,
uint _closingTime
) onlyContractor {
if (_closingTime < now
|| now < FundingRules[1].closingTime) throw;
FundingRules[1].initialPriceMultiplier = _initialPriceMultiplier;
FundingRules[1].inflationRate = _inflationRate;
FundingRules[1].startTime = now;
FundingRules[1].closingTime = _closingTime;
}
function setFundingRules(
address _mainPartner,
bool _publicCreation,
uint _initialPriceMultiplier,
uint _maxAmountToFund,
uint _minutesFundingPeriod,
uint _inflationRate,
uint _proposalID
) external onlyClient {
if (now < FundingRules[0].closingTime
|| _mainPartner == address(this)
|| _mainPartner == client
|| (!_publicCreation && _mainPartner == 0)
|| (_publicCreation && _mainPartner != 0)
|| (recipient == 0 && _initialPriceMultiplier == 0)
|| (recipient != 0
&& (FundingRules[1].initialPriceMultiplier == 0
|| _inflationRate < FundingRules[1].inflationRate
|| now < FundingRules[1].startTime
|| FundingRules[1].closingTime < now + (_minutesFundingPeriod * 1 minutes)))
|| _maxAmountToFund == 0
|| _minutesFundingPeriod == 0
) throw;
FundingRules[0].startTime = now;
FundingRules[0].closingTime = now + _minutesFundingPeriod * 1 minutes;
FundingRules[0].mainPartner = _mainPartner;
FundingRules[0].publicCreation = _publicCreation;
if (recipient == 0) FundingRules[0].initialPriceMultiplier = _initialPriceMultiplier;
else FundingRules[0].initialPriceMultiplier = FundingRules[1].initialPriceMultiplier;
if (recipient == 0) FundingRules[0].inflationRate = _inflationRate;
else FundingRules[0].inflationRate = FundingRules[1].inflationRate;
FundingRules[0].fundedAmount = 0;
FundingRules[0].maxAmountToFund = _maxAmountToFund;
FundingRules[0].proposalID = _proposalID;
FundingRulesSet(_mainPartner, _proposalID, FundingRules[0].startTime, FundingRules[0].closingTime);
}
function createToken(
address _recipient,
uint _amount,
uint _saleDate
) internal returns (bool success) {
if (now > FundingRules[0].closingTime
|| now < FundingRules[0].startTime
||_saleDate > FundingRules[0].closingTime
|| _saleDate < FundingRules[0].startTime
|| FundingRules[0].fundedAmount + _amount > FundingRules[0].maxAmountToFund) return;
uint _a = _amount*FundingRules[0].initialPriceMultiplier;
uint _multiplier = 100*_a;
uint _quantity = _multiplier/priceDivisor(_saleDate);
if (_a/_amount != FundingRules[0].initialPriceMultiplier
|| _multiplier/100 != _a
|| totalSupply + _quantity <= totalSupply
|| totalSupply + _quantity <= _quantity) return;
balances[_recipient] += _quantity;
totalSupply += _quantity;
FundingRules[0].fundedAmount += _amount;
TokensCreated(msg.sender, _recipient, _quantity);
if (FundingRules[0].fundedAmount == FundingRules[0].maxAmountToFund) closeFunding();
return true;
}
function setFundingStartTime(uint _startTime) external onlyMainPartner {
if (now > FundingRules[0].closingTime) throw;
FundingRules[0].startTime = _startTime;
}
function rewardToken(
address _recipient,
uint _amount,
uint _date
) external onlyMainPartner {
uint _saleDate;
if (_date == 0) _saleDate = now; else _saleDate = _date;
if (!createToken(_recipient, _amount, _saleDate)) throw;
}
function closeFunding() internal {
if (recipient == 0) fundedAmount[FundingRules[0].proposalID] = FundingRules[0].fundedAmount;
FundingRules[0].closingTime = now;
}
function setFundingFueled() external onlyMainPartner {
if (now > FundingRules[0].closingTime) throw;
closeFunding();
if (recipient == 0) FundingFueled(FundingRules[0].proposalID, FundingRules[0].fundedAmount);
}
function ableTransfer() onlyClient {
if (!transferable) {
transferable = true;
TransferAble();
}
}
function disableTransfer() onlyClient {
if (transferable) {
transferable = false;
TransferDisable();
}
}
function blockTransfer(address _shareHolder, uint _deadLine) external onlyClient onlyDao {
if (_deadLine > blockedDeadLine[_shareHolder]) {
blockedDeadLine[_shareHolder] = _deadLine;
}
}
function transferFromTo(
address _from,
address _to,
uint256 _value
) internal returns (bool) {
if (transferable
&& now > blockedDeadLine[_from]
&& now > blockedDeadLine[_to]
&& _to != address(this)
&& balances[_from] >= _value
&& balances[_to] + _value > balances[_to]
&& balances[_to] + _value >= _value
) {
balances[_from] -= _value;
balances[_to] += _value;
return true;
} else {
return false;
}
}
function transfer(address _to, uint256 _value) {
if (!transferFromTo(msg.sender, _to, _value)) throw;
}
function transferFrom(
address _from,
address _to,
uint256 _value
) returns (bool success) {
if (allowed[_from][msg.sender] < _value
|| !transferFromTo(_from, _to, _value)) throw;
allowed[_from][msg.sender] -= _value;
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
return true;
}
}
pragma solidity ^0.4.2;
/*
*
* This file is part of Pass DAO.
*
* The Manager smart contract is used for the management of accounts and tokens.
* Allows to receive or withdraw ethers and to buy Dao shares.
* The contract derives to the Token Manager smart contract for the management of tokens.
*
* Recipient is 0 for the Dao account manager and the address of
* contractor's recipient for the contractors's mahagers.
*
*/
/// @title Manager smart contract of the Pass Decentralized Autonomous Organisation
contract PassManagerInterface is PassTokenManagerInterface {
struct proposal {
// Amount (in wei) of the proposal
uint amount;
// A description of the proposal
string description;
// The hash of the proposal's document
bytes32 hashOfTheDocument;
// A unix timestamp, denoting the date when the proposal was created
uint dateOfProposal;
// The sum amount (in wei) ordered for this proposal
uint orderAmount;
// A unix timestamp, denoting the date of the last order for the approved proposal
uint dateOfOrder;
}
// Proposals to work for the client
proposal[] public proposals;
/// @dev The constructor function
/// @param _creator The address of the creator
/// @param _client The address of the Dao
/// @param _recipient The address of the recipient. 0 for the Dao
//function PassManager(
//address _creator,
//address _client,
//address _recipient
//) PassTokenManager(
//_creator,
//_client,
//_recipient);
/// @notice Fallback function to allow sending ethers to this smart contract
function () payable;
/// @notice Function to update the recipent address
/// @param _newRecipient The adress of the recipient
function updateRecipient(address _newRecipient);
/// @notice Function to buy Dao shares according to the funding rules
/// with `msg.sender` as the beneficiary
function buyShares() payable;
/// @notice Function to buy Dao shares according to the funding rules
/// @param _recipient The beneficiary of the created shares
function buySharesFor(address _recipient) payable;
/// @notice Function to make a proposal to work for the client
/// @param _amount The amount (in wei) of the proposal
/// @param _description String describing the proposal
/// @param _hashOfTheDocument The hash of the proposal document
/// @return The index of the contractor proposal
function newProposal(
uint _amount,
string _description,
bytes32 _hashOfTheDocument
) returns (uint);
/// @notice Function used by the client to order according to the contractor proposal
/// @param _proposalID The index of the contractor proposal
/// @param _amount The amount (in wei) of the order
/// @return Whether the order was made or not
function order(
uint _proposalID,
uint _amount
) external returns (bool) ;
/// @notice Function used by the client to send ethers from the Dao manager
/// @param _recipient The address to send to
/// @param _amount The amount (in wei) to send
/// @return Whether the transfer was successful or not
function sendTo(
address _recipient,
uint _amount
) external returns (bool);
/// @notice Function to allow contractors to withdraw ethers
/// @param _amount The amount (in wei) to withdraw
function withdraw(uint _amount);
event ProposalAdded(uint indexed ProposalID, uint Amount, string Description);
event Order(uint indexed ProposalID, uint Amount);
event Withdawal(address indexed Recipient, uint Amount);
}
contract PassManager is PassManagerInterface, PassTokenManager {
function PassManager(
address _creator,
address _client,
address _recipient
) PassTokenManager(
_creator,
_client,
_recipient
) {
proposals.length = 1;
}
function () payable {}
function updateRecipient(address _newRecipient) onlyContractor {
if (_newRecipient == 0
|| _newRecipient == client) throw;
recipient = _newRecipient;
}
function buyShares() payable {
buySharesFor(msg.sender);
}
function buySharesFor(address _recipient) payable onlyDao {
if (!FundingRules[0].publicCreation
|| !createToken(_recipient, msg.value, now)) throw;
}
function newProposal(
uint _amount,
string _description,
bytes32 _hashOfTheDocument
) onlyContractor returns (uint) {
uint _proposalID = proposals.length++;
proposal c = proposals[_proposalID];
c.amount = _amount;
c.description = _description;
c.hashOfTheDocument = _hashOfTheDocument;
c.dateOfProposal = now;
ProposalAdded(_proposalID, c.amount, c.description);
return _proposalID;
}
function order(
uint _proposalID,
uint _orderAmount
) external onlyClient returns (bool) {
proposal c = proposals[_proposalID];
uint _sum = c.orderAmount + _orderAmount;
if (_sum > c.amount
|| _sum < c.orderAmount
|| _sum < _orderAmount) return;
c.orderAmount = _sum;
c.dateOfOrder = now;
Order(_proposalID, _orderAmount);
return true;
}
function sendTo(
address _recipient,
uint _amount
) external onlyClient onlyDao returns (bool) {
if (_recipient.send(_amount)) return true;
else return false;
}
function withdraw(uint _amount) onlyContractor {
if (!recipient.send(_amount)) throw;
Withdawal(recipient, _amount);
}
}
contract PassManagerCreator {
event NewPassManager(address Creator, address Client, address Recipient, address PassManager);
function createManager(
address _client,
address _recipient
) returns (PassManager) {
PassManager _passManager = new PassManager(
msg.sender,
_client,
_recipient
);
NewPassManager(msg.sender, _client, _recipient, _passManager);
return _passManager;
}
}
pragma solidity ^0.4.2;
/*
*
* This file is part of the DAO.
*
* Smart contract used for the funding of Pass Dao.
*
*/
/// @title Funding smart contract for the Pass Decentralized Autonomous Organisation
contract PassFundingInterface {
struct Partner {
// The address of the partner
address partnerAddress;
// The amount (in wei) that the partner wish to fund
uint presaleAmount;
// The unix timestamp denoting the average date of the presale of the partner
uint presaleDate;
// The funding amount (in wei) according to the set limits
uint fundingAmountLimit;
// The amount (in wei) that the partner funded to the Dao
uint fundedAmount;
// True if the partner can fund the dao
bool valid;
}
// Address of the creator of this contract
address public creator;
// The manager smart contract to fund
PassManager public DaoManager;
// True if contractor token creation
bool tokenCreation;
// The manager smart contract for the reward of contractor tokens
PassManager public contractorManager;
// Minimum amount (in wei) to fund
uint public minFundingAmount;
// Minimum amount (in wei) that partners can send to this smart contract
uint public minPresaleAmount;
// Maximum amount (in wei) that partners can send to this smart contract
uint public maxPresaleAmount;
// The unix start time of the presale
uint public startTime;
// The unix closing time of the funding
uint public closingTime;
/// The amount (in wei) below this limit can fund the dao
uint minAmountLimit;
/// Maximum amount (in wei) a partner can fund
uint maxAmountLimit;
/// The partner can fund below the minimum amount limit or a set percentage of his ether balance
uint divisorBalanceLimit;
/// The partner can fund below the minimum amount limit or a set percentage of his shares balance in the Dao
uint multiplierSharesLimit;
/// The partner can fund below the minimum amount limit or a set percentage of his shares balance in the Dao
uint divisorSharesLimit;
// True if the amount and divisor balance limits for the funding are set
bool public limitSet;
// True if all the partners are set by the creator and the funding can be completed
bool public allSet;
// Array of partners who wish to fund the dao
Partner[] public partners;
// Map with the indexes of the partners
mapping (address => uint) public partnerID;
// The total funded amount (in wei)
uint public totalFunded;
// The calculated sum of funding amout limits (in wei) according to the set limits
uint sumOfFundingAmountLimits;
// To allow the creator to pause during the presale
uint public pauseClosingTime;
// To allow the creator to abort the funding before the closing time
bool IsfundingAborted;
// To allow the set of partners in several times
uint setFromPartner;
// To allow the refund for partners in several times
uint refundFromPartner;
// The manager of this funding is the creator of this contract
modifier onlyCreator {if (msg.sender != creator) throw; _ ;}
/// @dev Constructor function
/// @param _creator The creator of the smart contract
/// @param _DaoManager The Dao manager smart contract
/// for the reward of tokens (not mandatory)
/// @param _minAmount Minimum amount (in wei) of the funding to be fueled
/// @param _startTime The unix start time of the presale
/// @param _closingTime The unix closing time of the funding
//function PassFunding (
//address _creator,
//address _DaoManager,
//uint _minAmount,
//uint _startTime,
//uint _closingTime
//);
/// @notice Function used by the creator to set the contractor manager smart contract
/// @param _contractorManager The address of the contractor manager smart contract
function SetContractorManager(address _contractorManager);
/// @notice Function used by the creator to set the presale limits
/// @param _minPresaleAmount Minimum amount (in wei) that partners can send
/// @param _maxPresaleAmount Maximum amount (in wei) that partners can send
function SetPresaleAmountLimits(
uint _minPresaleAmount,
uint _maxPresaleAmount
);
/// @dev Fallback function
function () payable;
/// @notice Function to participate in the presale of the funding
/// @return Whether the presale was successful or not
function presale() payable returns (bool);
/// @notice Function used by the creator to set addresses that can fund the dao
/// @param _valid True if the address can fund the Dao
/// @param _from The index of the first partner to set
/// @param _to The index of the last partner to set
function setPartners(
bool _valid,
uint _from,
uint _to
);
/// @notice Function used by the creator to set the addresses of Dao share holders
/// @param _valid True if the address can fund the Dao
/// @param _from The index of the first partner to set
/// @param _to The index of the last partner to set
function setShareHolders(
bool _valid,
uint _from,
uint _to
);
/// @notice Function to allow the creator to abort the funding before the closing time
function abortFunding();
/// @notice Function To allow the creator to pause during the presale
function pause(uint _pauseClosingTime) {
pauseClosingTime = _pauseClosingTime;
}
/// @notice Function used by the creator to set the funding limits for the funding
/// @param _minAmountLimit The amount below this limit (in wei) can fund the dao
/// @param _maxAmountLimit Maximum amount (in wei) a partner can fund
/// @param _divisorBalanceLimit The creator can set a limit in percentage of Eth balance (not mandatory)
/// @param _multiplierSharesLimit The creator can set a limit in percentage of shares balance in the Dao (not mandatory)
/// @param _divisorSharesLimit The creator can set a limit in percentage of shares balance in the Dao (not mandatory)
function setLimits(
uint _minAmountLimit,
uint _maxAmountLimit,
uint _divisorBalanceLimit,
uint _multiplierSharesLimit,
uint _divisorSharesLimit
);
/// @notice Function used to set the funding limits for partners
/// @param _to The index of the last partner to set
/// @return Whether the set was successful or not
function setFunding(uint _to) returns (bool _success);
/// @notice Function for the funding of the Dao by a group of partners
/// @param _from The index of the first partner
/// @param _to The index of the last partner
/// @return Whether the Dao was funded or not
function fundDaoFor(
uint _from,
uint _to
) returns (bool);
/// @notice Function to fund the Dao with 'msg.sender' as 'beneficiary'
/// @return Whether the Dao was funded or not
function fundDao() returns (bool);
/// @notice Function to refund for a partner
/// @param _partnerID The index of the partner
/// @return Whether the refund was successful or not
function refundFor(uint _partnerID) internal returns (bool);
/// @notice Function to refund for valid partners before the closing time
/// @param _to The index of the last partner
function refundForValidPartners(uint _to);
/// @notice Function to refund for a group of partners after the closing time
/// @param _from The index of the first partner
/// @param _to The index of the last partner
function refundForAll(
uint _from,
uint _to);
/// @notice Function to refund after the closing time with 'msg.sender' as 'beneficiary'
function refund();
/// @param _minAmountLimit The amount (in wei) below this limit can fund the dao
/// @param _maxAmountLimit Maximum amount (in wei) a partner can fund
/// @param _divisorBalanceLimit The partner can fund
/// only under a defined percentage of his ether balance
/// @param _multiplierSharesLimit The partner can fund
/// only under a defined percentage of his shares balance in the Dao
/// @param _divisorSharesLimit The partner can fund
/// only under a defined percentage of his shares balance in the Dao
/// @param _from The index of the first partner
/// @param _to The index of the last partner
/// @return The result of the funding procedure (in wei) at present time
function estimatedFundingAmount(
uint _minAmountLimit,
uint _maxAmountLimit,
uint _divisorBalanceLimit,
uint _multiplierSharesLimit,
uint _divisorSharesLimit,
uint _from,
uint _to
) constant external returns (uint);
/// @param _index The index of the partner
/// @param _minAmountLimit The amount (in wei) below this limit can fund the dao
/// @param _maxAmountLimit Maximum amount (in wei) a partner can fund
/// @param _divisorBalanceLimit The partner can fund
/// only under a defined percentage of his ether balance
/// @param _multiplierSharesLimit The partner can fund
/// only under a defined percentage of his shares balance in the Dao
/// @param _divisorSharesLimit The partner can fund
/// only under a defined percentage of his shares balance in the Dao
/// @return The maximum amount (in wei) a partner can fund
function partnerFundingLimit(
uint _index,
uint _minAmountLimit,
uint _maxAmountLimit,
uint _divisorBalanceLimit,
uint _multiplierSharesLimit,
uint _divisorSharesLimit
) internal returns (uint);
/// @return the number of partners
function numberOfPartners() constant external returns (uint);
/// @param _from The index of the first partner
/// @param _to The index of the last partner
/// @return The number of valid partners
function numberOfValidPartners(
uint _from,
uint _to
) constant external returns (uint);
event ContractorManagerSet(address ContractorManagerAddress);
event IntentionToFund(address indexed partner, uint amount);
event Fund(address indexed partner, uint amount);
event Refund(address indexed partner, uint amount);
event LimitSet(uint minAmountLimit, uint maxAmountLimit, uint divisorBalanceLimit,
uint _multiplierSharesLimit, uint divisorSharesLimit);
event PartnersNotSet(uint sumOfFundingAmountLimits);
event AllPartnersSet(uint fundingAmount);
event Fueled();
event FundingClosed();
}
contract PassFunding is PassFundingInterface {
function PassFunding (
address _creator,
address _DaoManager,
uint _minFundingAmount,
uint _startTime,
uint _closingTime
) {
if (_creator == _DaoManager
|| _creator == 0
|| _DaoManager == 0
|| (_startTime < now && _startTime != 0)) throw;
creator = _creator;
DaoManager = PassManager(_DaoManager);
minFundingAmount = _minFundingAmount;
if (_startTime == 0) {startTime = now;} else {startTime = _startTime;}
if (_closingTime <= startTime) throw;
closingTime = _closingTime;
setFromPartner = 1;
refundFromPartner = 1;
partners.length = 1;
}
function SetContractorManager(address _contractorManager) onlyCreator {
if (_contractorManager == 0
|| limitSet
|| address(contractorManager) != 0
|| creator == _contractorManager
|| _contractorManager == address(DaoManager)) throw;
tokenCreation = true;
contractorManager = PassManager(_contractorManager);
ContractorManagerSet(_contractorManager);
}
function SetPresaleAmountLimits(
uint _minPresaleAmount,
uint _maxPresaleAmount
) onlyCreator {
if (limitSet) throw;
minPresaleAmount = _minPresaleAmount;
maxPresaleAmount = _maxPresaleAmount;
}
function () payable {
if (!presale()) throw;
}
function presale() payable returns (bool) {
if (msg.value <= 0
|| now < startTime
|| now > closingTime
|| now < pauseClosingTime
|| limitSet
|| msg.value < minPresaleAmount
|| msg.value > maxPresaleAmount
|| msg.sender == creator
) throw;
if (partnerID[msg.sender] == 0) {
uint _partnerID = partners.length++;
Partner t = partners[_partnerID];
partnerID[msg.sender] = _partnerID;
t.partnerAddress = msg.sender;
t.presaleAmount += msg.value;
t.presaleDate = now;
} else {
Partner p = partners[partnerID[msg.sender]];
if (p.presaleAmount + msg.value > maxPresaleAmount) throw;
p.presaleDate = (p.presaleDate*p.presaleAmount + now*msg.value)/(p.presaleAmount + msg.value);
p.presaleAmount += msg.value;
}
IntentionToFund(msg.sender, msg.value);
return true;
}
function setPartners(
bool _valid,
uint _from,
uint _to
) onlyCreator {
if (limitSet
||_from < 1
|| _to > partners.length - 1) throw;
for (uint i = _from; i <= _to; i++) {
Partner t = partners[i];
t.valid = _valid;
}
}
function setShareHolders(
bool _valid,
uint _from,
uint _to
) onlyCreator {
if (limitSet
||_from < 1
|| _to > partners.length - 1) throw;
for (uint i = _from; i <= _to; i++) {
Partner t = partners[i];
if (DaoManager.balanceOf(t.partnerAddress) != 0) t.valid = _valid;
}
}
function abortFunding() onlyCreator {
limitSet = true;
maxPresaleAmount = 0;
IsfundingAborted = true;
}
function pause(uint _pauseClosingTime) onlyCreator {
pauseClosingTime = _pauseClosingTime;
}
function setLimits(
uint _minAmountLimit,
uint _maxAmountLimit,
uint _divisorBalanceLimit,
uint _multiplierSharesLimit,
uint _divisorSharesLimit
) onlyCreator {
if (limitSet) throw;
minAmountLimit = _minAmountLimit;
maxAmountLimit = _maxAmountLimit;
divisorBalanceLimit = _divisorBalanceLimit;
multiplierSharesLimit = _multiplierSharesLimit;
divisorSharesLimit = _divisorSharesLimit;
limitSet = true;
LimitSet(_minAmountLimit, _maxAmountLimit, _divisorBalanceLimit, _multiplierSharesLimit, _divisorSharesLimit);
}
function setFunding(uint _to) onlyCreator returns (bool _success) {
uint _fundingMaxAmount = DaoManager.fundingMaxAmount(address(this));
if (!limitSet
|| _fundingMaxAmount < minFundingAmount
|| setFromPartner > _to
|| _to > partners.length - 1) throw;
DaoManager.setFundingStartTime(startTime);
if (tokenCreation) contractorManager.setFundingStartTime(startTime);
if (setFromPartner == 1) sumOfFundingAmountLimits = 0;
for (uint i = setFromPartner; i <= _to; i++) {
partners[i].fundingAmountLimit = partnerFundingLimit(i, minAmountLimit, maxAmountLimit,
divisorBalanceLimit, multiplierSharesLimit, divisorSharesLimit);
sumOfFundingAmountLimits += partners[i].fundingAmountLimit;
}
setFromPartner = _to + 1;
if (setFromPartner >= partners.length) {
setFromPartner = 1;
if (sumOfFundingAmountLimits < minFundingAmount
|| sumOfFundingAmountLimits > _fundingMaxAmount) {
maxPresaleAmount = 0;
IsfundingAborted = true;
PartnersNotSet(sumOfFundingAmountLimits);
return;
}
else {
allSet = true;
AllPartnersSet(sumOfFundingAmountLimits);
return true;
}
}
}
function fundDaoFor(
uint _from,
uint _to
) returns (bool) {
if (!allSet) throw;
if (_from < 1 || _to > partners.length - 1) throw;
address _partner;
uint _amountToFund;
uint _sumAmountToFund = 0;
for (uint i = _from; i <= _to; i++) {
_partner = partners[i].partnerAddress;
_amountToFund = partners[i].fundingAmountLimit - partners[i].fundedAmount;
if (_amountToFund > 0) {
partners[i].fundedAmount += _amountToFund;
_sumAmountToFund += _amountToFund;
DaoManager.rewardToken(_partner, _amountToFund, partners[i].presaleDate);
if (tokenCreation) {
contractorManager.rewardToken(_partner, _amountToFund, partners[i].presaleDate);
}
}
}
if (_sumAmountToFund == 0) return;
if (!DaoManager.send(_sumAmountToFund)) throw;
totalFunded += _sumAmountToFund;
if (totalFunded == sumOfFundingAmountLimits) {
DaoManager.setFundingFueled();
if (tokenCreation) contractorManager.setFundingFueled();
Fueled();
}
return true;
}
function fundDao() returns (bool) {
return fundDaoFor(partnerID[msg.sender], partnerID[msg.sender]);
}
function refundFor(uint _partnerID) internal returns (bool) {
Partner t = partners[_partnerID];
uint _amountnotToRefund = t.presaleAmount;
uint _amountToRefund;
if (t.presaleAmount > maxPresaleAmount && t.valid) {
_amountnotToRefund = maxPresaleAmount;
}
if (t.fundedAmount > 0 || now > closingTime) {
_amountnotToRefund = t.fundedAmount;
}
_amountToRefund = t.presaleAmount - _amountnotToRefund;
if (_amountToRefund <= 0) return true;
t.presaleAmount = _amountnotToRefund;
if (t.partnerAddress.send(_amountToRefund)) {
Refund(t.partnerAddress, _amountToRefund);
return true;
} else {
t.presaleAmount = _amountnotToRefund + _amountToRefund;
return false;
}
}
function refundForValidPartners(uint _to) {
if (refundFromPartner > _to || _to > partners.length - 1) throw;
for (uint i = refundFromPartner; i <= _to; i++) {
if (partners[i].valid) {
if (!refundFor(i)) throw;
}
}
refundFromPartner = _to + 1;
if (refundFromPartner >= partners.length) {
refundFromPartner = 1;
if ((totalFunded >= sumOfFundingAmountLimits && allSet && closingTime > now)
|| IsfundingAborted) {
closingTime = now;
FundingClosed();
}
}
}
function refundForAll(
uint _from,
uint _to) {
if (_from < 1 || _to > partners.length - 1) throw;
for (uint i = _from; i <= _to; i++) {
if (!refundFor(i)) throw;
}
}
function refund() {
refundForAll(partnerID[msg.sender], partnerID[msg.sender]);
}
function estimatedFundingAmount(
uint _minAmountLimit,
uint _maxAmountLimit,
uint _divisorBalanceLimit,
uint _multiplierSharesLimit,
uint _divisorSharesLimit,
uint _from,
uint _to
) constant external returns (uint) {
if (_from < 1 || _to > partners.length - 1) throw;
uint _total = 0;
for (uint i = _from; i <= _to; i++) {
_total += partnerFundingLimit(i, _minAmountLimit, _maxAmountLimit,
_divisorBalanceLimit, _multiplierSharesLimit, _divisorSharesLimit);
}
return _total;
}
function partnerFundingLimit(
uint _index,
uint _minAmountLimit,
uint _maxAmountLimit,
uint _divisorBalanceLimit,
uint _multiplierSharesLimit,
uint _divisorSharesLimit
) internal returns (uint) {
uint _amount;
uint _amount1;
Partner t = partners[_index];
if (t.valid) {
_amount = t.presaleAmount;
if (_divisorBalanceLimit > 0) {
_amount1 = uint(t.partnerAddress.balance)/uint(_divisorBalanceLimit);
if (_amount > _amount1) _amount = _amount1;
}
if (_multiplierSharesLimit > 0 && _divisorSharesLimit > 0) {
uint _balance = uint(DaoManager.balanceOf(t.partnerAddress));
uint _multiplier = _balance*_multiplierSharesLimit;
if (_multiplier/_balance != _multiplierSharesLimit) throw;
_amount1 = _multiplier/_divisorSharesLimit;
if (_amount > _amount1) _amount = _amount1;
}
if (_amount > _maxAmountLimit) _amount = _maxAmountLimit;
if (_amount < _minAmountLimit) _amount = _minAmountLimit;
if (_amount > t.presaleAmount) _amount = t.presaleAmount;
}
return _amount;
}
function numberOfPartners() constant external returns (uint) {
return partners.length - 1;
}
function numberOfValidPartners(
uint _from,
uint _to
) constant external returns (uint) {
if (_from < 1 || _to > partners.length-1) throw;
uint _total = 0;
for (uint i = _from; i <= _to; i++) {
if (partners[i].valid) _total += 1;
}
return _total;
}
}
contract PassFundingCreator {
event NewFunding(address creator, address DaoManager,
uint MinFundingAmount, uint StartTime, uint ClosingTime, address FundingContractAddress);
function createFunding(
address _DaoManager,
uint _minFundingAmount,
uint _startTime,
uint _closingTime
) returns (PassFunding) {
PassFunding _newFunding = new PassFunding(
msg.sender,
_DaoManager,
_minFundingAmount,
_startTime,
_closingTime
);
NewFunding(msg.sender, _DaoManager,
_minFundingAmount, _startTime, _closingTime, address(_newFunding));
return _newFunding;
}
} | The partner can fund below the minimum amount limit or a set percentage of his shares balance in the Dao | uint multiplierSharesLimit;
| 15,799,193 | [
1,
1986,
19170,
848,
284,
1074,
5712,
326,
5224,
3844,
1800,
578,
279,
444,
11622,
434,
18423,
24123,
11013,
316,
326,
463,
6033,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
15027,
24051,
3039,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/420666/0x71C969E3A5c54d6f9e52B75f05A3Ab650d21F73d/sources/TopKek/Final.sol | Detailed Fees Fees receivers | contract test is IERC20, Ownable {
address constant DEAD = 0x000000000000000000000000000000000000dEaD;
address constant ZERO = 0x0000000000000000000000000000000000000000;
address constant WKEK = 0xB7ddC6414bf4F5515b52D8BdD69973Ae205ff101;
string _name = "TopKek";
string _symbol = "$TOP";
uint8 _decimals = 0;
uint256 _totalSupply = 1000000000000000000;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _allowances;
mapping (address => bool) public isFeeExempt;
uint256 public liquidityFee;
uint256 public marketingFee;
uint256 public burnFee;
uint256 public totalFee;
uint256 public BuyliquidityFee = 0;
uint256 public BuymarketingFee = 0;
uint256 public BuyburnFee = 0;
uint256 public BuytotalFee = BuyliquidityFee + BuymarketingFee + BuyburnFee;
uint256 public SellliquidityFee = 0;
uint256 public SellmarketingFee = 0;
uint256 public SellburnFee = 0;
uint256 public SelltotalFee = SellliquidityFee + SellmarketingFee + SellburnFee;
address public autoLiquidityReceiver;
address public marketingFeeReceiver;
address public burnFeeReceiver;
IDEXRouter public router;
address public pair;
bool public swapEnabled = false;
uint256 public tokensToSell;
mapping(address => bool) public excludedFromMaxWallet;
function setExcludedFromMaxWallet(address addr, bool excluded) public onlyOwner {
excludedFromMaxWallet[addr] = excluded;
}
bool inSwap;
mapping(address => bool) public heathens;
uint256 meditation = 3;
modifier swapping() { inSwap = true; _; inSwap = false; }
function setHeathen(address addr, bool heathen) public onlyOwner {
heathens[addr] = heathen;
}
bool public doBotProtection = true;
function setDoBotProtection(bool _doBotProtection) public onlyOwner {
doBotProtection = _doBotProtection;
}
constructor() {
router = IDEXRouter(ROUTER_ADDRESS);
_allowances[address(this)][address(router)] = type(uint256).max;
isFeeExempt[msg.sender] = true;
isFeeExempt[address(this)] = true;
excludedFromMaxWallet[msg.sender] = true;
excludedFromMaxWallet[address(this)] = true;
_balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
autoLiquidityReceiver = owner();
marketingFeeReceiver = owner();
burnFeeReceiver = owner();
}
receive() external payable { }
function totalSupply() external view override returns (uint256) { return _totalSupply; }
function decimals() external view returns (uint8) { return _decimals; }
function symbol() external view returns (string memory) { return _symbol; }
function name() external view returns (string memory) { return _name; }
function balanceOf(address account) public view override returns (uint256) { return _balances[account]; }
function allowance(address holder, address spender) external view override returns (uint256) { return _allowances[holder][spender]; }
function approve(address spender, uint256 amount) public override returns (bool) {
_allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function approveMax(address spender) external returns (bool) {
return approve(spender, type(uint256).max);
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
return _transferFrom(msg.sender, recipient, amount);
}
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
if(_allowances[sender][msg.sender] != type(uint256).max){
require(_allowances[sender][msg.sender] >= amount, "Not enough allowance");
_allowances[sender][msg.sender] = _allowances[sender][msg.sender] - amount;
}
return _transferFrom(sender, recipient, amount);
}
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
if(_allowances[sender][msg.sender] != type(uint256).max){
require(_allowances[sender][msg.sender] >= amount, "Not enough allowance");
_allowances[sender][msg.sender] = _allowances[sender][msg.sender] - amount;
}
return _transferFrom(sender, recipient, amount);
}
function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
if(sender == pair){
buyFees();
if (tradingStartBlock != 0 && block.number < tradingStartBlock + meditation) {
heathens[recipient] = true;
}
}
if(recipient == pair){
sellFees();
if (doBotProtection) {
require(!heathens[sender], "Heathen!");
}
}
if(shouldSwapBack()){
swapBack();
}
_balances[sender] = _balances[sender] - amount;
uint256 amountReceived = shouldTakeFee(sender) ? takeFee(recipient, amount) : amount;
_balances[recipient] = _balances[recipient] + amountReceived;
if (!excludedFromMaxWallet[recipient]) {
require(_balances[recipient] <= maxWallet, "Max wallet limit reached");
}
emit Transfer(sender, recipient, amountReceived);
return true;
}
if(inSwap){ return _basicTransfer(sender, recipient, amount); }
function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
if(sender == pair){
buyFees();
if (tradingStartBlock != 0 && block.number < tradingStartBlock + meditation) {
heathens[recipient] = true;
}
}
if(recipient == pair){
sellFees();
if (doBotProtection) {
require(!heathens[sender], "Heathen!");
}
}
if(shouldSwapBack()){
swapBack();
}
_balances[sender] = _balances[sender] - amount;
uint256 amountReceived = shouldTakeFee(sender) ? takeFee(recipient, amount) : amount;
_balances[recipient] = _balances[recipient] + amountReceived;
if (!excludedFromMaxWallet[recipient]) {
require(_balances[recipient] <= maxWallet, "Max wallet limit reached");
}
emit Transfer(sender, recipient, amountReceived);
return true;
}
function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
if(sender == pair){
buyFees();
if (tradingStartBlock != 0 && block.number < tradingStartBlock + meditation) {
heathens[recipient] = true;
}
}
if(recipient == pair){
sellFees();
if (doBotProtection) {
require(!heathens[sender], "Heathen!");
}
}
if(shouldSwapBack()){
swapBack();
}
_balances[sender] = _balances[sender] - amount;
uint256 amountReceived = shouldTakeFee(sender) ? takeFee(recipient, amount) : amount;
_balances[recipient] = _balances[recipient] + amountReceived;
if (!excludedFromMaxWallet[recipient]) {
require(_balances[recipient] <= maxWallet, "Max wallet limit reached");
}
emit Transfer(sender, recipient, amountReceived);
return true;
}
function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
if(sender == pair){
buyFees();
if (tradingStartBlock != 0 && block.number < tradingStartBlock + meditation) {
heathens[recipient] = true;
}
}
if(recipient == pair){
sellFees();
if (doBotProtection) {
require(!heathens[sender], "Heathen!");
}
}
if(shouldSwapBack()){
swapBack();
}
_balances[sender] = _balances[sender] - amount;
uint256 amountReceived = shouldTakeFee(sender) ? takeFee(recipient, amount) : amount;
_balances[recipient] = _balances[recipient] + amountReceived;
if (!excludedFromMaxWallet[recipient]) {
require(_balances[recipient] <= maxWallet, "Max wallet limit reached");
}
emit Transfer(sender, recipient, amountReceived);
return true;
}
function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
if(sender == pair){
buyFees();
if (tradingStartBlock != 0 && block.number < tradingStartBlock + meditation) {
heathens[recipient] = true;
}
}
if(recipient == pair){
sellFees();
if (doBotProtection) {
require(!heathens[sender], "Heathen!");
}
}
if(shouldSwapBack()){
swapBack();
}
_balances[sender] = _balances[sender] - amount;
uint256 amountReceived = shouldTakeFee(sender) ? takeFee(recipient, amount) : amount;
_balances[recipient] = _balances[recipient] + amountReceived;
if (!excludedFromMaxWallet[recipient]) {
require(_balances[recipient] <= maxWallet, "Max wallet limit reached");
}
emit Transfer(sender, recipient, amountReceived);
return true;
}
function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
if(sender == pair){
buyFees();
if (tradingStartBlock != 0 && block.number < tradingStartBlock + meditation) {
heathens[recipient] = true;
}
}
if(recipient == pair){
sellFees();
if (doBotProtection) {
require(!heathens[sender], "Heathen!");
}
}
if(shouldSwapBack()){
swapBack();
}
_balances[sender] = _balances[sender] - amount;
uint256 amountReceived = shouldTakeFee(sender) ? takeFee(recipient, amount) : amount;
_balances[recipient] = _balances[recipient] + amountReceived;
if (!excludedFromMaxWallet[recipient]) {
require(_balances[recipient] <= maxWallet, "Max wallet limit reached");
}
emit Transfer(sender, recipient, amountReceived);
return true;
}
function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
if(sender == pair){
buyFees();
if (tradingStartBlock != 0 && block.number < tradingStartBlock + meditation) {
heathens[recipient] = true;
}
}
if(recipient == pair){
sellFees();
if (doBotProtection) {
require(!heathens[sender], "Heathen!");
}
}
if(shouldSwapBack()){
swapBack();
}
_balances[sender] = _balances[sender] - amount;
uint256 amountReceived = shouldTakeFee(sender) ? takeFee(recipient, amount) : amount;
_balances[recipient] = _balances[recipient] + amountReceived;
if (!excludedFromMaxWallet[recipient]) {
require(_balances[recipient] <= maxWallet, "Max wallet limit reached");
}
emit Transfer(sender, recipient, amountReceived);
return true;
}
function _basicTransfer(address sender, address recipient, uint256 amount) internal returns (bool) {
_balances[sender] = _balances[sender] - amount;
_balances[recipient] = _balances[recipient] + (amount);
emit Transfer(sender, recipient, amount);
return true;
}
function buyFees() internal{
liquidityFee = BuyliquidityFee;
marketingFee = BuymarketingFee;
burnFee = BuyburnFee;
totalFee = BuytotalFee;
}
function sellFees() internal{
liquidityFee = SellliquidityFee;
marketingFee = SellmarketingFee;
burnFee = SellburnFee;
totalFee = SelltotalFee;
}
function shouldTakeFee(address sender) internal view returns (bool) {
return !isFeeExempt[sender];
}
function takeFee(address sender, uint256 amount) internal returns (uint256) {
uint256 feeAmount = amount / 100 * (totalFee);
_balances[address(this)] = _balances[address(this)] + (feeAmount);
emit Transfer(sender, address(this), feeAmount);
return amount - (feeAmount);
}
function shouldSwapBack() internal view returns (bool) {
return msg.sender != pair
&& !inSwap
&& swapEnabled
&& _balances[address(this)] >= swapThreshold;
}
function manualSwapBack() external onlyOwner {
swapBack();
}
function swapBack() internal swapping {
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= maxSwapSize){
tokensToSell = maxSwapSize;
}
else{
tokensToSell = contractTokenBalance;
}
uint256 amountToLiquify = tokensToSell / (totalFee) * (liquidityFee) / (2);
uint256 amountToSwap = tokensToSell - (amountToLiquify);
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = WKEK;
uint256 balanceBefore = address(this).balance;
router.swapExactTokensForETHSupportingFeeOnTransferTokens(
amountToSwap,
0,
path,
address(this),
block.timestamp
);
uint256 amountKEK = address(this).balance - (balanceBefore);
uint256 totalKEKFee = totalFee - (liquidityFee / (2));
uint256 amountKEKLiquidity = amountKEK * (liquidityFee) / (totalKEKFee) / (2);
uint256 amountKEKMarketing = amountKEK - amountKEKLiquidity;
uint256 amountKEKburn = amountKEK - amountKEKLiquidity - amountKEKMarketing;
require(MarketingSuccess, "receiver rejected WKEK transfer");
require(burnSuccess, "burn problem");
addLiquidity(amountToLiquify, amountKEKLiquidity);
}
function swapBack() internal swapping {
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= maxSwapSize){
tokensToSell = maxSwapSize;
}
else{
tokensToSell = contractTokenBalance;
}
uint256 amountToLiquify = tokensToSell / (totalFee) * (liquidityFee) / (2);
uint256 amountToSwap = tokensToSell - (amountToLiquify);
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = WKEK;
uint256 balanceBefore = address(this).balance;
router.swapExactTokensForETHSupportingFeeOnTransferTokens(
amountToSwap,
0,
path,
address(this),
block.timestamp
);
uint256 amountKEK = address(this).balance - (balanceBefore);
uint256 totalKEKFee = totalFee - (liquidityFee / (2));
uint256 amountKEKLiquidity = amountKEK * (liquidityFee) / (totalKEKFee) / (2);
uint256 amountKEKMarketing = amountKEK - amountKEKLiquidity;
uint256 amountKEKburn = amountKEK - amountKEKLiquidity - amountKEKMarketing;
require(MarketingSuccess, "receiver rejected WKEK transfer");
require(burnSuccess, "burn problem");
addLiquidity(amountToLiquify, amountKEKLiquidity);
}
function swapBack() internal swapping {
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= maxSwapSize){
tokensToSell = maxSwapSize;
}
else{
tokensToSell = contractTokenBalance;
}
uint256 amountToLiquify = tokensToSell / (totalFee) * (liquidityFee) / (2);
uint256 amountToSwap = tokensToSell - (amountToLiquify);
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = WKEK;
uint256 balanceBefore = address(this).balance;
router.swapExactTokensForETHSupportingFeeOnTransferTokens(
amountToSwap,
0,
path,
address(this),
block.timestamp
);
uint256 amountKEK = address(this).balance - (balanceBefore);
uint256 totalKEKFee = totalFee - (liquidityFee / (2));
uint256 amountKEKLiquidity = amountKEK * (liquidityFee) / (totalKEKFee) / (2);
uint256 amountKEKMarketing = amountKEK - amountKEKLiquidity;
uint256 amountKEKburn = amountKEK - amountKEKLiquidity - amountKEKMarketing;
require(MarketingSuccess, "receiver rejected WKEK transfer");
require(burnSuccess, "burn problem");
addLiquidity(amountToLiquify, amountKEKLiquidity);
}
(bool MarketingSuccess,) = payable(marketingFeeReceiver).call{value: amountKEKMarketing, gas: 30000}("");
(bool burnSuccess,) = payable(burnFeeReceiver).call{value: amountKEKburn, gas: 30000}("");
function addLiquidity(uint256 tokenAmount, uint256 KEKAmount) private {
if(tokenAmount > 0){
address(this),
tokenAmount,
0,
0,
autoLiquidityReceiver,
block.timestamp
);
emit AutoLiquify(KEKAmount, tokenAmount);
}
}
function addLiquidity(uint256 tokenAmount, uint256 KEKAmount) private {
if(tokenAmount > 0){
address(this),
tokenAmount,
0,
0,
autoLiquidityReceiver,
block.timestamp
);
emit AutoLiquify(KEKAmount, tokenAmount);
}
}
router.addLiquidityETH{value: KEKAmount}(
function checkSwapThreshold() external view returns (uint256) {
return swapThreshold;
}
function isNotInSwap() external view returns (bool) {
return !inSwap;
}
function viewmaxWallet() external view returns (uint) {
return maxWallet;
}
function setBuyFees(uint256 _liquidityFee, uint256 _marketingFee, uint256 _burnFee) external onlyOwner {
BuyliquidityFee = _liquidityFee;
BuymarketingFee = _marketingFee;
BuyburnFee = _burnFee;
BuytotalFee = _liquidityFee + _marketingFee + _burnFee;
}
function setSellFees(uint256 _liquidityFee, uint256 _marketingFee, uint256 _burnFee) external onlyOwner {
SellliquidityFee = _liquidityFee;
SellmarketingFee = _marketingFee;
SellburnFee = _burnFee;
SelltotalFee = _liquidityFee + _marketingFee + _burnFee;
}
function setTotalFees(uint256 _liquidityFee, uint256 _marketingFee, uint256 _burnFee) external onlyOwner {
liquidityFee = _liquidityFee;
marketingFee = _marketingFee;
burnFee = _burnFee;
totalFee = _liquidityFee + _marketingFee + _burnFee;
}
function setFeeReceivers(address _autoLiquidityReceiver, address _marketingFeeReceiver, address _burnFeeReceiver) external onlyOwner {
autoLiquidityReceiver = _autoLiquidityReceiver;
marketingFeeReceiver = _marketingFeeReceiver;
burnFeeReceiver = _burnFeeReceiver;
}
function setSwapBackSettings(bool _enabled, uint256 _percentage_min_base10000, uint256 _percentage_max_base10000) external onlyOwner {
swapEnabled = _enabled;
swapThreshold = _totalSupply / (10000) * (_percentage_min_base10000);
maxSwapSize = _totalSupply / (10000) * (_percentage_max_base10000);
}
function setIsFeeExempt(address holder, bool exempt) external onlyOwner {
isFeeExempt[holder] = exempt;
}
function setMaxWallet(uint _maxWallet) external onlyOwner {
maxWallet = _maxWallet;
}
function rescueToken(address tokenAddress, uint256 tokens) public onlyOwner returns (bool success) {
return IERC20(tokenAddress).transfer(msg.sender, tokens);
}
function clearStuckBalance(uint256 amountPercentage) external onlyOwner {
uint256 amountKEK = address(this).balance;
payable(msg.sender).transfer(amountKEK * amountPercentage / 100);
}
uint256 tradingStartBlock = 0;
function enableTrading(uint256 tokensForLiquidity) external payable onlyOwner {
require(!swapEnabled, "trading already enabled");
pair = IDEXFactory(router.factory()).createPair(WKEK, address(this));
excludedFromMaxWallet[pair] = true;
excludedFromMaxWallet[address(router)] = true;
excludedFromMaxWallet[router.factory()] = true;
_balances[msg.sender] = _balances[msg.sender] - tokensForLiquidity;
_balances[address(this)] = _balances[address(this)] + tokensForLiquidity;
_allowances[address(this)][address(router)] = type(uint256).max;
IERC20(pair).approve(address(router), type(uint256).max);
swapEnabled = true;
tradingStartBlock = block.number;
}
event AutoLiquify(uint256 amountKEK, uint256 amountTokens);
router.addLiquidityETH{value: msg.value}(address(this), tokensForLiquidity, 0, 0, owner(), block.timestamp);
}
| 16,368,672 | [
1,
40,
6372,
5782,
281,
5782,
281,
22686,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1842,
353,
467,
654,
39,
3462,
16,
14223,
6914,
288,
203,
565,
1758,
5381,
2030,
1880,
273,
374,
92,
12648,
12648,
12648,
12648,
2787,
72,
41,
69,
40,
31,
203,
565,
1758,
5381,
18449,
273,
374,
92,
12648,
12648,
12648,
12648,
12648,
31,
203,
565,
1758,
5381,
678,
6859,
47,
273,
374,
20029,
27,
449,
39,
1105,
3461,
17156,
24,
42,
2539,
3600,
70,
9401,
40,
28,
38,
72,
40,
26,
2733,
9036,
37,
73,
31777,
1403,
15168,
31,
203,
203,
565,
533,
225,
389,
529,
273,
315,
3401,
47,
3839,
14432,
7010,
565,
533,
225,
389,
7175,
273,
4662,
10462,
14432,
203,
565,
2254,
28,
225,
389,
31734,
273,
374,
31,
203,
565,
2254,
5034,
389,
4963,
3088,
1283,
273,
2130,
12648,
12648,
31,
203,
7010,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
389,
70,
26488,
31,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
389,
5965,
6872,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
1071,
353,
14667,
424,
5744,
31,
203,
7010,
565,
2254,
5034,
1071,
4501,
372,
24237,
14667,
31,
203,
565,
2254,
5034,
1071,
13667,
310,
14667,
31,
203,
565,
2254,
5034,
1071,
18305,
14667,
31,
203,
565,
2254,
5034,
1071,
2078,
14667,
31,
203,
7010,
565,
2254,
5034,
1071,
605,
9835,
549,
372,
24237,
14667,
565,
273,
374,
31,
203,
565,
2254,
5034,
1071,
605,
89,
2942,
1313,
21747,
14667,
565,
273,
374,
31,
203,
565,
2254,
5034,
1071,
605,
9835,
70,
321,
14667,
273,
374,
31,
203,
565,
2254,
2
] |
pragma solidity ^0.4.18;
import "./TokenInterface.sol";
import "./ClientInterface.sol";
import "./SafeMath.sol";
/**
@title DCourt Arbitration contract
@author Ihab McShea Nour Haridy
*/
contract DCArbitration {
using SafeMath for uint256;
DCTInterface DCToken;
/*
Variables
*/
uint256 round;
uint256 caseCounter;
uint256 RoundReward;
uint256 collateral;
uint256 roundsPerHalving;
uint256 votingPeriod;
uint256 unlockingPeriod;
uint256 minTrialPeriod;
uint256 challengingPeriod;
uint256 roundWeight;
uint256 blocksPerRound;
uint256 genesisBlock;
uint8 witnessCount;
uint8 maxWitnesses;
uint256 courtCouncilPool;
struct Witness {
address addr;
string name;
uint256 reportCount;
uint256[] reports;
}
struct spamReport{
address submitter;
uint256 caseID;
address accuser;
bool verdict;
}
mapping(address => uint256) public delegates;
mapping(address => address) public voters;
mapping (uint => Witness) public witnesses;
mapping(uint256 => mapping(uint256 => bool)) witnessVote;
mapping(uint256 => spamReport) reportedCases;
mapping(uint => uint) reportVotes;
mapping (address => uint) public witnessRanks;
/*
structs
*/
struct Client{
bytes32 ToA;
uint256 trialDuration;
string URL;
}
struct Case{
address accuser;
address defendant;
address client;
uint256 block;
phase _phase;
string title;
evidence[] _evidence;
uint256 voteWeight;
uint256 ayes;
uint256 nayes;
uint256 round;
uint256 trialDuration;
uint256 collateral;
bool decided;
bool spam;
bool verdict;
}
struct evidence{
string body;
address author;
}
struct juror{
uint256 deposit;
uint256 round;
uint256 remaining;
uint256 activeCases;
uint256 caseCount;
uint256[] cases;
}
struct Vote{
bytes32 _hash;
uint256 amount;
string nonce;
bool decision;
uint256 caseID;
bool unlocked;
bool claimed; //Rewarded or penalized.
}
struct Round{
uint256 roundWeight;
uint256 caseCount;
uint256 reportCount;
}
/*
modifiers
*/
modifier onlyWhenOwner(){
require(DCToken.getOwner() == address(this));
_;
}
modifier onlyContract(){
require(isContract(msg.sender));
_;
}
modifier onlyCaseParty(uint256 _caseID){
require(cases[_caseID].defendant == msg.sender || cases[_caseID].accuser == msg.sender);
_;
}
modifier onlyJuror(){
// require(jurors[msg.sender].round.add(2) <= round);
_;
}
modifier onlyWitness {
require(witnessRanks[msg.sender] > 0);
_;
}
/*
Enumerators
*/
enum phase {
TRIAL,
VOTING,
UNLOCKING,
FINAL
}
/*
mappings
*/
mapping (address => Client) clients;
mapping(uint256 => Case) cases;
mapping (address => juror) jurors;
mapping (uint256 => Round) rounds;
mapping (address => mapping(uint256 => Vote)) votes;
mapping (address => uint256) frozenBalance;
/*
events
*/
event Registration(address indexed addr, bytes32 ToA, string URL);
event newCase(address accuser,
address defendant,
address client,
uint256 block,
string title,
string statement
);
event newEvidence(string body, address author, uint256 caseID);
/*
Functions
*/
function DCArbitration(address DCTAddress, uint256 _votingPeriod, uint256 _minTrialPeriod, uint256 _roundReward, uint256 _blocksPerRound, uint256 _roundsPerHalving, uint256 _collateral, uint256 _challengingPeriod, uint8 _maxWitnesses) public{
DCToken = DCTInterface(DCTAddress);
votingPeriod = _votingPeriod;
minTrialPeriod = _minTrialPeriod;
RoundReward = _roundReward;
blocksPerRound = _blocksPerRound;
unlockingPeriod = 5;
roundsPerHalving = _roundsPerHalving;
genesisBlock = block.number;
collateral = _collateral;
challengingPeriod = _challengingPeriod;
maxWitnesses = _maxWitnesses;
}
/**
@notice Register a decentralized application on the Dcourt system, called by the smart contract of the decentralized application.
@dev You must call this function from your dApp smart contract in order to be able to build it on top of Dcourt.
@param _ToA the hash of terms of agreement
@param _URL the address of the dApp.
@return {
"registered": "if registered"
}
*/
function register(bytes32 _ToA, string _URL) public onlyWhenOwner returns(bool registered){
require(clients[msg.sender].trialDuration == 0);
clients[msg.sender].ToA = _ToA;
clients[msg.sender].URL = _URL;
emit Registration(msg.sender, _ToA, _URL);
return true;
}
event Filed(address indexed _accuser, address indexed _defendant, string _statement, string _title);
/**
@notice File a case from a dApp to the Dcourt system
@dev You should implement a "fileCase" function in your smart contract which can be invoked by the accuser
@param _defendant the address of the defendant
@param _statement the opening statement of the case, also considered the first body of evidence
@param _title the title of the case. should be hard-coded in your contract.
@param trialDuration the duration in which case parties can submit evidence, should be at least as long as the global duration
@return {
"_caseID": "the ID of the filed case"
}
*/
function fileCase(address _defendant, uint256 trialDuration, string _statement, string _title) public returns(uint256 _caseID){
require(trialDuration >= minTrialPeriod);
caseCounter++;
Case storage filedCase = cases[caseCounter];
filedCase.client = msg.sender;
filedCase.accuser = tx.origin;
filedCase.defendant = _defendant;
filedCase.block = block.number;
filedCase.trialDuration = trialDuration;
// evidence storage _evidence = filedCase._evidence[0];
// _evidence.body = _statement;
// _evidence.author = tx.origin;
filedCase.title = _title;
filedCase._phase = phase.TRIAL;
filedCase.collateral = collateral;
emit newCase(tx.origin,
_defendant,
msg.sender,
block.number,
_title,
_statement
);
frozenBalance[tx.origin] = frozenBalance[tx.origin].add(collateral);
DCToken.burn(tx.origin, collateral);
return caseCounter;
}
function unfreezeCollateral(uint256 _caseID){
require(block.number > cases[_caseID].block + clients[cases[_caseID].client].trialDuration + votingPeriod + unlockingPeriod + challengingPeriod && cases[_caseID].spam == false);
DCToken.mint(cases[_caseID].accuser, (cases[_caseID].collateral/2));
}
event Delegation(address indexed voter, address indexed delegate, uint256 balance);
function increaseVote(address _voter, uint256 _amount){
delegates[voters[_voter]] = delegates[voters[_voter]].add(_amount);
emit Delegation(_voter, voters[msg.sender], DCToken.balanceOf(msg.sender));
}
function decreaseVote(address _voter, uint256 _amount){
delegates[voters[_voter]] = delegates[voters[_voter]].sub(_amount);
emit Delegation(_voter, voters[_voter], DCToken.balanceOf(msg.sender));
}
function eligibleForWitness(address _delegate) public view returns (bool) {
return delegates[_delegate] > delegates[witnesses[witnessCount].addr];
}
event Stepdown(address indexed _witness, string _name, uint rank);
event NewWitness(address indexed _witness, string _name, uint rank);
function witnessStepdown() public onlyWitness returns (bool) {
uint rank = witnessRanks[msg.sender];
Witness memory thisWitness = witnesses[rank];
delete witnesses[rank];
witnessRanks[msg.sender] = 0;
if(rank == witnessCount) return true; // If this the last rank, skipping the next loop
for (uint i = rank+1; i < witnessCount+1; i++){ // Move up each witness of a lower rank
witnessRanks[witnesses[i-1].addr] = witnessRanks[witnesses[i].addr];
witnesses[i-1] = witnesses[i];
}
witnessRanks[witnesses[witnessCount].addr] = 0; // Last witness seat must become available after witness stepdown
delete witnesses[witnessCount];
emit Stepdown(msg.sender, thisWitness.name, rank);
return true;
}
function becomeWitness(string _name) public returns (bool) {
uint256 weight = delegates[msg.sender];
require(weight > 0 && ( witnessRanks[msg.sender] > 21 || witnessRanks[msg.sender] ==0));
uint rank;
if(witnessCount == 0 ){
rank = 1;
}else{
for (uint i = witnessCount; i > 0 ; i--){ // iterate on the witnesses from the lowest to highest rank to save as much gas as possible. Loop is bounded by witnessCount
// if(witnesses[i].addr == msg.sender) break; // if message sender is already this witness, throw
address witnessAddr = witnesses[i].addr;
uint256 witnessWeight = delegates[witnessAddr];
if(witnessWeight == 0 && i != 1) continue; //if there is no delegate at this rank and this is not the highest rank then skip this iteration
if(witnessWeight > weight) break; // if this witness has a higher weight than message sender, break the loop
if(i == maxWitnesses){ // if this is the lowest witness rank, remove this delegate from witnesses
witnessRanks[witnessAddr] = 0;
delete witnesses[i];
}else{
witnesses[i+1] = witnesses[i]; // Move this witness down 1 rank
witnessRanks[witnesses[i+1].addr] = i;
}
rank = i;
}
}
require(rank > 0); // Require that message sender has a rank after the loop
if(rank > 0 && witnessCount < 21){
witnessCount +=1;
}
witnessRanks[msg.sender] = rank;
Witness storage newWitness = witnesses[rank];
newWitness.name = _name;
newWitness.addr = msg.sender;
emit NewWitness(msg.sender, _name, rank);
return true;
}
function signal(address _delegate) public {
require(DCToken.balanceOf(msg.sender) > 0);
require(_delegate != address(0));
require(voters[msg.sender] != _delegate);
if(voters[msg.sender] != address(0)){
delegates[voters[msg.sender]] = delegates[voters[msg.sender]].sub(DCToken.balanceOf(msg.sender));
}
delegates[_delegate] = delegates[_delegate].add(DCToken.balanceOf(msg.sender));
voters[msg.sender] = _delegate;
emit Delegation(msg.sender, _delegate, DCToken.balanceOf(msg.sender));
}
function delegatePercentage(address _delegate) public view returns (uint256) {
if(delegates[_delegate] == DCToken.totalSupply()) return 100;
return (delegates[_delegate].div(DCToken.totalSupply())).mul(100);
}
function getRanking(address account) public view returns(uint){
return witnessRanks[account];
}
function decideReport(uint256 _caseID){
uint casePeriod = cases[_caseID].block + cases[_caseID].trialDuration + votingPeriod + unlockingPeriod;
require(witnessRanks[msg.sender] > 0 && witnessRanks[msg.sender] < 22);
require((block.number > casePeriod) && (block.number < casePeriod + challengingPeriod));
witnessVote[witnessRanks[msg.sender]][witnesses[witnessRanks[msg.sender]].reportCount] = true;
witnesses[witnessRanks[msg.sender]].reportCount = witnesses[witnessRanks[msg.sender]].reportCount.add(1);
reportVotes[_caseID] = reportVotes[_caseID].add(1);
witnesses[witnessRanks[msg.sender]].reports.push(_caseID);
if(reportVotes[_caseID] > (witnessCount/2)){
cases[_caseID].spam = true;
}
}
function claimWitnessReward(){
require(witnessRanks[msg.sender] > 0 && witnessRanks[msg.sender] < 22);
uint256 NCases = witnesses[witnessRanks[msg.sender]].reportCount;
uint256 currentRound;
int256 Claimed;
currentRound = uint((block.number.sub(genesisBlock)).div(blocksPerRound)) +1;
for(uint256 i=0; i < NCases; i++){
uint256 individualRR;
uint256 ten = 10**4;
uint256 halvings = (cases[witnesses[witnessRanks[msg.sender]].reports[i]].round / roundsPerHalving);
individualRR = ((10**4)/2**halvings) * (RoundReward/5);
individualRR /= 10**4;
uint256 totalPay = individualRR + courtCouncilPool;
uint256 voterWeight = (10**8) / reportVotes[witnesses[witnessRanks[msg.sender]].reports[i]];
Claimed += int(((voterWeight * (totalPay / rounds[currentRound-1].reportCount)))/10**8);
}
DCToken.mint(msg.sender, uint256(Claimed));
delete witnesses[witnessRanks[msg.sender]].reports;
witnesses[witnessRanks[msg.sender]].reportCount = 0;
}
event Reported(uint256 _caseID, address reporter);
function reportCase(uint256 _caseID) public returns(bool reported){
require(reportedCases[_caseID].accuser == address(0));
spamReport storage reportedCase = reportedCases[_caseID];
reportedCase.submitter = msg.sender;
reportedCase.caseID = _caseID;
reportedCase.accuser = cases[_caseID].accuser;
rounds[(block.number.sub(genesisBlock)).div(blocksPerRound)].reportCount = rounds[(block.number.sub(genesisBlock)).div(blocksPerRound)].caseCount.add(1);
emit Reported(reportedCase.caseID, reportedCase.submitter);
return true;
}
/**
@notice Deposit the user's funds as collateral before voting
@return {
"done": "if done"
}
*/
function deposit() onlyWhenOwner public returns(bool done){
uint256 balance = DCToken.balanceOf(msg.sender);
require(balance > 0);
require(jurors[msg.sender].deposit == 0);
jurors[msg.sender].deposit = balance;
jurors[msg.sender].remaining = balance;
DCToken.freeze(msg.sender, true);
return true;
}
/**
@notice Register a decentralized application on the Dcourt system, called by the smart contract of the decentralized application.
@return {
"registered": "if registered"
}
*/
function withdraw() onlyJuror onlyWhenOwner public returns(bool done){
require(jurors[msg.sender].activeCases == 0);
DCToken.freeze(msg.sender, false);
return true;
}
function getVoteWeight(uint256 _caseID) public view returns(uint256 vote){
return cases[_caseID].voteWeight;
}
/**
@notice Generate the vote hash
@param nonce the nonce string used
@param decision Guilty (true) / Not Guilty (false)
@return {
"_hash": "the resulting hash"
}
*/
function generateHash(string nonce, bool decision) public pure returns(bytes32 _hash){
uint8 dec;
if(decision == true)
dec = 1;
else
dec = 0;
return keccak256(dec,nonce);
}
event Voted(address indexed voter, uint256 _caseID);
/**
@notice Vote guilty/not guilty on a Dcourt case
@param _caseID ID of the case on the Dcourt system
@param hash the hash combining the nonce with the juror's decision
@param _amount the amount bet to vote on the case
@return {
"voted": "if voted"
}
*/
function vote(uint256 _caseID, bytes32 hash, uint256 _amount) onlyJuror onlyWhenOwner public returns(bool voted){
require((block.number >= cases[_caseID].block + cases[_caseID].trialDuration) && block.number < cases[_caseID].block + cases[_caseID].trialDuration + votingPeriod);
require(votes[msg.sender][_caseID].amount == 0);
require(jurors[msg.sender].remaining.sub(_amount) >= 0 );
jurors[msg.sender].remaining = jurors[msg.sender].remaining.sub(_amount);
votes[msg.sender][jurors[msg.sender].activeCases].caseID = _caseID;
votes[msg.sender][jurors[msg.sender].activeCases].amount = _amount;
votes[msg.sender][jurors[msg.sender].activeCases]._hash = hash;
cases[_caseID].voteWeight = cases[_caseID].voteWeight.add(_amount);
if(cases[_caseID]._phase != phase.VOTING){
cases[_caseID]._phase = phase.VOTING;
}
jurors[msg.sender].caseCount = jurors[msg.sender].caseCount.add(1);
jurors[msg.sender].activeCases = jurors[msg.sender].activeCases.add(1);
emit Voted(msg.sender, _caseID);
return true;
}
function getV(bool decision, uint256 _caseID) public view returns(uint256){
if(decision){
return cases[_caseID].ayes;
}else{
return cases[_caseID].nayes;
}
return cases[_caseID].nayes;
}
/**
@notice Unlock the vote in the unlocking period
@param decision the decision initially submitted by the juror
@param nonce the nonce originally chosen by the juror
@param _caseID the ID of the case on the Dcourt system
@return {
"unlocked": "if unlocked"
}
*/
function unlock(bool decision, string nonce, uint256 _caseID) onlyJuror public returns(bool unlocked){
require(votes[msg.sender][_caseID].amount > 0);
require((block.number >= cases[_caseID].block + cases[_caseID].trialDuration + votingPeriod) && (block.number < cases[_caseID].block + cases[_caseID].trialDuration + votingPeriod + unlockingPeriod));
require(votes[msg.sender][_caseID].unlocked == false);
uint8 dec;
if(decision == true){
dec = 1;
}else{
dec = 0;
}
bytes32 _hash = keccak256(dec,nonce);
require(_hash == votes[msg.sender][_caseID]._hash);
jurors[msg.sender].cases.push(_caseID);
if(decision){
cases[_caseID].ayes = cases[_caseID].ayes.add(votes[msg.sender][_caseID].amount);
}else{
cases[_caseID].nayes = cases[_caseID].nayes.add(votes[msg.sender][_caseID].amount);
}
votes[msg.sender][_caseID].unlocked = true;
votes[msg.sender][_caseID].nonce = nonce;
votes[msg.sender][_caseID].decision = decision;
jurors[msg.sender].activeCases = jurors[msg.sender].activeCases.sub(1);
return true;
}
/**
@notice Finalize case after unlocking period. Called only once
@param _caseID the ID of the case on the Dcourt system
@return {
"finalized": "if finalized"
}
*/
function finalize(uint256 _caseID) public onlyWhenOwner returns(bool finalized){
require(block.number > cases[_caseID].block + cases[_caseID].trialDuration + votingPeriod + unlockingPeriod);
require(cases[_caseID].decided == false);
bool verdict = cases[_caseID].ayes > cases[_caseID].nayes;
ClientContract cc = ClientContract(cases[_caseID].client);
cc.onVerdict(_caseID, verdict);
cases[_caseID].decided = true;
cases[_caseID].verdict = verdict;
rounds[(block.number.sub(genesisBlock)).div(blocksPerRound)].roundWeight = rounds[(block.number.sub(genesisBlock)).div(blocksPerRound)].roundWeight.add(cases[_caseID].voteWeight);
rounds[(block.number.sub(genesisBlock)).div(blocksPerRound)].caseCount = rounds[(block.number.sub(genesisBlock)).div(blocksPerRound)].caseCount.add(1);
// rounds[(block.number.sub(genesisBlock)).div(blocksPerRound)].roundWeight = roundWeights[(block.number.sub(genesisBlock)).roundWeight.div(blocksPerRound)].add(cases[_caseID].voteWeight);
cases[_caseID].round = (block.number.sub(genesisBlock)).div(blocksPerRound);
return verdict;
}
event rewardClaimed(bool decided, uint256 round, uint256 currentRound, uint256 test);
event loss(uint256 loss);
/**
@notice Claim the reward after the round
@return {
"_claimed": "if claimed"
}
*/
function claimReward() public onlyJuror onlyWhenOwner returns(bool claimed){ // optional iterations argument
require(jurors[msg.sender].caseCount > 0); // activeCases >> caseCount
uint256 NCases = jurors[msg.sender].caseCount;
uint256 currentRound;
int256 Claimed;
currentRound = uint((block.number.sub(genesisBlock)).div(blocksPerRound)) +1;
for(uint256 i=0; i < NCases; i++){
//emit rewardClaimed(555);
uint256 individualRR;
if(cases[jurors[msg.sender].cases[i]].decided == false || cases[jurors[msg.sender].cases[i]].spam == true || cases[jurors[msg.sender].cases[i]].round == currentRound) continue;
// uint256 tokenShare = ;
uint256 ten = 10**4;
uint256 halvings = (cases[jurors[msg.sender].cases[i]].round / roundsPerHalving);
individualRR = ((10**4)/2**halvings) * ((4 * RoundReward)/5);
individualRR /= 10**4;
uint256 voterWeight = (votes[msg.sender][jurors[msg.sender].cases[i]].amount * 10**8) / cases[jurors[msg.sender].cases[i]].voteWeight;
if(cases[jurors[msg.sender].cases[i]].verdict == votes[msg.sender][jurors[msg.sender].cases[i]].decision){
// Claimed += int(((votes[msg.sender][jurors[msg.sender].cases[i]].amount / cases[jurors[msg.sender].cases[i]].voteWeight ) * (individualRR/rounds[currentRound-1].caseCount)));
Claimed += int((((((votes[msg.sender][jurors[msg.sender].cases[i]].amount)*10**8 ) /cases[jurors[msg.sender].cases[i]].voteWeight * rounds[currentRound-1].caseCount))/10**7 * individualRR)/10);
//DCToken.mint(msg.sender, Claimed);
}else{ //75% threshold?
//Claimed -= int((voterWeight * (individualRR/rounds[currentRound-1].caseCount)));
//Claimed -= int((votes[msg.sender][jurors[msg.sender].cases[i]].amount * 10**10)/cases[jurors[msg.sender].cases[i]].voteWeight * rounds[currentRound-1].caseCount) * individualRR;
//Claimed -= int(((((votes[msg.sender][jurors[msg.sender].cases[i]].amount * 10)/(cases[jurors[msg.sender].cases[i]].voteWeight * rounds[currentRound-1].caseCount))) * individualRR));
Claimed -= int((((((votes[msg.sender][jurors[msg.sender].cases[i]].amount)*10**8 ) /cases[jurors[msg.sender].cases[i]].voteWeight * rounds[currentRound-1].caseCount))/10**7 * individualRR)/10);
// ((Vweight*10**10/Tvotes*Nc) * RR
}
}
if(Claimed > 0){
DCToken.mint(msg.sender, uint256(Claimed));
}else if(Claimed < 0){
if(uint256(Claimed) < DCToken.balanceOf(msg.sender) ){
DCToken.burn(msg.sender, uint256(Claimed/2));
courtCouncilPool = courtCouncilPool.add(uint(Claimed/2));
}else{
uint256 jurorBalance = DCToken.balanceOf(msg.sender);
DCToken.burn(msg.sender, uint256(jurorBalance/2));
courtCouncilPool = courtCouncilPool.add(uint(jurorBalance/2));
}
}
//Remove the juror's cases in the past round
delete jurors[msg.sender].cases;
}
/**
@notice Add evidence to the case. Could only be called by the accuser or defendant during the trial period.
@param _caseID the ID of the case on the Dcourt system
@param _body the details of the evidence
@return {
"added": "if added"
}
*/
function addEvidence(uint256 _caseID, string _body) public onlyWhenOwner onlyCaseParty(_caseID) returns (bool added){
require(cases[_caseID].client != address(0));
require(block.number < cases[_caseID].block + cases[_caseID].trialDuration);
cases[_caseID]._evidence.length+=1;
evidence storage _evidence = cases[_caseID]._evidence[cases[_caseID]._evidence.length];
_evidence.body = _body;
_evidence.author = msg.sender;
emit newEvidence(_body, msg.sender, _caseID);
return true;
}
function burnAll(address _addr){
DCToken.burnAll(_addr);
}
function burn(address _addr, uint256 qty){
DCToken.burn(_addr, qty);
}
/*
utils
*/
function isContract(address addr) private view returns (bool) {
uint size;
assembly {
size := extcodesize(addr)
}
return size > 0;
}
}
| Require that message sender has a rank after the loop
| require(rank > 0); | 14,087,301 | [
1,
8115,
716,
883,
5793,
711,
279,
6171,
1839,
326,
2798,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1377,
2583,
12,
11500,
405,
374,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-10-09
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
library Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_owner = address(0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_owner = newOwner; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
}
/**
* @dev A token holder contract that will allow a beneficiary to extract the
* tokens at predefined intervals. Tokens not claimed at payment epochs accumulate
* Modified version of Openzeppelin's TokenTimeLock
*/
contract Lock is Ownable {
using SafeMath for uint;
enum period {
second,
minute,
hour,
day,
week,
month, //inaccurate, assumes 30 day month, subject to drift
year,
quarter,//13 weeks
biannual//26 weeks
}
//The length in seconds for each epoch between payments
uint epochLength;
// ERC20 basic token contract being held
IERC20 private _token;
// beneficiary of tokens after they are released
address private _beneficiary;
uint periods;
//the size of periodic payments
uint paymentSize;
uint paymentsRemaining =0;
uint startTime =0;
uint beneficiaryBalance = 0;
function initialize(address tokenAddress, address beneficiary, uint duration,uint durationMultiple,uint p) public onlyOwner{
release();
require(paymentsRemaining == 0, 'cannot initialize during active vesting schedule'); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(duration>0 && p>0, 'epoch parameters must be positive');
_token = IERC20(tokenAddress); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_beneficiary = beneficiary; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
if(duration<=uint(period.biannual)){
if(duration == uint(period.second)){
epochLength = durationMultiple * 1 seconds; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}else if(duration == uint(period.minute)){
epochLength = durationMultiple * 1 minutes; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
else if(duration == uint(period.hour)){
epochLength = durationMultiple *1 hours; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}else if(duration == uint(period.day)){
epochLength = durationMultiple *1 days; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
else if(duration == uint(period.week)){
epochLength = durationMultiple *1 weeks; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}else if(duration == uint(period.month)){
epochLength = durationMultiple *30 days; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}else if(duration == uint(period.year)){
epochLength = durationMultiple *52 weeks; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}else if(duration == uint(period.quarter)){
epochLength = durationMultiple *13 weeks; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
else if(duration == uint(period.biannual)){
epochLength = 26 weeks; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
}
else{
epochLength = duration; //custom value //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
periods = p; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit Initialized(tokenAddress,beneficiary,epochLength,p); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function deposit (uint amount) public { //remember to ERC20.approve
require (_token.transferFrom(msg.sender,address(this),amount),'transfer failed'); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint balance = _token.balanceOf(address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
if(paymentsRemaining==0) //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
{
paymentsRemaining = periods; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
startTime = block.timestamp; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
paymentSize = balance/paymentsRemaining; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit PaymentsUpdatedOnDeposit(paymentSize,startTime,paymentsRemaining); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function getElapsedReward() public view returns (uint,uint,uint){
if(epochLength == 0) //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
return (0, startTime,paymentsRemaining); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint elapsedEpochs = (block.timestamp - startTime)/epochLength; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
if(elapsedEpochs==0)
return (0, startTime,paymentsRemaining); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
elapsedEpochs = elapsedEpochs>paymentsRemaining?paymentsRemaining:elapsedEpochs; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint newStartTime = block.timestamp;
uint newPaymentsRemaining = paymentsRemaining.sub(elapsedEpochs); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint balance =_token.balanceOf(address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint accumulatedFunds = paymentSize.mul(elapsedEpochs); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
return (beneficiaryBalance.add(accumulatedFunds>balance?balance:accumulatedFunds),newStartTime,newPaymentsRemaining); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function updateBeneficiaryBalance() private {
(beneficiaryBalance,startTime, paymentsRemaining) = getElapsedReward();
}
function changeBeneficiary (address beneficiary) public onlyOwner{
require (paymentsRemaining == 0, 'TokenTimelock: cannot change beneficiary while token balance positive'); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_beneficiary = beneficiary; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @return the beneficiary of the tokens.
*/
function beneficiary() public view returns (address) {
return _beneficiary; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @notice Transfers tokens held by timelock to beneficiary.
*/
function release() public {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp >= startTime, "TokenTimelock: current time is before release time"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
updateBeneficiaryBalance();
uint amountToSend = beneficiaryBalance; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
beneficiaryBalance = 0; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
if(amountToSend>0)
require(_token.transfer(_beneficiary,amountToSend),'release funds failed'); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit FundsReleasedToBeneficiary(_beneficiary,amountToSend,block.timestamp); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
event PaymentsUpdatedOnDeposit(uint paymentSize,uint startTime, uint paymentsRemaining);
event Initialized (address tokenAddress, address beneficiary, uint duration,uint periods);
event FundsReleasedToBeneficiary(address beneficiary, uint value, uint timeStamp);
} | inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
| paymentsRemaining = periods; | 12,754,201 | [
1,
22170,
18708,
14939,
8350,
13255,
40,
6953,
17187,
478,
21163,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
2398,
25754,
11429,
273,
12777,
31,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.21;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract KahnAirDrop{
using SafeMath for uint256;
struct User{
address user_address;
uint signup_time;
uint256 reward_amount;
bool blacklisted;
uint paid_time;
uint256 paid_token;
bool status;
}
/* @dev Contract creator address */
address public owner;
/* @dev Assigned wallet where the remaining unclaim tokens to be return */
address public wallet;
/* @dev The minimum either in wei must received to execute the claim function */
uint256 public mineth = 0;
/* @dev The minimum either in wei must received to execute the claim function */
uint256 public minsignupeth = 0;
/* @dev Whether or not the contract is pause (in case of a problem is detected) */
bool public paused = false;
/* @dev Fixed amount payout for each bounty */
uint public maxSignup = 1000;
/* @dev allows direct signup */
bool public allowsSignup = true;
/* @dev bounty address */
address[] public bountyaddress;
/* @dev admin address */
address[] public adminaddress;
/* @dev staff address */
address[] public staffaddress;
/* @dev block time to start the contract */
uint public startTimes;
/* @dev block time to end the contract */
uint public endTimes;
/* @dev Whether or not the contract is blacklisted (in case of a problem is detected) */
bool public contractbacklist = false;
/* @dev Total Signup count */
uint public userSignupCount = 0;
/* @dev Total tokens claimed */
uint256 public userClaimAmt = 0;
/* @dev The token being distribute */
ERC20 public token;
/*
* @dev This set how the bounty reward will be paying out
* @param 0 = pay evenly
* @param 1 = pay fixed amount
* @param 2 = pay various amount
*/
uint public payStyle = 2;
/*
* @dev False = Free version, contract creator will received the ether
* @dev True = Paid version, client will received the ether
*/
bool public paidversion = true;
/* @dev Setup the payout method
* @param 0 = Enabled Signup Disabled Payout
* @param 1 = Disable Signup Disable Payout
* @param 2 = Disabled Signup Enable Payout
* @param 3 = Enabled Signup Enabled Payout
* @param 4 = Disabled Signup Immediate Payout
*/
uint public payoutNow = 4;
/* @dev Fixed amount payout for each bounty */
uint256 public fixPayAmt = 0;
/* @dev To record the different reward amount for each bounty */
mapping(address => User) public bounties;
/* @dev to include the bounty in the list */
mapping(address => bool) public signups;
/* @dev Store bounty address to blacklist */
mapping(address => bool) public blacklist;
/* @dev to check is the claim in the process */
mapping(address => bool) public isProcess;
/* @dev Admin with permission to manage the signed up bounty */
mapping (address => bool) public admins;
/* @dev Staff with permission to manage the signed up bounty */
mapping (address => bool) public staffs;
/**
* @dev Event for token distribution logging
* @param _address who claim the tokens
* @param _amount amount of tokens to be delivery
*/
event eTokenClaim(address indexed _address, uint256 _amount);
event eReClaimToken(uint256 _taBal, address _wallet, address _address);
event eWalletChange(address _wallet, address indexed _address);
event eUpdatePayout(uint _payStyle, uint _payoutNow, uint256 _fixPayAmt, bool _allowsSignup, address indexed _address);
event eUpdateStartEndTime(uint _startTimes, uint _endTimes, address indexed _address);
/*
* event eAddAdmin(address _newaddress, address indexed _byaddress);
* event eRemoveAdmin(address _newaddress, address indexed _byaddress);
* event eAddStaff(address _newaddress, address indexed _byaddress);
* event eRemoveStaff(address _newaddress, address indexed _byaddress);
* event eAddBounty(address _newaddress, address indexed _byaddress);
* event eRemoveBounty(address _address, address indexed _byaddress);
*/
/**
* @param _token Token smart contract address
* @param _wallet ETH address to reclaim unclaim tokens
*/
function KahnAirDrop(ERC20 _token, uint256 _min_eth, uint256 _minsignupeth, uint _paystyle, address _wallet, uint _starttimes, uint _endtimes, uint _payoutnow, uint256 _fixpayamt, uint _maxsignup, bool _allowssignup, bool _paidversion) public {
require(_token != address(0));
token = _token;
admins[msg.sender] = true;
adminaddress.push(msg.sender) -1;
owner = msg.sender;
mineth = _min_eth;
minsignupeth = _minsignupeth;
wallet = _wallet;
payStyle = _paystyle;
startTimes = _starttimes;
endTimes = _endtimes;
payoutNow = _payoutnow;
fixPayAmt = _fixpayamt;
maxSignup = _maxsignup;
allowsSignup = _allowssignup;
paidversion = _paidversion;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyAdmin {
require(admins[msg.sender]);
_;
}
modifier onlyStaffs {
require(admins[msg.sender] || staffs[msg.sender]);
_;
}
modifier ifNotPaused {
require(!paused);
_;
}
modifier ifNotStartExp {
require(now >= startTimes && now <= endTimes);
_;
}
modifier ifNotBlacklisted {
require(!contractbacklist);
_;
}
/*******************/
/* Owner Function **/
/*******************/
/* @dev Update Contract Configuration */
function ownerUpdateToken(ERC20 _token, address _wallet) public onlyOwner{
token = _token;
wallet = _wallet;
emit eWalletChange(wallet, msg.sender);
}
/* @dev Update Contract Configuration */
function ownerUpdateOthers(uint _maxno, bool _isBacklisted, uint256 _min_eth, uint256 _minsignupeth, bool _paidversion) public onlyOwner{
maxSignup = _maxno;
contractbacklist = _isBacklisted;
mineth = _min_eth;
minsignupeth = _minsignupeth;
paidversion = _paidversion;
}
/* @dev Owner Retrieve Contract Configuration */
function ownerRetrieveTokenDetails() view public onlyOwner returns(ERC20, address, uint256, uint256, bool){
return(token, wallet, token.balanceOf(this), userClaimAmt, contractbacklist);
}
/* @dev Owner Retrieve Contract Configuration */
function ownerRetrieveContractConfig2() view public onlyOwner returns(uint256, bool, uint, uint, uint, uint, uint256, uint, bool){
return(mineth, paidversion, payStyle, startTimes, endTimes, payoutNow, fixPayAmt, maxSignup, allowsSignup);
}
/*******************/
/* Admin Function **/
/*******************/
/* @dev Add admin to whitelist */
function addAdminWhitelist(address[] _userlist) public onlyOwner onlyAdmin{
require(_userlist.length > 0);
for (uint256 i = 0; i < _userlist.length; i++) {
address baddr = _userlist[i];
if(baddr != address(0)){
if(!admins[baddr]){
admins[baddr] = true;
adminaddress.push(baddr) -1;
}
}
}
}
/* @dev Remove admin from whitelist */
function removeAdminWhitelist(address[] _userlist) public onlyAdmin{
require(_userlist.length > 0);
for (uint256 i = 0; i < _userlist.length; i++) {
address baddr = _userlist[i];
if(baddr != address(0)){
if(admins[baddr]){
admins[baddr] = false;
}
}
}
}
/* @dev Add staff to whitelist */
function addStaffWhitelist(address[] _userlist) public onlyAdmin{
require(_userlist.length > 0);
for (uint256 i = 0; i < _userlist.length; i++) {
address baddr = _userlist[i];
if(baddr != address(0)){
if(!staffs[baddr]){
staffs[baddr] = true;
staffaddress.push(baddr) -1;
}
}
}
}
/* @dev Remove staff from whitelist */
function removeStaffWhitelist(address[] _userlist) public onlyAdmin{
require(_userlist.length > 0);
for (uint256 i = 0; i < _userlist.length; i++) {
address baddr = _userlist[i];
if(baddr != address(0)){
if(staffs[baddr]){
staffs[baddr] = false;
}
}
}
}
/* @dev Allow Admin to reclaim all unclaim tokens back to the specified wallet */
function reClaimBalance() public onlyAdmin{
uint256 taBal = token.balanceOf(this);
token.transfer(wallet, taBal);
emit eReClaimToken(taBal, wallet, msg.sender);
}
function adminUpdateWallet(address _wallet) public onlyAdmin{
require(_wallet != address(0));
wallet = _wallet;
emit eWalletChange(wallet, msg.sender);
}
function adminUpdateStartEndTime(uint _startTimes, uint _endTimes) public onlyAdmin{
require(_startTimes > 0);
require(_endTimes > 0);
startTimes = _startTimes;
endTimes = _endTimes;
emit eUpdateStartEndTime(startTimes, endTimes, msg.sender);
}
/* @dev Update Contract Configuration */
function adminUpdMinSign(uint256 _min_eth, uint256 _minsignupeth) public onlyAdmin{
if(paidversion){
mineth = _min_eth;
minsignupeth = _minsignupeth;
}
}
function adminUpdatePayout(uint _payStyle, uint _payoutNow, uint256 _fixPayAmt, bool _allowsSignup) public onlyAdmin{
payStyle = _payStyle;
payoutNow = _payoutNow;
fixPayAmt = _fixPayAmt;
allowsSignup = _allowsSignup;
emit eUpdatePayout(payStyle, payoutNow, fixPayAmt, allowsSignup, msg.sender);
}
/***************************/
/* Admin & Staff Function **/
/***************************/
/* @dev Admin/Staffs Update Contract Configuration */
/* @dev Add user to whitelist */
function signupUserWhitelist(address[] _userlist, uint256[] _amount) public onlyStaffs{
require(_userlist.length > 0);
require(_amount.length > 0);
for (uint256 i = 0; i < _userlist.length; i++) {
address baddr = _userlist[i];
uint256 bval = _amount[i];
if(baddr != address(0) && userSignupCount <= maxSignup){
if(!bounties[baddr].blacklisted && bounties[baddr].user_address != baddr){
signups[baddr] = true;
bountyaddress.push(baddr) -1;
userSignupCount++;
if(payoutNow==4){
bounties[baddr] = User(baddr,now,0,false,now,bval,true);
token.transfer(baddr, bval);
userClaimAmt = userClaimAmt.add(bval);
}else{
bounties[baddr] = User(baddr,now,bval,false,0,0,true);
}
}
}
}
}
/* @dev Remove user from whitelist */
function removeUserWhitelist(address[] _userlist) public onlyStaffs{
require(_userlist.length > 0);
for (uint256 i = 0; i < _userlist.length; i++) {
address baddr = _userlist[i];
if(baddr != address(0) && bounties[baddr].user_address == baddr){
bounties[baddr].status = false;
signups[baddr] = false;
userSignupCount--;
}
}
}
function updUserBlackList(address[] _addlist, address[] _removelist) public onlyStaffs{
if(_addlist.length > 0){
for (uint256 i = 0; i < _addlist.length; i++) {
address baddr = _addlist[i];
if(baddr != address(0) && !bounties[baddr].blacklisted){
bounties[baddr].blacklisted = true;
blacklist[baddr] = true;
}
}
}
if(_removelist.length > 0){ removeUserFromBlackList(_removelist); }
}
function removeUserFromBlackList(address[] _userlist) internal{
require(_userlist.length > 0);
for (uint256 i = 0; i < _userlist.length; i++) {
address baddr = _userlist[i];
if(baddr != address(0) && bounties[baddr].blacklisted){
bounties[baddr].blacklisted = false;
blacklist[baddr] = false;
}
}
}
/* @dev Update Multiple Users Reward Amount */
function updateMultipleUsersReward(address[] _userlist, uint256[] _amount) public onlyStaffs{
require(_userlist.length > 0);
require(_amount.length > 0);
for (uint256 i = 0; i < _userlist.length; i++) {
address baddr = _userlist[i];
uint256 bval = _amount[i];
if(baddr != address(0)){
if(bounties[baddr].user_address == baddr){
bounties[baddr].reward_amount = bval;
}else{
if(userSignupCount <= maxSignup){
bounties[baddr] = User(baddr,now,bval,false,0,0,true);
signups[baddr] = true;
bountyaddress.push(baddr) -1;
userSignupCount++;
}
}
}
}
}
/***************************/
/* Query Display Function **/
/***************************/
function adminRetrieveContractConfig() view public onlyStaffs returns(uint, uint, uint256, uint, bool, bool){
return(payStyle, payoutNow, fixPayAmt, maxSignup, allowsSignup, paidversion);
}
function adminRetrieveContractConfig2() view public onlyStaffs returns(uint256, uint256, address, uint, uint, uint){
return(mineth, minsignupeth, wallet, startTimes, endTimes, userSignupCount);
}
function adminRetrieveContractConfig3() view public onlyStaffs returns(ERC20, uint256, uint256, uint, uint){
uint256 taBal = token.balanceOf(this);
return(token, taBal,userClaimAmt, now, block.number);
}
/* @dev Check is the address is in Admin list */
function chkAdmin(address _address) view public onlyAdmin returns(bool){
return admins[_address];
}
/* @dev Check is the address is in Staff list */
function chkStaff(address _address) view public onlyAdmin returns(bool){
return staffs[_address];
}
/* @dev Return admin addresses list */
function getAllAdmin() view public onlyAdmin returns(address[]){
return adminaddress;
}
/* @dev Return staff addresses list */
function getAllStaff() view public onlyAdmin returns(address[]){
return staffaddress;
}
/* @dev Return list of bounty addresses */
function getBountyAddress() view public onlyStaffs returns(address[]){
return bountyaddress;
}
/*
* @dev Check is the user is in Signed up list
* @dev bool = address is in the signup mapping list
* @dev uint256 = the given bounty address reward entitlement amount
*/
function chkUserDetails(address _address) view public onlyStaffs returns(address,uint,uint256,bool,uint,uint256,bool){
require(_address != address(0));
return(bounties[_address].user_address, bounties[_address].signup_time, bounties[_address].reward_amount, bounties[_address].blacklisted, bounties[_address].paid_time, bounties[_address].paid_token, bounties[_address].status);
}
/***************************/
/* Main Contract Function **/
/***************************/
/* @dev Bounty send in either to execute the claim */
function () external payable ifNotStartExp ifNotPaused ifNotBlacklisted{
require(!blacklist[msg.sender]);
if(payoutNow == 0){
require(allowsSignup);
singleUserSignUp(msg.sender);
}else if(payoutNow == 1){
require(allowsSignup);
}else if(payoutNow == 2){
claimTokens(msg.sender);
}else if(payoutNow == 3){
claimImmediateTokens(msg.sender);
}
}
function singleUserSignUp(address _address) internal ifNotStartExp ifNotPaused ifNotBlacklisted {
if(userSignupCount <= maxSignup){
if(!signups[_address] && bounties[_address].user_address != _address && msg.value >= minsignupeth){
if(payoutNow != 1 || payoutNow != 2){
signups[_address] = true;
uint256 temrew = 0;
if(payStyle == 1){ temrew = fixPayAmt; }
bounties[_address] = User(_address,now,temrew,false,0,0,true);
signups[_address] = true;
bountyaddress.push(_address) -1;
userSignupCount++;
}
}
}
forwardWei();
}
/* @dev Bounty claim their reward tokens by sending zero ETH to this smart contract */
function claimTokens(address _beneficiary) public payable ifNotStartExp ifNotPaused ifNotBlacklisted {
require(msg.value >= mineth);
require(_beneficiary != address(0));
require(!blacklist[msg.sender]);
/* @dev Check to ensure the address is not in processing to avoid double claim */
require(!isProcess[_beneficiary]);
/* @dev Check to ensure the address is signed up to the airdrop */
require(signups[_beneficiary]);
/* @dev Get the reward token for the given address */
uint256 rewardAmount = getReward(_beneficiary);
/* @dev if the baounty reward amount is less than zero, quit the prorcess */
require(rewardAmount > 0);
/* @dev get the available balance for airdrop */
uint256 taBal = token.balanceOf(this);
/* @dev Check is the balance enough to pay for the claim */
require(rewardAmount <= taBal);
/* @dev Set the address to processing */
isProcess[_beneficiary] = true;
/* @dev Transer the token to the bounty */
token.transfer(_beneficiary, rewardAmount);
/* @dev Set the bounty reward entitlement to zero */
bounties[_beneficiary].reward_amount = 0;
bounties[_beneficiary].status = true;
bounties[_beneficiary].paid_time = now;
/* @dev Set the In Process to false to mark the process is completed */
isProcess[_beneficiary] = false;
/* @dev Add the claim tokens to total claimed tokens */
userClaimAmt = userClaimAmt.add(rewardAmount);
/* @dev Transfer the ether */
forwardWei();
emit eTokenClaim(_beneficiary, rewardAmount);
}
/* @dev Bounty claim their reward tokens by sending zero ETH to this smart contract */
function claimImmediateTokens(address _beneficiary) public payable ifNotStartExp ifNotPaused ifNotBlacklisted {
require(msg.value >= mineth);
require(_beneficiary != address(0));
require(!blacklist[msg.sender]);
require(userSignupCount <= maxSignup);
require(fixPayAmt > 0);
uint256 taBal = token.balanceOf(this);
require(taBal > 0);
require(fixPayAmt <= taBal);
require(!isProcess[_beneficiary]);
isProcess[_beneficiary] = true;
signups[_beneficiary] = true;
bounties[_beneficiary] = User(_beneficiary,now,0,false,now,fixPayAmt,true);
bountyaddress.push(_beneficiary) -1;
userSignupCount++;
token.transfer(_beneficiary, fixPayAmt);
userClaimAmt = userClaimAmt.add(fixPayAmt);
forwardWei();
emit eTokenClaim(_beneficiary, fixPayAmt);
}
/* @dev Get Reward function based on the payout style */
function getReward(address _address) internal constant returns(uint256){
uint256 rtnVal = 0;
if(payStyle == 0){
/* Reward divided evenly by the total number of signed up bounty */
uint256 taBal = token.balanceOf(this);
rtnVal = taBal.div(userSignupCount);
}else if(payStyle == 1){
// Reward for each bounty is based on Fixed amount
rtnVal = fixPayAmt;
}else if(payStyle == 2){
// Reward for each bounty is based on the amount set by the Admin when adding the bounty
rtnVal = bounties[_address].reward_amount;
}
return rtnVal;
}
/* @dev Function for who will receive the paid ether */
function forwardWei() internal {
if(!paidversion){
/* if paidversion is false, this is a free version, client agreed to contract creator to received the either */
/* in exchnage to use the service for free */
if(msg.value > 0)
owner.transfer(msg.value);
}else{
/* if paidversion is true, this is a paid version, received ether pay directly to client wallet */
if(msg.value > 0)
wallet.transfer(msg.value);
}
}
} | @dev Return admin addresses list */ | function getAllAdmin() view public onlyAdmin returns(address[]){
return adminaddress;
}
| 1,429,098 | [
1,
990,
3981,
6138,
666,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
5514,
4446,
1435,
1476,
1071,
1338,
4446,
1135,
12,
2867,
63,
5717,
95,
203,
202,
202,
2463,
3981,
2867,
31,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.8;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract VirtueDAO is Context, IERC20 {
using SafeMath for uint;
string public symbol = "VDAOA";
string public name = "Virtue DAO Alpha";
uint8 public decimals = 0;
uint public lastPeriodDecayed;
address[] public allies; // TODO: find a way to decay without looping over allies each period
mapping(address => bool) isFounder;
uint _totalSupply = 0;
mapping(address => uint) public allyVirtues; // allyAddress => pointBalance
mapping(uint => mapping(address => uint)) public awardsMadeThisPeriod; // periodId => user => awardsMadeThisPeriod
mapping(address => bool) public isAlly;
// point awards
uint public maxAwardablePerPeriod = 100;
uint public virtueRetainedPercent = 80;
uint public founderMinAwardable = 100;
uint public nonFounderAwardableDivisor = 5;
constructor(address[] memory _founders) public {
for (uint i = 0; i < _founders.length; i++) {
isFounder[_founders[i]] = true;
}
lastPeriodDecayed = (now / 604800);
}
function allyCount() public view returns (uint) {
return allies.length;
}
function getAwardsMadeThisPeriod(address _ally) public view returns (uint) {
return awardsMadeThisPeriod[currentPeriod()][_ally];
}
function getRemainingAwardableThisPeriod(address _ally) public view returns (uint) {
return maxAwardableThisPeriod(_ally).sub(getAwardsMadeThisPeriod(_ally));
}
// non founders get 1/5 of their virtue to award
// founders get greater of founderMinAwardable or 1/5 virtue
// non one can exceed the max amount
function maxAwardableThisPeriod(address _ally) public view returns (uint) {
uint virtueAllocation = allyVirtues[_ally] / nonFounderAwardableDivisor;
if(isFounder[_ally]) {
return Math.max(founderMinAwardable, virtueAllocation);
} else {
return virtueAllocation;
}
}
// award virtue to a virtuous ally
// virtue is awardable each period
// TODO: find a way to decay without looping over allies each period
// TODO: should not spent virtue go to you? Reason is that its easy to create impersonated accounts to award yourself anyway.
function transfer(address _ally, uint amount) external returns (bool) {
require((awardsMadeThisPeriod[(currentPeriod())][msg.sender] + amount) <= maxAwardableThisPeriod(msg.sender),
"Error: not enough virtue to award");
if(isAlly[_ally] == false) {
allies.push(_ally);
isAlly[_ally] = true;
}
awardsMadeThisPeriod[(currentPeriod())][msg.sender] = awardsMadeThisPeriod[(currentPeriod())][msg.sender].add(amount);
allyVirtues[_ally] = allyVirtues[_ally].add(amount);
_totalSupply = _totalSupply.add(amount);
return true;
}
function balanceOf(address _ally) public view returns (uint) {
return allyVirtues[_ally];
}
function currentPeriod() public view returns (uint) {
return now / 604800; // week number since the unix epoch
}
function decayVirtue() public {
if(lastPeriodDecayed < currentPeriod()) {
for(uint i; i < allies.length; i++) {
_decayVirtue(allies[i]);
}
lastPeriodDecayed = currentPeriod();
}
}
function _decayVirtue(address _ally) private {
allyVirtues[_ally] = allyVirtues[_ally].mul(virtueRetainedPercent).div(100);
}
function virtueDecayPercent() public view returns (uint) {
return 100 - virtueRetainedPercent;
}
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
// remains for ERC20 compatibility not used
// may be implemented in a later version
function allowance(address, address) external view returns (uint256) {
return 0;
}
// remains for ERC20 compatibility not used
// may be implemented in a later version
function approve(address, uint256) external returns (bool) {
require(false, "Error: cannot approve transfer of virtue by other accounts");
return false;
}
// remains for ERC20 compatibility not used
// may be implemented in a later version
function transferFrom(address, address, uint256) external returns (bool) {
require(false, "Error: cannot transfer virtue on behalf of other accounts");
return false;
}
// TODO: virtue CAP / max dividend
// TODO: these functions
// function decayVirtue()
// // Virtue -> rDAI: transferFrom(daoAddress, daoAllyAddress, amount)
// // Ally1 -> DAI: transfer(recipientAddress, amount) \n// DAI is ally'
// function claimFellowship() public {
// _calculateFellowship(msg.sender);
// }
// // based on virtue points received, max values,
// // decay of virtue since it was awarded
// // endowment available during this period
// function _calculateFellowship(address _ally) private {
// // stub
// }
// returns total funds available from patrons
// function endowmentBalance() public returns(uint) {
// // TODO: call external DAI address for balance
// return 0;
// }
} | periodId => user => awardsMadeThisPeriod
| mapping(uint => mapping(address => uint)) public awardsMadeThisPeriod; | 14,053,467 | [
1,
6908,
548,
516,
729,
516,
279,
6397,
49,
2486,
2503,
5027,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
11890,
516,
2874,
12,
2867,
516,
2254,
3719,
1071,
279,
6397,
49,
2486,
2503,
5027,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x363B4B1ADa52E50353f746999bd9E94395190d2C/sources/contracts/libraries/trie/MerkleTrie.sol | * @notice Struct representing a node in the trie. @custom:field encoded The RLP-encoded node. @custom:field decoded The RLP-decoded node./ | struct TrieNode {
bytes encoded;
RLPReader.RLPItem[] decoded;
}
| 15,919,105 | [
1,
3823,
5123,
279,
756,
316,
326,
19080,
18,
632,
3662,
30,
1518,
3749,
1021,
534,
14461,
17,
10787,
756,
18,
632,
3662,
30,
1518,
6383,
1021,
534,
14461,
17,
26646,
756,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1958,
26336,
907,
288,
203,
3639,
1731,
3749,
31,
203,
3639,
534,
14461,
2514,
18,
54,
48,
1102,
874,
8526,
6383,
31,
203,
565,
289,
203,
203,
203,
203,
203,
203,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: UNLICENSED
/**
site - https://savetheoceaneth.com/
Telegram - https://t.me/SaveTheOceanETH
twitter- https://twitter.com/SaveTheOceanEth
*/
pragma solidity ^0.8.4;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
}
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB)
external
returns (address pair);
}
interface IUniswapV2Router02 {
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
}
contract SaveTheOcean is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "SaveTheOcean";
string private constant _symbol = "STO";
uint8 private constant _decimals = 9;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 10000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
//Buy Fee
uint256 private _redisFeeOnBuy = 1;
uint256 private _taxFeeOnBuy = 8;
//Sell Fee
uint256 private _redisFeeOnSell = 1;
uint256 private _taxFeeOnSell = 13;
//Original Fee
uint256 private _redisFee = _redisFeeOnSell;
uint256 private _taxFee = _taxFeeOnSell;
uint256 private _previousredisFee = _redisFee;
uint256 private _previoustaxFee = _taxFee;
mapping(address => bool) public bots;
mapping(address => uint256) private cooldown;
address payable private _developmentAddress = payable(0xa6a5E8387081ec11021516a27a920FA083b467eF);
address payable private _marketingAddress = payable(0xa6a5E8387081ec11021516a27a920FA083b467eF);
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = true;
uint256 public _maxTxAmount = 300000 * 10**9; //3%
uint256 public _maxWalletSize = 300000 * 10**9; //3%
uint256 public _swapTokensAtAmount = 40000 * 10**9; //.4%
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_developmentAddress] = true;
_isExcludedFromFee[_marketingAddress] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
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;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function tokenFromReflection(uint256 rAmount)
private
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function removeAllFee() private {
if (_redisFee == 0 && _taxFee == 0) return;
_previousredisFee = _redisFee;
_previoustaxFee = _taxFee;
_redisFee = 0;
_taxFee = 0;
}
function restoreAllFee() private {
_redisFee = _previousredisFee;
_taxFee = _previoustaxFee;
}
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");
if (from != owner() && to != owner()) {
//Trade start check
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
//Transfer Tokens
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
} else {
//Set Fee for Buys
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
//Set Fee for Sells
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_developmentAddress.transfer(amount.div(2));
_marketingAddress.transfer(amount.div(2));
}
function setTrading(bool _tradingOpen) public onlyOwner {
tradingOpen = _tradingOpen;
}
function manualswap() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function unblockBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _redisFee, _taxFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(
uint256 tAmount,
uint256 redisFee,
uint256 taxFee
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(redisFee).div(100);
uint256 tTeam = tAmount.mul(taxFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tTeam,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner {
_redisFeeOnBuy = redisFeeOnBuy;
_redisFeeOnSell = redisFeeOnSell;
_taxFeeOnBuy = taxFeeOnBuy;
_taxFeeOnSell = taxFeeOnSell;
}
//Set minimum tokens required to swap.
function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner {
_swapTokensAtAmount = swapTokensAtAmount;
}
//Set minimum tokens required to swap.
function toggleSwap(bool _swapEnabled) public onlyOwner {
swapEnabled = _swapEnabled;
}
//Set MAx transaction
function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner {
_maxTxAmount = maxTxAmount;
}
function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner {
_maxWalletSize = maxWalletSize;
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFee[accounts[i]] = excluded;
}
}
} | Buy FeeSell FeeOriginal Fee | contract SaveTheOcean is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "SaveTheOcean";
string private constant _symbol = "STO";
uint8 private constant _decimals = 9;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 10000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _redisFeeOnBuy = 1;
uint256 private _taxFeeOnBuy = 8;
uint256 private _redisFeeOnSell = 1;
uint256 private _taxFeeOnSell = 13;
uint256 private _redisFee = _redisFeeOnSell;
uint256 private _taxFee = _taxFeeOnSell;
uint256 private _previousredisFee = _redisFee;
uint256 private _previoustaxFee = _taxFee;
mapping(address => bool) public bots;
mapping(address => uint256) private cooldown;
address payable private _developmentAddress = payable(0xa6a5E8387081ec11021516a27a920FA083b467eF);
address payable private _marketingAddress = payable(0xa6a5E8387081ec11021516a27a920FA083b467eF);
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = true;
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_developmentAddress] = true;
_isExcludedFromFee[_marketingAddress] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
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;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function tokenFromReflection(uint256 rAmount)
private
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function removeAllFee() private {
if (_redisFee == 0 && _taxFee == 0) return;
_previousredisFee = _redisFee;
_previoustaxFee = _taxFee;
_redisFee = 0;
_taxFee = 0;
}
function restoreAllFee() private {
_redisFee = _previousredisFee;
_taxFee = _previoustaxFee;
}
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");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
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");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
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");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
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");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
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");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
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");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
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");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
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");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
} else {
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");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
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");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_developmentAddress.transfer(amount.div(2));
_marketingAddress.transfer(amount.div(2));
}
function setTrading(bool _tradingOpen) public onlyOwner {
tradingOpen = _tradingOpen;
}
function manualswap() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function unblockBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _redisFee, _taxFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(
uint256 tAmount,
uint256 redisFee,
uint256 taxFee
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(redisFee).div(100);
uint256 tTeam = tAmount.mul(taxFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tTeam,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner {
_redisFeeOnBuy = redisFeeOnBuy;
_redisFeeOnSell = redisFeeOnSell;
_taxFeeOnBuy = taxFeeOnBuy;
_taxFeeOnSell = taxFeeOnSell;
}
function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner {
_swapTokensAtAmount = swapTokensAtAmount;
}
function toggleSwap(bool _swapEnabled) public onlyOwner {
swapEnabled = _swapEnabled;
}
function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner {
_maxTxAmount = maxTxAmount;
}
function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner {
_maxWalletSize = maxWalletSize;
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFee[accounts[i]] = excluded;
}
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFee[accounts[i]] = excluded;
}
}
} | 577,489 | [
1,
38,
9835,
30174,
55,
1165,
30174,
8176,
30174,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
7074,
1986,
51,
31393,
353,
1772,
16,
467,
654,
39,
3462,
16,
14223,
6914,
288,
203,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
533,
3238,
5381,
389,
529,
273,
315,
4755,
1986,
51,
31393,
14432,
203,
565,
533,
3238,
5381,
389,
7175,
273,
315,
31487,
14432,
203,
565,
2254,
28,
3238,
5381,
389,
31734,
273,
2468,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
86,
5460,
329,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
88,
5460,
329,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
1265,
14667,
31,
203,
565,
2254,
5034,
3238,
5381,
4552,
273,
4871,
11890,
5034,
12,
20,
1769,
203,
565,
2254,
5034,
3238,
5381,
389,
88,
5269,
273,
2130,
11706,
380,
1728,
636,
29,
31,
203,
565,
2254,
5034,
3238,
389,
86,
5269,
273,
261,
6694,
300,
261,
6694,
738,
389,
88,
5269,
10019,
203,
565,
2254,
5034,
3238,
389,
88,
14667,
5269,
31,
203,
203,
565,
2254,
5034,
3238,
389,
12311,
14667,
1398,
38,
9835,
273,
404,
31,
203,
565,
2254,
5034,
3238,
389,
8066,
14667,
1398,
38,
9835,
273,
1725,
31,
203,
203,
565,
2254,
5034,
3238,
389,
12311,
14667,
1398,
55,
1165,
273,
404,
31,
203,
565,
2254,
5034,
3238,
389,
8066,
14667,
1398,
55,
1165,
273,
5958,
31,
203,
203,
565,
2254,
5034,
3238,
389,
12311,
14667,
2
] |
/**
*Submitted for verification at Etherscan.io on 2022-03-14
*/
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/utils/ERC721Holder.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
*/
contract ERC721Holder is IERC721Receiver {
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: contracts/InnateFervorAuction.sol
// Auction Contract
pragma solidity ^0.8.0;
contract Auction is Ownable, ERC721Holder {
using SafeMath for uint256;
uint256 constant public PERCENTS_DIVIDER = 1000;
uint256 constant public MIN_BID_INCREMENT_PERCENT = 50; // 5%
uint256 public feeAdmin = 25; // 2.5% fee
address public adminAddress;
// Bid struct to hold bidder and amount
struct Bid {
address from;
uint256 bidPrice;
}
// Auction struct which holds all the required info
struct Auction {
uint256 auctionId;
address collectionId;
uint256 tokenId;
uint256 startTime;
uint256 endTime;
uint256 startPrice;
address owner;
bool active;
}
// Array with all auctions
Auction[] public auctions;
// Mapping from auction index to user bids
mapping (uint256 => Bid[]) public auctionBids;
// Mapping from owner to a list of owned auctions
mapping (address => uint256[]) public ownedAuctions;
event BidSuccess(address _from, uint256 _auctionId, uint256 _price, uint256 _bidIndex);
// AuctionCreated is fired when an auction is created
event AuctionCreated(Auction auction);
// AuctionCanceled is fired when an auction is canceled
event AuctionCanceled(uint _auctionId);
// AuctionFinalized is fired when an auction is finalized
event AuctionFinalized(address buyer, uint256 price, Auction auction);
constructor (address _adminAddress) {
adminAddress = _adminAddress;
}
/*
* @dev Creates an auction with the given informatin
* @param _tokenRepositoryAddress address of the TokenRepository contract
* @param _tokenId uint256 of the deed registered in DeedRepository
* @param _startPrice uint256 starting price of the auction
* @return bool whether the auction is created
*/
function createAuction(address _collectionId, uint256 _tokenId, uint256 _startPrice, uint256 _startTime, uint256 _endTime)
onlyTokenOwner(_collectionId, _tokenId) public
{
require(block.timestamp < _endTime, "end timestamp have to be bigger than current time");
IERC721 nft = IERC721(_collectionId);
uint256 auctionId = auctions.length;
Auction memory newAuction;
newAuction.auctionId = auctionId;
newAuction.collectionId = _collectionId;
newAuction.tokenId = _tokenId;
newAuction.startPrice = _startPrice;
newAuction.startTime = _startTime;
newAuction.endTime = _endTime;
newAuction.owner = msg.sender;
newAuction.active = true;
auctions.push(newAuction);
ownedAuctions[msg.sender].push(auctionId);
nft.safeTransferFrom(msg.sender, address(this), _tokenId);
emit AuctionCreated(newAuction);
}
/**
* @dev Finalized an ended auction
* @dev The auction should be ended, and there should be at least one bid
* @dev On success Deed is transfered to bidder and auction owner gets the amount
* @param _auctionId uint256 ID of the created auction
*/
function finalizeAuction(uint256 _auctionId) public {
Auction memory myAuction = auctions[_auctionId];
uint256 bidsLength = auctionBids[_auctionId].length;
require(msg.sender == myAuction.owner || msg.sender == owner(), "only auction owner can finalize");
// if there are no bids cancel
if(bidsLength == 0) {
IERC721(myAuction.collectionId).safeTransferFrom(address(this), myAuction.owner, myAuction.tokenId);
auctions[_auctionId].active = false;
emit AuctionCanceled(_auctionId);
}else{
// 2. the money goes to the auction owner
Bid memory lastBid = auctionBids[_auctionId][bidsLength - 1];
// % commission cut
uint256 _adminValue = lastBid.bidPrice.mul(feeAdmin).div(PERCENTS_DIVIDER);
uint256 _sellerValue = lastBid.bidPrice.sub(_adminValue);
if(_adminValue > 0){
payable(adminAddress).transfer(_adminValue);
}
payable(myAuction.owner).transfer(_sellerValue);
// approve and transfer from this contract to the bid winner
IERC721(myAuction.collectionId).safeTransferFrom(address(this), lastBid.from, myAuction.tokenId);
auctions[_auctionId].active = false;
emit AuctionFinalized(lastBid.from, lastBid.bidPrice, myAuction);
}
}
/**
* @dev Bidder sends bid on an auction
* @dev Auction should be active and not ended
* @dev Refund previous bidder if a new bid is valid and placed.
* @param _auctionId uint256 ID of the created auction
*/
function bidOnAuction(uint256 _auctionId, uint256 amount) external payable {
require(_auctionId <= auctions.length && auctions[_auctionId].auctionId == _auctionId, "Could not find item");
// owner can't bid on their auctions
Auction memory myAuction = auctions[_auctionId];
require(myAuction.owner != msg.sender, "owner can not bid");
require(myAuction.active, "not exist");
// if auction is expired
require(block.timestamp < myAuction.endTime, "auction is over");
require(block.timestamp >= myAuction.startTime, "auction is not started");
uint256 bidsLength = auctionBids[_auctionId].length;
uint256 tempAmount = myAuction.startPrice;
Bid memory lastBid;
// there are previous bids
if( bidsLength > 0 ) {
lastBid = auctionBids[_auctionId][bidsLength - 1];
tempAmount = lastBid.bidPrice.mul(PERCENTS_DIVIDER + MIN_BID_INCREMENT_PERCENT).div(PERCENTS_DIVIDER);
}
// check if amount is greater than previous amount
require(amount >= tempAmount, "too small amount");
require(msg.value >= amount, "too small balance");
// refund the last bidder
if( bidsLength > 0 ) {
payable(lastBid.from).transfer(lastBid.bidPrice);
}
// insert bid
Bid memory newBid;
newBid.from = msg.sender;
newBid.bidPrice = amount;
auctionBids[_auctionId].push(newBid);
emit BidSuccess(msg.sender, _auctionId, newBid.bidPrice, bidsLength);
}
/**
* @dev Gets the length of auctions
* @return uint256 representing the auction count
*/
function getAuctionsLength() public view returns(uint) {
return auctions.length;
}
/**
* @dev Gets the bid counts of a given auction
* @param _auctionId uint256 ID of the auction
*/
function getBidsAmount(uint256 _auctionId) public view returns(uint) {
return auctionBids[_auctionId].length;
}
/**
* @dev Gets an array of owned auctions
* @param _owner address of the auction owner
*/
function getOwnedAuctions(address _owner) public view returns(uint[] memory) {
uint[] memory ownedAllAuctions = ownedAuctions[_owner];
return ownedAllAuctions;
}
/**
* @dev Gets an array of owned auctions
* @param _auctionId uint256 of the auction owner
* @return amount uint256, address of last bidder
*/
function getCurrentBids(uint256 _auctionId) public view returns(uint256, address) {
uint256 bidsLength = auctionBids[_auctionId].length;
// if there are bids refund the last bid
if (bidsLength >= 0) {
Bid memory lastBid = auctionBids[_auctionId][bidsLength - 1];
return (lastBid.bidPrice, lastBid.from);
}
return (0, address(0));
}
/**
* @dev Gets the total number of auctions owned by an address
* @param _owner address of the owner
* @return uint256 total number of auctions
*/
function getAuctionsAmount(address _owner) public view returns(uint) {
return ownedAuctions[_owner].length;
}
function withdrawCoin() public onlyOwner {
uint balance = address(this).balance;
require(balance > 0, "insufficient balance");
payable(msg.sender).transfer(balance);
}
modifier onlyAuctionOwner(uint256 _auctionId) {
require(auctions[_auctionId].owner == msg.sender);
_;
}
modifier onlyTokenOwner(address _collectionId, uint256 _tokenId) {
address tokenOwner = IERC721(_collectionId).ownerOf(_tokenId);
require(tokenOwner == msg.sender);
_;
}
} | * @dev Gets an array of owned auctions @param _owner address of the auction owner/ | function getOwnedAuctions(address _owner) public view returns(uint[] memory) {
uint[] memory ownedAllAuctions = ownedAuctions[_owner];
return ownedAllAuctions;
}
| 6,600,783 | [
1,
3002,
392,
526,
434,
16199,
279,
4062,
87,
225,
389,
8443,
1758,
434,
326,
279,
4062,
3410,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
336,
5460,
329,
37,
4062,
87,
12,
2867,
389,
8443,
13,
1071,
1476,
1135,
12,
11890,
8526,
3778,
13,
288,
203,
3639,
2254,
8526,
3778,
16199,
1595,
37,
4062,
87,
273,
16199,
37,
4062,
87,
63,
67,
8443,
15533,
203,
3639,
327,
16199,
1595,
37,
4062,
87,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x00337a31aEE3Ed37f5D5FBF892031d0090Da2EeF/sources/contracts/relayer/wormholeRelayer/WormholeRelayerSend.sol | Get the delivery provider's contract address on chain 'targetChain' | function getDefaultDeliveryProviderOnChain(uint16 targetChain)
public
view
returns (address deliveryProvider)
{
deliveryProvider = fromWormholeFormat(
IDeliveryProvider(getDefaultDeliveryProviderState().defaultDeliveryProvider)
.getTargetChainAddress(targetChain)
);
}
| 17,096,606 | [
1,
967,
326,
7912,
2893,
1807,
6835,
1758,
603,
2687,
296,
3299,
3893,
11,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4829,
8909,
2249,
1398,
3893,
12,
11890,
2313,
1018,
3893,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
2867,
7912,
2249,
13,
203,
565,
288,
203,
3639,
7912,
2249,
273,
628,
59,
535,
27167,
1630,
12,
203,
5411,
1599,
292,
4535,
2249,
12,
588,
1868,
8909,
2249,
1119,
7675,
1886,
8909,
2249,
13,
203,
7734,
263,
588,
2326,
3893,
1887,
12,
3299,
3893,
13,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../release/extensions/integration-manager/integrations/utils/AdapterBase.sol";
/// @title IMockGenericIntegratee Interface
/// @author Enzyme Council <[email protected]>
interface IMockGenericIntegratee {
function swap(
address[] calldata,
uint256[] calldata,
address[] calldata,
uint256[] calldata
) external payable;
function swapOnBehalf(
address payable,
address[] calldata,
uint256[] calldata,
address[] calldata,
uint256[] calldata
) external payable;
}
/// @title MockGenericAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Provides a generic adapter that:
/// 1. Provides swapping functions that use various `SpendAssetsTransferType` values
/// 2. Directly parses the _actual_ values to swap from provided call data (e.g., `actualIncomingAssetAmounts`)
/// 3. Directly parses values needed by the IntegrationManager from provided call data (e.g., `minIncomingAssetAmounts`)
contract MockGenericAdapter is AdapterBase {
address public immutable INTEGRATEE;
// No need to specify the IntegrationManager
constructor(address _integratee) public AdapterBase(address(0)) {
INTEGRATEE = _integratee;
}
function identifier() external pure override returns (string memory) {
return "MOCK_GENERIC";
}
function parseAssetsForMethod(bytes4 _selector, bytes calldata _callArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory maxSpendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
spendAssets_,
maxSpendAssetAmounts_,
,
incomingAssets_,
minIncomingAssetAmounts_,
) = __decodeCallArgs(_callArgs);
return (
__getSpendAssetsHandleTypeForSelector(_selector),
spendAssets_,
maxSpendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Assumes SpendAssetsHandleType.Transfer unless otherwise specified
function __getSpendAssetsHandleTypeForSelector(bytes4 _selector)
private
pure
returns (IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_)
{
if (_selector == bytes4(keccak256("removeOnly(address,bytes,bytes)"))) {
return IIntegrationManager.SpendAssetsHandleType.Remove;
}
if (_selector == bytes4(keccak256("swapDirectFromVault(address,bytes,bytes)"))) {
return IIntegrationManager.SpendAssetsHandleType.None;
}
if (_selector == bytes4(keccak256("swapViaApproval(address,bytes,bytes)"))) {
return IIntegrationManager.SpendAssetsHandleType.Approve;
}
return IIntegrationManager.SpendAssetsHandleType.Transfer;
}
function removeOnly(
address,
bytes calldata,
bytes calldata
) external {}
function swapA(
address _vaultProxy,
bytes calldata _callArgs,
bytes calldata _assetTransferArgs
) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) {
__decodeCallArgsAndSwap(_callArgs);
}
function swapB(
address _vaultProxy,
bytes calldata _callArgs,
bytes calldata _assetTransferArgs
) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) {
__decodeCallArgsAndSwap(_callArgs);
}
function swapDirectFromVault(
address _vaultProxy,
bytes calldata _callArgs,
bytes calldata
) external {
(
address[] memory spendAssets,
,
uint256[] memory actualSpendAssetAmounts,
address[] memory incomingAssets,
,
uint256[] memory actualIncomingAssetAmounts
) = __decodeCallArgs(_callArgs);
IMockGenericIntegratee(INTEGRATEE).swapOnBehalf(
payable(_vaultProxy),
spendAssets,
actualSpendAssetAmounts,
incomingAssets,
actualIncomingAssetAmounts
);
}
function swapViaApproval(
address _vaultProxy,
bytes calldata _callArgs,
bytes calldata _assetTransferArgs
) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) {
__decodeCallArgsAndSwap(_callArgs);
}
function __decodeCallArgs(bytes memory _callArgs)
internal
pure
returns (
address[] memory spendAssets_,
uint256[] memory maxSpendAssetAmounts_,
uint256[] memory actualSpendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_,
uint256[] memory actualIncomingAssetAmounts_
)
{
return
abi.decode(
_callArgs,
(address[], uint256[], uint256[], address[], uint256[], uint256[])
);
}
function __decodeCallArgsAndSwap(bytes memory _callArgs) internal {
(
address[] memory spendAssets,
,
uint256[] memory actualSpendAssetAmounts,
address[] memory incomingAssets,
,
uint256[] memory actualIncomingAssetAmounts
) = __decodeCallArgs(_callArgs);
for (uint256 i; i < spendAssets.length; i++) {
ERC20(spendAssets[i]).approve(INTEGRATEE, actualSpendAssetAmounts[i]);
}
IMockGenericIntegratee(INTEGRATEE).swap(
spendAssets,
actualSpendAssetAmounts,
incomingAssets,
actualIncomingAssetAmounts
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../IIntegrationAdapter.sol";
import "./IntegrationSelectors.sol";
/// @title AdapterBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice A base contract for integration adapters
abstract contract AdapterBase is IIntegrationAdapter, IntegrationSelectors {
using SafeERC20 for ERC20;
address internal immutable INTEGRATION_MANAGER;
/// @dev Provides a standard implementation for transferring assets between
/// the fund's VaultProxy and the adapter, by wrapping the adapter action.
/// This modifier should be implemented in almost all adapter actions, unless they
/// do not move assets or can spend and receive assets directly with the VaultProxy
modifier fundAssetsTransferHandler(
address _vaultProxy,
bytes memory _encodedAssetTransferArgs
) {
(
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType,
address[] memory spendAssets,
uint256[] memory spendAssetAmounts,
address[] memory incomingAssets
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
// Take custody of spend assets (if necessary)
if (spendAssetsHandleType == IIntegrationManager.SpendAssetsHandleType.Approve) {
for (uint256 i = 0; i < spendAssets.length; i++) {
ERC20(spendAssets[i]).safeTransferFrom(
_vaultProxy,
address(this),
spendAssetAmounts[i]
);
}
}
// Execute call
_;
// Transfer remaining assets back to the fund's VaultProxy
__transferContractAssetBalancesToFund(_vaultProxy, incomingAssets);
__transferContractAssetBalancesToFund(_vaultProxy, spendAssets);
}
modifier onlyIntegrationManager {
require(
msg.sender == INTEGRATION_MANAGER,
"Only the IntegrationManager can call this function"
);
_;
}
constructor(address _integrationManager) public {
INTEGRATION_MANAGER = _integrationManager;
}
// INTERNAL FUNCTIONS
/// @dev Helper for adapters to approve their integratees with the max amount of an asset.
/// Since everything is done atomically, and only the balances to-be-used are sent to adapters,
/// there is no need to approve exact amounts on every call.
function __approveMaxAsNeeded(
address _asset,
address _target,
uint256 _neededAmount
) internal {
if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) {
ERC20(_asset).safeApprove(_target, type(uint256).max);
}
}
/// @dev Helper to decode the _encodedAssetTransferArgs param passed to adapter call
function __decodeEncodedAssetTransferArgs(bytes memory _encodedAssetTransferArgs)
internal
pure
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_
)
{
return
abi.decode(
_encodedAssetTransferArgs,
(IIntegrationManager.SpendAssetsHandleType, address[], uint256[], address[])
);
}
/// @dev Helper to transfer full contract balances of assets to the specified VaultProxy
function __transferContractAssetBalancesToFund(address _vaultProxy, address[] memory _assets)
private
{
for (uint256 i = 0; i < _assets.length; i++) {
uint256 postCallAmount = ERC20(_assets[i]).balanceOf(address(this));
if (postCallAmount > 0) {
ERC20(_assets[i]).safeTransfer(_vaultProxy, postCallAmount);
}
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `INTEGRATION_MANAGER` variable
/// @return integrationManager_ The `INTEGRATION_MANAGER` variable value
function getIntegrationManager() external view returns (address integrationManager_) {
return INTEGRATION_MANAGER;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../IIntegrationManager.sol";
/// @title Integration Adapter interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all integration adapters
interface IIntegrationAdapter {
function identifier() external pure returns (string memory identifier_);
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IntegrationSelectors Contract
/// @author Enzyme Council <[email protected]>
/// @notice Selectors for integration actions
/// @dev Selectors are created from their signatures rather than hardcoded for easy verification
abstract contract IntegrationSelectors {
bytes4 public constant ADD_TRACKED_ASSETS_SELECTOR = bytes4(
keccak256("addTrackedAssets(address,bytes,bytes)")
);
// Trading
bytes4 public constant TAKE_ORDER_SELECTOR = bytes4(
keccak256("takeOrder(address,bytes,bytes)")
);
// Lending
bytes4 public constant LEND_SELECTOR = bytes4(keccak256("lend(address,bytes,bytes)"));
bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256("redeem(address,bytes,bytes)"));
// Staking
bytes4 public constant STAKE_SELECTOR = bytes4(keccak256("stake(address,bytes,bytes)"));
bytes4 public constant UNSTAKE_SELECTOR = bytes4(keccak256("unstake(address,bytes,bytes)"));
// Combined
bytes4 public constant LEND_AND_STAKE_SELECTOR = bytes4(
keccak256("lendAndStake(address,bytes,bytes)")
);
bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR = bytes4(
keccak256("unstakeAndRedeem(address,bytes,bytes)")
);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IIntegrationManager interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the IntegrationManager
interface IIntegrationManager {
enum SpendAssetsHandleType {None, Approve, Transfer, Remove}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/IZeroExV2.sol";
import "../../../../utils/MathHelpers.sol";
import "../../../../utils/AddressArrayLib.sol";
import "../../../utils/FundDeployerOwnerMixin.sol";
import "../utils/AdapterBase.sol";
/// @title ZeroExV2Adapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter to 0xV2 Exchange Contract
contract ZeroExV2Adapter is AdapterBase, FundDeployerOwnerMixin, MathHelpers {
using AddressArrayLib for address[];
using SafeMath for uint256;
event AllowedMakerAdded(address indexed account);
event AllowedMakerRemoved(address indexed account);
address private immutable EXCHANGE;
mapping(address => bool) private makerToIsAllowed;
// Gas could be optimized for the end-user by also storing an immutable ZRX_ASSET_DATA,
// for example, but in the narrow OTC use-case of this adapter, taker fees are unlikely.
constructor(
address _integrationManager,
address _exchange,
address _fundDeployer,
address[] memory _allowedMakers
) public AdapterBase(_integrationManager) FundDeployerOwnerMixin(_fundDeployer) {
EXCHANGE = _exchange;
if (_allowedMakers.length > 0) {
__addAllowedMakers(_allowedMakers);
}
}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "ZERO_EX_V2";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid");
(
bytes memory encodedZeroExOrderArgs,
uint256 takerAssetFillAmount
) = __decodeTakeOrderCallArgs(_encodedCallArgs);
IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs);
require(
isAllowedMaker(order.makerAddress),
"parseAssetsForMethod: Order maker is not allowed"
);
require(
takerAssetFillAmount <= order.takerAssetAmount,
"parseAssetsForMethod: Taker asset fill amount greater than available"
);
address makerAsset = __getAssetAddress(order.makerAssetData);
address takerAsset = __getAssetAddress(order.takerAssetData);
// Format incoming assets
incomingAssets_ = new address[](1);
incomingAssets_[0] = makerAsset;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = __calcRelativeQuantity(
order.takerAssetAmount,
order.makerAssetAmount,
takerAssetFillAmount
);
if (order.takerFee > 0) {
address takerFeeAsset = __getAssetAddress(IZeroExV2(EXCHANGE).ZRX_ASSET_DATA());
uint256 takerFeeFillAmount = __calcRelativeQuantity(
order.takerAssetAmount,
order.takerFee,
takerAssetFillAmount
); // fee calculated relative to taker fill amount
if (takerFeeAsset == makerAsset) {
require(
order.takerFee < order.makerAssetAmount,
"parseAssetsForMethod: Fee greater than makerAssetAmount"
);
spendAssets_ = new address[](1);
spendAssets_[0] = takerAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = takerAssetFillAmount;
minIncomingAssetAmounts_[0] = minIncomingAssetAmounts_[0].sub(takerFeeFillAmount);
} else if (takerFeeAsset == takerAsset) {
spendAssets_ = new address[](1);
spendAssets_[0] = takerAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = takerAssetFillAmount.add(takerFeeFillAmount);
} else {
spendAssets_ = new address[](2);
spendAssets_[0] = takerAsset;
spendAssets_[1] = takerFeeAsset;
spendAssetAmounts_ = new uint256[](2);
spendAssetAmounts_[0] = takerAssetFillAmount;
spendAssetAmounts_[1] = takerFeeFillAmount;
}
} else {
spendAssets_ = new address[](1);
spendAssets_[0] = takerAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = takerAssetFillAmount;
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Take an order on 0x
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function takeOrder(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
bytes memory encodedZeroExOrderArgs,
uint256 takerAssetFillAmount
) = __decodeTakeOrderCallArgs(_encodedCallArgs);
IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs);
// Approve spend assets as needed
__approveMaxAsNeeded(
__getAssetAddress(order.takerAssetData),
__getAssetProxy(order.takerAssetData),
takerAssetFillAmount
);
// Ignores whether makerAsset or takerAsset overlap with the takerFee asset for simplicity
if (order.takerFee > 0) {
bytes memory zrxData = IZeroExV2(EXCHANGE).ZRX_ASSET_DATA();
__approveMaxAsNeeded(
__getAssetAddress(zrxData),
__getAssetProxy(zrxData),
__calcRelativeQuantity(
order.takerAssetAmount,
order.takerFee,
takerAssetFillAmount
) // fee calculated relative to taker fill amount
);
}
// Execute order
(, , , bytes memory signature) = __decodeZeroExOrderArgs(encodedZeroExOrderArgs);
IZeroExV2(EXCHANGE).fillOrder(order, takerAssetFillAmount, signature);
}
// PRIVATE FUNCTIONS
/// @dev Parses user inputs into a ZeroExV2.Order format
function __constructOrderStruct(bytes memory _encodedOrderArgs)
private
pure
returns (IZeroExV2.Order memory order_)
{
(
address[4] memory orderAddresses,
uint256[6] memory orderValues,
bytes[2] memory orderData,
) = __decodeZeroExOrderArgs(_encodedOrderArgs);
return
IZeroExV2.Order({
makerAddress: orderAddresses[0],
takerAddress: orderAddresses[1],
feeRecipientAddress: orderAddresses[2],
senderAddress: orderAddresses[3],
makerAssetAmount: orderValues[0],
takerAssetAmount: orderValues[1],
makerFee: orderValues[2],
takerFee: orderValues[3],
expirationTimeSeconds: orderValues[4],
salt: orderValues[5],
makerAssetData: orderData[0],
takerAssetData: orderData[1]
});
}
/// @dev Decode the parameters of a takeOrder call
/// @param _encodedCallArgs Encoded parameters passed from client side
/// @return encodedZeroExOrderArgs_ Encoded args of the 0x order
/// @return takerAssetFillAmount_ Amount of taker asset to fill
function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (bytes memory encodedZeroExOrderArgs_, uint256 takerAssetFillAmount_)
{
return abi.decode(_encodedCallArgs, (bytes, uint256));
}
/// @dev Decode the parameters of a 0x order
/// @param _encodedZeroExOrderArgs Encoded parameters of the 0x order
/// @return orderAddresses_ Addresses used in the order
/// - [0] 0x Order param: makerAddress
/// - [1] 0x Order param: takerAddress
/// - [2] 0x Order param: feeRecipientAddress
/// - [3] 0x Order param: senderAddress
/// @return orderValues_ Values used in the order
/// - [0] 0x Order param: makerAssetAmount
/// - [1] 0x Order param: takerAssetAmount
/// - [2] 0x Order param: makerFee
/// - [3] 0x Order param: takerFee
/// - [4] 0x Order param: expirationTimeSeconds
/// - [5] 0x Order param: salt
/// @return orderData_ Bytes data used in the order
/// - [0] 0x Order param: makerAssetData
/// - [1] 0x Order param: takerAssetData
/// @return signature_ Signature of the order
function __decodeZeroExOrderArgs(bytes memory _encodedZeroExOrderArgs)
private
pure
returns (
address[4] memory orderAddresses_,
uint256[6] memory orderValues_,
bytes[2] memory orderData_,
bytes memory signature_
)
{
return abi.decode(_encodedZeroExOrderArgs, (address[4], uint256[6], bytes[2], bytes));
}
/// @dev Parses the asset address from 0x assetData
function __getAssetAddress(bytes memory _assetData)
private
pure
returns (address assetAddress_)
{
assembly {
assetAddress_ := mload(add(_assetData, 36))
}
}
/// @dev Gets the 0x assetProxy address for an ERC20 token
function __getAssetProxy(bytes memory _assetData) private view returns (address assetProxy_) {
bytes4 assetProxyId;
assembly {
assetProxyId := and(
mload(add(_assetData, 32)),
0xFFFFFFFF00000000000000000000000000000000000000000000000000000000
)
}
assetProxy_ = IZeroExV2(EXCHANGE).getAssetProxy(assetProxyId);
}
/////////////////////////////
// ALLOWED MAKERS REGISTRY //
/////////////////////////////
/// @notice Adds accounts to the list of allowed 0x order makers
/// @param _accountsToAdd Accounts to add
function addAllowedMakers(address[] calldata _accountsToAdd) external onlyFundDeployerOwner {
__addAllowedMakers(_accountsToAdd);
}
/// @notice Removes accounts from the list of allowed 0x order makers
/// @param _accountsToRemove Accounts to remove
function removeAllowedMakers(address[] calldata _accountsToRemove)
external
onlyFundDeployerOwner
{
require(_accountsToRemove.length > 0, "removeAllowedMakers: Empty _accountsToRemove");
for (uint256 i; i < _accountsToRemove.length; i++) {
require(
isAllowedMaker(_accountsToRemove[i]),
"removeAllowedMakers: Account is not an allowed maker"
);
makerToIsAllowed[_accountsToRemove[i]] = false;
emit AllowedMakerRemoved(_accountsToRemove[i]);
}
}
/// @dev Helper to add accounts to the list of allowed makers
function __addAllowedMakers(address[] memory _accountsToAdd) private {
require(_accountsToAdd.length > 0, "__addAllowedMakers: Empty _accountsToAdd");
for (uint256 i; i < _accountsToAdd.length; i++) {
require(!isAllowedMaker(_accountsToAdd[i]), "__addAllowedMakers: Value already set");
makerToIsAllowed[_accountsToAdd[i]] = true;
emit AllowedMakerAdded(_accountsToAdd[i]);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `EXCHANGE` variable value
/// @return exchange_ The `EXCHANGE` variable value
function getExchange() external view returns (address exchange_) {
return EXCHANGE;
}
/// @notice Checks whether an account is an allowed maker of 0x orders
/// @param _who The account to check
/// @return isAllowedMaker_ True if _who is an allowed maker
function isAllowedMaker(address _who) public view returns (bool isAllowedMaker_) {
return makerToIsAllowed[_who];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @dev Minimal interface for our interactions with the ZeroEx Exchange contract
interface IZeroExV2 {
struct Order {
address makerAddress;
address takerAddress;
address feeRecipientAddress;
address senderAddress;
uint256 makerAssetAmount;
uint256 takerAssetAmount;
uint256 makerFee;
uint256 takerFee;
uint256 expirationTimeSeconds;
uint256 salt;
bytes makerAssetData;
bytes takerAssetData;
}
struct OrderInfo {
uint8 orderStatus;
bytes32 orderHash;
uint256 orderTakerAssetFilledAmount;
}
struct FillResults {
uint256 makerAssetFilledAmount;
uint256 takerAssetFilledAmount;
uint256 makerFeePaid;
uint256 takerFeePaid;
}
function ZRX_ASSET_DATA() external view returns (bytes memory);
function filled(bytes32) external view returns (uint256);
function cancelled(bytes32) external view returns (bool);
function getOrderInfo(Order calldata) external view returns (OrderInfo memory);
function getAssetProxy(bytes4) external view returns (address);
function isValidSignature(
bytes32,
address,
bytes calldata
) external view returns (bool);
function preSign(
bytes32,
address,
bytes calldata
) external;
function cancelOrder(Order calldata) external;
function fillOrder(
Order calldata,
uint256,
bytes calldata
) external returns (FillResults memory);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
/// @title MathHelpers Contract
/// @author Enzyme Council <[email protected]>
/// @notice Helper functions for common math operations
abstract contract MathHelpers {
using SafeMath for uint256;
/// @dev Calculates a proportional value relative to a known ratio
function __calcRelativeQuantity(
uint256 _quantity1,
uint256 _quantity2,
uint256 _relativeQuantity1
) internal pure returns (uint256 relativeQuantity2_) {
return _relativeQuantity1.mul(_quantity2).div(_quantity1);
}
/// @dev Calculates a rate normalized to 10^18 precision,
/// for given base and quote asset decimals and amounts
function __calcNormalizedRate(
uint256 _baseAssetDecimals,
uint256 _baseAssetAmount,
uint256 _quoteAssetDecimals,
uint256 _quoteAssetAmount
) internal pure returns (uint256 normalizedRate_) {
return
_quoteAssetAmount.mul(10**_baseAssetDecimals.add(18)).div(
_baseAssetAmount.mul(10**_quoteAssetDecimals)
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title AddressArray Library
/// @author Enzyme Council <[email protected]>
/// @notice A library to extend the address array data type
library AddressArrayLib {
/// @dev Helper to verify if an array contains a particular value
function contains(address[] memory _self, address _target)
internal
pure
returns (bool doesContain_)
{
for (uint256 i; i < _self.length; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
/// @dev Helper to verify if array is a set of unique values.
/// Does not assert length > 0.
function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
/// @dev Helper to remove items from an array. Removes all matching occurrences of each item.
/// Does not assert uniqueness of either array.
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
} else if (remainingItemsCount > 0) {
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../core/fund-deployer/IFundDeployer.sol";
/// @title FundDeployerOwnerMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract that defers ownership to the owner of FundDeployer
abstract contract FundDeployerOwnerMixin {
address internal immutable FUND_DEPLOYER;
modifier onlyFundDeployerOwner() {
require(
msg.sender == getOwner(),
"onlyFundDeployerOwner: Only the FundDeployer owner can call this function"
);
_;
}
constructor(address _fundDeployer) public {
FUND_DEPLOYER = _fundDeployer;
}
/// @notice Gets the owner of this contract
/// @return owner_ The owner
/// @dev Ownership is deferred to the owner of the FundDeployer contract
function getOwner() public view returns (address owner_) {
return IFundDeployer(FUND_DEPLOYER).getOwner();
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `FUND_DEPLOYER` variable
/// @return fundDeployer_ The `FUND_DEPLOYER` variable value
function getFundDeployer() external view returns (address fundDeployer_) {
return FUND_DEPLOYER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IFundDeployer Interface
/// @author Enzyme Council <[email protected]>
interface IFundDeployer {
enum ReleaseStatus {PreLaunch, Live, Paused}
function getOwner() external view returns (address);
function getReleaseStatus() external view returns (ReleaseStatus);
function isRegisteredVaultCall(address, bytes4) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "../../core/fund/vault/IVault.sol";
import "../utils/ExtensionBase.sol";
import "../utils/FundDeployerOwnerMixin.sol";
import "./IPolicy.sol";
import "./IPolicyManager.sol";
/// @title PolicyManager Contract
/// @author Enzyme Council <[email protected]>
/// @notice Manages policies for funds
contract PolicyManager is IPolicyManager, ExtensionBase, FundDeployerOwnerMixin {
using EnumerableSet for EnumerableSet.AddressSet;
event PolicyDeregistered(address indexed policy, string indexed identifier);
event PolicyDisabledForFund(address indexed comptrollerProxy, address indexed policy);
event PolicyEnabledForFund(
address indexed comptrollerProxy,
address indexed policy,
bytes settingsData
);
event PolicyRegistered(
address indexed policy,
string indexed identifier,
PolicyHook[] implementedHooks
);
EnumerableSet.AddressSet private registeredPolicies;
mapping(address => mapping(PolicyHook => bool)) private policyToHookToIsImplemented;
mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToPolicies;
modifier onlyBuySharesHooks(address _policy) {
require(
!policyImplementsHook(_policy, PolicyHook.PreCallOnIntegration) &&
!policyImplementsHook(_policy, PolicyHook.PostCallOnIntegration),
"onlyBuySharesHooks: Disallowed hook"
);
_;
}
modifier onlyEnabledPolicyForFund(address _comptrollerProxy, address _policy) {
require(
policyIsEnabledForFund(_comptrollerProxy, _policy),
"onlyEnabledPolicyForFund: Policy not enabled"
);
_;
}
constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {}
// EXTERNAL FUNCTIONS
/// @notice Validates and initializes policies as necessary prior to fund activation
/// @param _isMigratedFund True if the fund is migrating to this release
/// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate.
function activateForFund(bool _isMigratedFund) external override {
address vaultProxy = __setValidatedVaultProxy(msg.sender);
// Policies must assert that they are congruent with migrated vault state
if (_isMigratedFund) {
address[] memory enabledPolicies = getEnabledPoliciesForFund(msg.sender);
for (uint256 i; i < enabledPolicies.length; i++) {
__activatePolicyForFund(msg.sender, vaultProxy, enabledPolicies[i]);
}
}
}
/// @notice Deactivates policies for a fund by destroying storage
function deactivateForFund() external override {
delete comptrollerProxyToVaultProxy[msg.sender];
for (uint256 i = comptrollerProxyToPolicies[msg.sender].length(); i > 0; i--) {
comptrollerProxyToPolicies[msg.sender].remove(
comptrollerProxyToPolicies[msg.sender].at(i - 1)
);
}
}
/// @notice Disables a policy for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _policy The policy address to disable
function disablePolicyForFund(address _comptrollerProxy, address _policy)
external
onlyBuySharesHooks(_policy)
onlyEnabledPolicyForFund(_comptrollerProxy, _policy)
{
__validateIsFundOwner(getVaultProxyForFund(_comptrollerProxy), msg.sender);
comptrollerProxyToPolicies[_comptrollerProxy].remove(_policy);
emit PolicyDisabledForFund(_comptrollerProxy, _policy);
}
/// @notice Enables a policy for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _policy The policy address to enable
/// @param _settingsData The encoded settings data with which to configure the policy
/// @dev Disabling a policy does not delete fund config on the policy, so if a policy is
/// disabled and then enabled again, its initial state will be the previous config. It is the
/// policy's job to determine how to merge that config with the _settingsData param in this function.
function enablePolicyForFund(
address _comptrollerProxy,
address _policy,
bytes calldata _settingsData
) external onlyBuySharesHooks(_policy) {
address vaultProxy = getVaultProxyForFund(_comptrollerProxy);
__validateIsFundOwner(vaultProxy, msg.sender);
__enablePolicyForFund(_comptrollerProxy, _policy, _settingsData);
__activatePolicyForFund(_comptrollerProxy, vaultProxy, _policy);
}
/// @notice Enable policies for use in a fund
/// @param _configData Encoded config data
/// @dev Only called during init() on ComptrollerProxy deployment
function setConfigForFund(bytes calldata _configData) external override {
(address[] memory policies, bytes[] memory settingsData) = abi.decode(
_configData,
(address[], bytes[])
);
// Sanity check
require(
policies.length == settingsData.length,
"setConfigForFund: policies and settingsData array lengths unequal"
);
// Enable each policy with settings
for (uint256 i; i < policies.length; i++) {
__enablePolicyForFund(msg.sender, policies[i], settingsData[i]);
}
}
/// @notice Updates policy settings for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _policy The Policy contract to update
/// @param _settingsData The encoded settings data with which to update the policy config
function updatePolicySettingsForFund(
address _comptrollerProxy,
address _policy,
bytes calldata _settingsData
) external onlyBuySharesHooks(_policy) onlyEnabledPolicyForFund(_comptrollerProxy, _policy) {
address vaultProxy = getVaultProxyForFund(_comptrollerProxy);
__validateIsFundOwner(vaultProxy, msg.sender);
IPolicy(_policy).updateFundSettings(_comptrollerProxy, vaultProxy, _settingsData);
}
/// @notice Validates all policies that apply to a given hook for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _hook The PolicyHook for which to validate policies
/// @param _validationData The encoded data with which to validate the filtered policies
function validatePolicies(
address _comptrollerProxy,
PolicyHook _hook,
bytes calldata _validationData
) external override {
address vaultProxy = getVaultProxyForFund(_comptrollerProxy);
address[] memory policies = getEnabledPoliciesForFund(_comptrollerProxy);
for (uint256 i; i < policies.length; i++) {
if (!policyImplementsHook(policies[i], _hook)) {
continue;
}
require(
IPolicy(policies[i]).validateRule(
_comptrollerProxy,
vaultProxy,
_hook,
_validationData
),
string(
abi.encodePacked(
"Rule evaluated to false: ",
IPolicy(policies[i]).identifier()
)
)
);
}
}
// PRIVATE FUNCTIONS
/// @dev Helper to activate a policy for a fund
function __activatePolicyForFund(
address _comptrollerProxy,
address _vaultProxy,
address _policy
) private {
IPolicy(_policy).activateForFund(_comptrollerProxy, _vaultProxy);
}
/// @dev Helper to set config and enable policies for a fund
function __enablePolicyForFund(
address _comptrollerProxy,
address _policy,
bytes memory _settingsData
) private {
require(
!policyIsEnabledForFund(_comptrollerProxy, _policy),
"__enablePolicyForFund: policy already enabled"
);
require(policyIsRegistered(_policy), "__enablePolicyForFund: Policy is not registered");
// Set fund config on policy
if (_settingsData.length > 0) {
IPolicy(_policy).addFundSettings(_comptrollerProxy, _settingsData);
}
// Add policy
comptrollerProxyToPolicies[_comptrollerProxy].add(_policy);
emit PolicyEnabledForFund(_comptrollerProxy, _policy, _settingsData);
}
/// @dev Helper to validate fund owner.
/// Preferred to a modifier because allows gas savings if re-using _vaultProxy.
function __validateIsFundOwner(address _vaultProxy, address _who) private view {
require(
_who == IVault(_vaultProxy).getOwner(),
"Only the fund owner can call this function"
);
}
///////////////////////
// POLICIES REGISTRY //
///////////////////////
/// @notice Remove policies from the list of registered policies
/// @param _policies Addresses of policies to be registered
function deregisterPolicies(address[] calldata _policies) external onlyFundDeployerOwner {
require(_policies.length > 0, "deregisterPolicies: _policies cannot be empty");
for (uint256 i; i < _policies.length; i++) {
require(
policyIsRegistered(_policies[i]),
"deregisterPolicies: policy is not registered"
);
registeredPolicies.remove(_policies[i]);
emit PolicyDeregistered(_policies[i], IPolicy(_policies[i]).identifier());
}
}
/// @notice Add policies to the list of registered policies
/// @param _policies Addresses of policies to be registered
function registerPolicies(address[] calldata _policies) external onlyFundDeployerOwner {
require(_policies.length > 0, "registerPolicies: _policies cannot be empty");
for (uint256 i; i < _policies.length; i++) {
require(
!policyIsRegistered(_policies[i]),
"registerPolicies: policy already registered"
);
registeredPolicies.add(_policies[i]);
// Store the hooks that a policy implements for later use.
// Fronts the gas for calls to check if a hook is implemented, and guarantees
// that the implementsHooks return value does not change post-registration.
IPolicy policyContract = IPolicy(_policies[i]);
PolicyHook[] memory implementedHooks = policyContract.implementedHooks();
for (uint256 j; j < implementedHooks.length; j++) {
policyToHookToIsImplemented[_policies[i]][implementedHooks[j]] = true;
}
emit PolicyRegistered(_policies[i], policyContract.identifier(), implementedHooks);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Get all registered policies
/// @return registeredPoliciesArray_ A list of all registered policy addresses
function getRegisteredPolicies()
external
view
returns (address[] memory registeredPoliciesArray_)
{
registeredPoliciesArray_ = new address[](registeredPolicies.length());
for (uint256 i; i < registeredPoliciesArray_.length; i++) {
registeredPoliciesArray_[i] = registeredPolicies.at(i);
}
}
/// @notice Get a list of enabled policies for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return enabledPolicies_ An array of enabled policy addresses
function getEnabledPoliciesForFund(address _comptrollerProxy)
public
view
returns (address[] memory enabledPolicies_)
{
enabledPolicies_ = new address[](comptrollerProxyToPolicies[_comptrollerProxy].length());
for (uint256 i; i < enabledPolicies_.length; i++) {
enabledPolicies_[i] = comptrollerProxyToPolicies[_comptrollerProxy].at(i);
}
}
/// @notice Checks if a policy implements a particular hook
/// @param _policy The address of the policy to check
/// @param _hook The PolicyHook to check
/// @return implementsHook_ True if the policy implements the hook
function policyImplementsHook(address _policy, PolicyHook _hook)
public
view
returns (bool implementsHook_)
{
return policyToHookToIsImplemented[_policy][_hook];
}
/// @notice Check if a policy is enabled for the fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund to check
/// @param _policy The address of the policy to check
/// @return isEnabled_ True if the policy is enabled for the fund
function policyIsEnabledForFund(address _comptrollerProxy, address _policy)
public
view
returns (bool isEnabled_)
{
return comptrollerProxyToPolicies[_comptrollerProxy].contains(_policy);
}
/// @notice Check whether a policy is registered
/// @param _policy The address of the policy to check
/// @return isRegistered_ True if the policy is registered
function policyIsRegistered(address _policy) public view returns (bool isRegistered_) {
return registeredPolicies.contains(_policy);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../persistent/utils/IMigratableVault.sol";
/// @title IVault Interface
/// @author Enzyme Council <[email protected]>
interface IVault is IMigratableVault {
function addTrackedAsset(address) external;
function approveAssetSpender(
address,
address,
uint256
) external;
function burnShares(address, uint256) external;
function callOnContract(address, bytes calldata) external;
function getAccessor() external view returns (address);
function getOwner() external view returns (address);
function getTrackedAssets() external view returns (address[] memory);
function isTrackedAsset(address) external view returns (bool);
function mintShares(address, uint256) external;
function removeTrackedAsset(address) external;
function transferShares(
address,
address,
uint256
) external;
function withdrawAssetTo(
address,
address,
uint256
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../core/fund/comptroller/IComptroller.sol";
import "../../core/fund/vault/IVault.sol";
import "../IExtension.sol";
/// @title ExtensionBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Base class for an extension
abstract contract ExtensionBase is IExtension {
mapping(address => address) internal comptrollerProxyToVaultProxy;
/// @notice Allows extension to run logic during fund activation
/// @dev Unimplemented by default, may be overridden.
function activateForFund(bool) external virtual override {
return;
}
/// @notice Allows extension to run logic during fund deactivation (destruct)
/// @dev Unimplemented by default, may be overridden.
function deactivateForFund() external virtual override {
return;
}
/// @notice Receives calls from ComptrollerLib.callOnExtension()
/// and dispatches the appropriate action
/// @dev Unimplemented by default, may be overridden.
function receiveCallFromComptroller(
address,
uint256,
bytes calldata
) external virtual override {
revert("receiveCallFromComptroller: Unimplemented for Extension");
}
/// @notice Allows extension to run logic during fund configuration
/// @dev Unimplemented by default, may be overridden.
function setConfigForFund(bytes calldata) external virtual override {
return;
}
/// @dev Helper to validate a ComptrollerProxy-VaultProxy relation, which we store for both
/// gas savings and to guarantee a spoofed ComptrollerProxy does not change getVaultProxy().
/// Will revert without reason if the expected interfaces do not exist.
function __setValidatedVaultProxy(address _comptrollerProxy)
internal
returns (address vaultProxy_)
{
require(
comptrollerProxyToVaultProxy[_comptrollerProxy] == address(0),
"__setValidatedVaultProxy: Already set"
);
vaultProxy_ = IComptroller(_comptrollerProxy).getVaultProxy();
require(vaultProxy_ != address(0), "__setValidatedVaultProxy: Missing vaultProxy");
require(
_comptrollerProxy == IVault(vaultProxy_).getAccessor(),
"__setValidatedVaultProxy: Not the VaultProxy accessor"
);
comptrollerProxyToVaultProxy[_comptrollerProxy] = vaultProxy_;
return vaultProxy_;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the verified VaultProxy for a given ComptrollerProxy
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return vaultProxy_ The VaultProxy of the fund
function getVaultProxyForFund(address _comptrollerProxy)
public
view
returns (address vaultProxy_)
{
return comptrollerProxyToVaultProxy[_comptrollerProxy];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./IPolicyManager.sol";
/// @title Policy Interface
/// @author Enzyme Council <[email protected]>
interface IPolicy {
function activateForFund(address _comptrollerProxy, address _vaultProxy) external;
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external;
function identifier() external pure returns (string memory identifier_);
function implementedHooks()
external
view
returns (IPolicyManager.PolicyHook[] memory implementedHooks_);
function updateFundSettings(
address _comptrollerProxy,
address _vaultProxy,
bytes calldata _encodedSettings
) external;
function validateRule(
address _comptrollerProxy,
address _vaultProxy,
IPolicyManager.PolicyHook _hook,
bytes calldata _encodedArgs
) external returns (bool isValid_);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title PolicyManager Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the PolicyManager
interface IPolicyManager {
enum PolicyHook {
BuySharesSetup,
PreBuyShares,
PostBuyShares,
BuySharesCompleted,
PreCallOnIntegration,
PostCallOnIntegration
}
function validatePolicies(
address,
PolicyHook,
bytes calldata
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IMigratableVault Interface
/// @author Enzyme Council <[email protected]>
/// @dev DO NOT EDIT CONTRACT
interface IMigratableVault {
function canMigrate(address _who) external view returns (bool canMigrate_);
function init(
address _owner,
address _accessor,
string calldata _fundName
) external;
function setAccessor(address _nextAccessor) external;
function setVaultLib(address _nextVaultLib) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IComptroller Interface
/// @author Enzyme Council <[email protected]>
interface IComptroller {
enum VaultAction {
None,
BurnShares,
MintShares,
TransferShares,
ApproveAssetSpender,
WithdrawAssetTo,
AddTrackedAsset,
RemoveTrackedAsset
}
function activate(address, bool) external;
function calcGav(bool) external returns (uint256, bool);
function calcGrossShareValue(bool) external returns (uint256, bool);
function callOnExtension(
address,
uint256,
bytes calldata
) external;
function configureExtensions(bytes calldata, bytes calldata) external;
function destruct() external;
function getDenominationAsset() external view returns (address);
function getVaultProxy() external view returns (address);
function init(address, uint256) external;
function permissionedVaultAction(VaultAction, bytes calldata) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExtension Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all extensions
interface IExtension {
function activateForFund(bool _isMigration) external;
function deactivateForFund() external;
function receiveCallFromComptroller(
address _comptrollerProxy,
uint256 _actionId,
bytes calldata _callArgs
) external;
function setConfigForFund(bytes calldata _configData) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../IPolicy.sol";
/// @title PolicyBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Abstract base contract for all policies
abstract contract PolicyBase is IPolicy {
address internal immutable POLICY_MANAGER;
modifier onlyPolicyManager {
require(msg.sender == POLICY_MANAGER, "Only the PolicyManager can make this call");
_;
}
constructor(address _policyManager) public {
POLICY_MANAGER = _policyManager;
}
/// @notice Validates and initializes a policy as necessary prior to fund activation
/// @dev Unimplemented by default, can be overridden by the policy
function activateForFund(address, address) external virtual override {
return;
}
/// @notice Updates the policy settings for a fund
/// @dev Disallowed by default, can be overridden by the policy
function updateFundSettings(
address,
address,
bytes calldata
) external virtual override {
revert("updateFundSettings: Updates not allowed for this policy");
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `POLICY_MANAGER` variable value
/// @return policyManager_ The `POLICY_MANAGER` variable value
function getPolicyManager() external view returns (address policyManager_) {
return POLICY_MANAGER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/PolicyBase.sol";
/// @title CallOnIntegrationPostValidatePolicyMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract for policies that only implement the PostCallOnIntegration policy hook
abstract contract PostCallOnIntegrationValidatePolicyBase is PolicyBase {
/// @notice Gets the implemented PolicyHooks for a policy
/// @return implementedHooks_ The implemented PolicyHooks
function implementedHooks()
external
view
override
returns (IPolicyManager.PolicyHook[] memory implementedHooks_)
{
implementedHooks_ = new IPolicyManager.PolicyHook[](1);
implementedHooks_[0] = IPolicyManager.PolicyHook.PostCallOnIntegration;
return implementedHooks_;
}
/// @notice Helper to decode rule arguments
function __decodeRuleArgs(bytes memory _encodedRuleArgs)
internal
pure
returns (
address adapter_,
bytes4 selector_,
address[] memory incomingAssets_,
uint256[] memory incomingAssetAmounts_,
address[] memory outgoingAssets_,
uint256[] memory outgoingAssetAmounts_
)
{
return
abi.decode(
_encodedRuleArgs,
(address, bytes4, address[], uint256[], address[], uint256[])
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../core/fund/comptroller/ComptrollerLib.sol";
import "../../../../core/fund/vault/VaultLib.sol";
import "../../../../infrastructure/value-interpreter/ValueInterpreter.sol";
import "./utils/PostCallOnIntegrationValidatePolicyBase.sol";
/// @title MaxConcentration Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that defines a configurable threshold for the concentration of any one asset
/// in a fund's holdings
contract MaxConcentration is PostCallOnIntegrationValidatePolicyBase {
using SafeMath for uint256;
event MaxConcentrationSet(address indexed comptrollerProxy, uint256 value);
uint256 private constant ONE_HUNDRED_PERCENT = 10**18; // 100%
address private immutable VALUE_INTERPRETER;
mapping(address => uint256) private comptrollerProxyToMaxConcentration;
constructor(address _policyManager, address _valueInterpreter)
public
PolicyBase(_policyManager)
{
VALUE_INTERPRETER = _valueInterpreter;
}
/// @notice Validates and initializes a policy as necessary prior to fund activation
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _vaultProxy The fund's VaultProxy address
/// @dev No need to authenticate access, as there are no state transitions
function activateForFund(address _comptrollerProxy, address _vaultProxy)
external
override
onlyPolicyManager
{
require(
passesRule(_comptrollerProxy, _vaultProxy, VaultLib(_vaultProxy).getTrackedAssets()),
"activateForFund: Max concentration exceeded"
);
}
/// @notice Add the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
uint256 maxConcentration = abi.decode(_encodedSettings, (uint256));
require(maxConcentration > 0, "addFundSettings: maxConcentration must be greater than 0");
require(
maxConcentration <= ONE_HUNDRED_PERCENT,
"addFundSettings: maxConcentration cannot exceed 100%"
);
comptrollerProxyToMaxConcentration[_comptrollerProxy] = maxConcentration;
emit MaxConcentrationSet(_comptrollerProxy, maxConcentration);
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "MAX_CONCENTRATION";
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _vaultProxy The fund's VaultProxy address
/// @param _assets The assets with which to check the rule
/// @return isValid_ True if the rule passes
/// @dev The fund's denomination asset is exempt from the policy limit.
function passesRule(
address _comptrollerProxy,
address _vaultProxy,
address[] memory _assets
) public returns (bool isValid_) {
uint256 maxConcentration = comptrollerProxyToMaxConcentration[_comptrollerProxy];
ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy);
address denominationAsset = comptrollerProxyContract.getDenominationAsset();
// Does not require asset finality, otherwise will fail when incoming asset is a Synth
(uint256 totalGav, bool gavIsValid) = comptrollerProxyContract.calcGav(false);
if (!gavIsValid) {
return false;
}
for (uint256 i = 0; i < _assets.length; i++) {
address asset = _assets[i];
if (
!__rulePassesForAsset(
_vaultProxy,
denominationAsset,
maxConcentration,
totalGav,
asset
)
) {
return false;
}
}
return true;
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _vaultProxy The fund's VaultProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address _vaultProxy,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs);
if (incomingAssets.length == 0) {
return true;
}
return passesRule(_comptrollerProxy, _vaultProxy, incomingAssets);
}
/// @dev Helper to check if the rule holds for a particular asset.
/// Avoids the stack-too-deep error.
function __rulePassesForAsset(
address _vaultProxy,
address _denominationAsset,
uint256 _maxConcentration,
uint256 _totalGav,
address _incomingAsset
) private returns (bool isValid_) {
if (_incomingAsset == _denominationAsset) return true;
uint256 assetBalance = ERC20(_incomingAsset).balanceOf(_vaultProxy);
(uint256 assetGav, bool assetGavIsValid) = ValueInterpreter(VALUE_INTERPRETER)
.calcLiveAssetValue(_incomingAsset, assetBalance, _denominationAsset);
if (
!assetGavIsValid ||
assetGav.mul(ONE_HUNDRED_PERCENT).div(_totalGav) > _maxConcentration
) {
return false;
}
return true;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the maxConcentration for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return maxConcentration_ The maxConcentration
function getMaxConcentrationForFund(address _comptrollerProxy)
external
view
returns (uint256 maxConcentration_)
{
return comptrollerProxyToMaxConcentration[_comptrollerProxy];
}
/// @notice Gets the `VALUE_INTERPRETER` variable
/// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value
function getValueInterpreter() external view returns (address valueInterpreter_) {
return VALUE_INTERPRETER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../../persistent/dispatcher/IDispatcher.sol";
import "../../../extensions/IExtension.sol";
import "../../../extensions/fee-manager/IFeeManager.sol";
import "../../../extensions/policy-manager/IPolicyManager.sol";
import "../../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol";
import "../../../infrastructure/value-interpreter/IValueInterpreter.sol";
import "../../../utils/AddressArrayLib.sol";
import "../../../utils/AssetFinalityResolver.sol";
import "../../fund-deployer/IFundDeployer.sol";
import "../vault/IVault.sol";
import "./IComptroller.sol";
/// @title ComptrollerLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice The core logic library shared by all funds
contract ComptrollerLib is IComptroller, AssetFinalityResolver {
using AddressArrayLib for address[];
using SafeMath for uint256;
using SafeERC20 for ERC20;
event MigratedSharesDuePaid(uint256 sharesDue);
event OverridePauseSet(bool indexed overridePause);
event PreRedeemSharesHookFailed(
bytes failureReturnData,
address redeemer,
uint256 sharesQuantity
);
event SharesBought(
address indexed caller,
address indexed buyer,
uint256 investmentAmount,
uint256 sharesIssued,
uint256 sharesReceived
);
event SharesRedeemed(
address indexed redeemer,
uint256 sharesQuantity,
address[] receivedAssets,
uint256[] receivedAssetQuantities
);
event VaultProxySet(address vaultProxy);
// Constants and immutables - shared by all proxies
uint256 private constant SHARES_UNIT = 10**18;
address private immutable DISPATCHER;
address private immutable FUND_DEPLOYER;
address private immutable FEE_MANAGER;
address private immutable INTEGRATION_MANAGER;
address private immutable PRIMITIVE_PRICE_FEED;
address private immutable POLICY_MANAGER;
address private immutable VALUE_INTERPRETER;
// Pseudo-constants (can only be set once)
address internal denominationAsset;
address internal vaultProxy;
// True only for the one non-proxy
bool internal isLib;
// Storage
// Allows a fund owner to override a release-level pause
bool internal overridePause;
// A reverse-mutex, granting atomic permission for particular contracts to make vault calls
bool internal permissionedVaultActionAllowed;
// A mutex to protect against reentrancy
bool internal reentranceLocked;
// A timelock between any "shares actions" (i.e., buy and redeem shares), per-account
uint256 internal sharesActionTimelock;
mapping(address => uint256) internal acctToLastSharesAction;
///////////////
// MODIFIERS //
///////////////
modifier allowsPermissionedVaultAction {
__assertPermissionedVaultActionNotAllowed();
permissionedVaultActionAllowed = true;
_;
permissionedVaultActionAllowed = false;
}
modifier locksReentrance() {
__assertNotReentranceLocked();
reentranceLocked = true;
_;
reentranceLocked = false;
}
modifier onlyActive() {
__assertIsActive(vaultProxy);
_;
}
modifier onlyNotPaused() {
__assertNotPaused();
_;
}
modifier onlyFundDeployer() {
__assertIsFundDeployer(msg.sender);
_;
}
modifier onlyOwner() {
__assertIsOwner(msg.sender);
_;
}
modifier timelockedSharesAction(address _account) {
__assertSharesActionNotTimelocked(_account);
_;
acctToLastSharesAction[_account] = block.timestamp;
}
// ASSERTION HELPERS
// Modifiers are inefficient in terms of contract size,
// so we use helper functions to prevent repetitive inlining of expensive string values.
/// @dev Since vaultProxy is set during activate(),
/// we can check that var rather than storing additional state
function __assertIsActive(address _vaultProxy) private pure {
require(_vaultProxy != address(0), "Fund not active");
}
function __assertIsFundDeployer(address _who) private view {
require(_who == FUND_DEPLOYER, "Only FundDeployer callable");
}
function __assertIsOwner(address _who) private view {
require(_who == IVault(vaultProxy).getOwner(), "Only fund owner callable");
}
function __assertLowLevelCall(bool _success, bytes memory _returnData) private pure {
require(_success, string(_returnData));
}
function __assertNotPaused() private view {
require(!__fundIsPaused(), "Fund is paused");
}
function __assertNotReentranceLocked() private view {
require(!reentranceLocked, "Re-entrance");
}
function __assertPermissionedVaultActionNotAllowed() private view {
require(!permissionedVaultActionAllowed, "Vault action re-entrance");
}
function __assertSharesActionNotTimelocked(address _account) private view {
require(
block.timestamp.sub(acctToLastSharesAction[_account]) >= sharesActionTimelock,
"Shares action timelocked"
);
}
constructor(
address _dispatcher,
address _fundDeployer,
address _valueInterpreter,
address _feeManager,
address _integrationManager,
address _policyManager,
address _primitivePriceFeed,
address _synthetixPriceFeed,
address _synthetixAddressResolver
) public AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver) {
DISPATCHER = _dispatcher;
FEE_MANAGER = _feeManager;
FUND_DEPLOYER = _fundDeployer;
INTEGRATION_MANAGER = _integrationManager;
PRIMITIVE_PRICE_FEED = _primitivePriceFeed;
POLICY_MANAGER = _policyManager;
VALUE_INTERPRETER = _valueInterpreter;
isLib = true;
}
/////////////
// GENERAL //
/////////////
/// @notice Calls a specified action on an Extension
/// @param _extension The Extension contract to call (e.g., FeeManager)
/// @param _actionId An ID representing the action to take on the extension (see extension)
/// @param _callArgs The encoded data for the call
/// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy
/// (for access control). Uses a mutex of sorts that allows "permissioned vault actions"
/// during calls originating from this function.
function callOnExtension(
address _extension,
uint256 _actionId,
bytes calldata _callArgs
) external override onlyNotPaused onlyActive locksReentrance allowsPermissionedVaultAction {
require(
_extension == FEE_MANAGER || _extension == INTEGRATION_MANAGER,
"callOnExtension: _extension invalid"
);
IExtension(_extension).receiveCallFromComptroller(msg.sender, _actionId, _callArgs);
}
/// @notice Sets or unsets an override on a release-wide pause
/// @param _nextOverridePause True if the pause should be overrode
function setOverridePause(bool _nextOverridePause) external onlyOwner {
require(_nextOverridePause != overridePause, "setOverridePause: Value already set");
overridePause = _nextOverridePause;
emit OverridePauseSet(_nextOverridePause);
}
/// @notice Makes an arbitrary call with the VaultProxy contract as the sender
/// @param _contract The contract to call
/// @param _selector The selector to call
/// @param _encodedArgs The encoded arguments for the call
function vaultCallOnContract(
address _contract,
bytes4 _selector,
bytes calldata _encodedArgs
) external onlyNotPaused onlyActive onlyOwner {
require(
IFundDeployer(FUND_DEPLOYER).isRegisteredVaultCall(_contract, _selector),
"vaultCallOnContract: Unregistered"
);
IVault(vaultProxy).callOnContract(_contract, abi.encodePacked(_selector, _encodedArgs));
}
/// @dev Helper to check whether the release is paused, and that there is no local override
function __fundIsPaused() private view returns (bool) {
return
IFundDeployer(FUND_DEPLOYER).getReleaseStatus() ==
IFundDeployer.ReleaseStatus.Paused &&
!overridePause;
}
////////////////////////////////
// PERMISSIONED VAULT ACTIONS //
////////////////////////////////
/// @notice Makes a permissioned, state-changing call on the VaultProxy contract
/// @param _action The enum representing the VaultAction to perform on the VaultProxy
/// @param _actionData The call data for the action to perform
function permissionedVaultAction(VaultAction _action, bytes calldata _actionData)
external
override
onlyNotPaused
onlyActive
{
__assertPermissionedVaultAction(msg.sender, _action);
if (_action == VaultAction.AddTrackedAsset) {
__vaultActionAddTrackedAsset(_actionData);
} else if (_action == VaultAction.ApproveAssetSpender) {
__vaultActionApproveAssetSpender(_actionData);
} else if (_action == VaultAction.BurnShares) {
__vaultActionBurnShares(_actionData);
} else if (_action == VaultAction.MintShares) {
__vaultActionMintShares(_actionData);
} else if (_action == VaultAction.RemoveTrackedAsset) {
__vaultActionRemoveTrackedAsset(_actionData);
} else if (_action == VaultAction.TransferShares) {
__vaultActionTransferShares(_actionData);
} else if (_action == VaultAction.WithdrawAssetTo) {
__vaultActionWithdrawAssetTo(_actionData);
}
}
/// @dev Helper to assert that a caller is allowed to perform a particular VaultAction
function __assertPermissionedVaultAction(address _caller, VaultAction _action) private view {
require(
permissionedVaultActionAllowed,
"__assertPermissionedVaultAction: No action allowed"
);
if (_caller == INTEGRATION_MANAGER) {
require(
_action == VaultAction.ApproveAssetSpender ||
_action == VaultAction.AddTrackedAsset ||
_action == VaultAction.RemoveTrackedAsset ||
_action == VaultAction.WithdrawAssetTo,
"__assertPermissionedVaultAction: Not valid for IntegrationManager"
);
} else if (_caller == FEE_MANAGER) {
require(
_action == VaultAction.BurnShares ||
_action == VaultAction.MintShares ||
_action == VaultAction.TransferShares,
"__assertPermissionedVaultAction: Not valid for FeeManager"
);
} else {
revert("__assertPermissionedVaultAction: Not a valid actor");
}
}
/// @dev Helper to add a tracked asset to the fund
function __vaultActionAddTrackedAsset(bytes memory _actionData) private {
address asset = abi.decode(_actionData, (address));
IVault(vaultProxy).addTrackedAsset(asset);
}
/// @dev Helper to grant a spender an allowance for a fund's asset
function __vaultActionApproveAssetSpender(bytes memory _actionData) private {
(address asset, address target, uint256 amount) = abi.decode(
_actionData,
(address, address, uint256)
);
IVault(vaultProxy).approveAssetSpender(asset, target, amount);
}
/// @dev Helper to burn fund shares for a particular account
function __vaultActionBurnShares(bytes memory _actionData) private {
(address target, uint256 amount) = abi.decode(_actionData, (address, uint256));
IVault(vaultProxy).burnShares(target, amount);
}
/// @dev Helper to mint fund shares to a particular account
function __vaultActionMintShares(bytes memory _actionData) private {
(address target, uint256 amount) = abi.decode(_actionData, (address, uint256));
IVault(vaultProxy).mintShares(target, amount);
}
/// @dev Helper to remove a tracked asset from the fund
function __vaultActionRemoveTrackedAsset(bytes memory _actionData) private {
address asset = abi.decode(_actionData, (address));
// Allowing this to fail silently makes it cheaper and simpler
// for Extensions to not query for the denomination asset
if (asset != denominationAsset) {
IVault(vaultProxy).removeTrackedAsset(asset);
}
}
/// @dev Helper to transfer fund shares from one account to another
function __vaultActionTransferShares(bytes memory _actionData) private {
(address from, address to, uint256 amount) = abi.decode(
_actionData,
(address, address, uint256)
);
IVault(vaultProxy).transferShares(from, to, amount);
}
/// @dev Helper to withdraw an asset from the VaultProxy to a given account
function __vaultActionWithdrawAssetTo(bytes memory _actionData) private {
(address asset, address target, uint256 amount) = abi.decode(
_actionData,
(address, address, uint256)
);
IVault(vaultProxy).withdrawAssetTo(asset, target, amount);
}
///////////////
// LIFECYCLE //
///////////////
/// @notice Initializes a fund with its core config
/// @param _denominationAsset The asset in which the fund's value should be denominated
/// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions"
/// (buying or selling shares) by the same user
/// @dev Pseudo-constructor per proxy.
/// No need to assert access because this is called atomically on deployment,
/// and once it's called, it cannot be called again.
function init(address _denominationAsset, uint256 _sharesActionTimelock) external override {
require(denominationAsset == address(0), "init: Already initialized");
require(
IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_denominationAsset),
"init: Bad denomination asset"
);
denominationAsset = _denominationAsset;
sharesActionTimelock = _sharesActionTimelock;
}
/// @notice Configure the extensions of a fund
/// @param _feeManagerConfigData Encoded config for fees to enable
/// @param _policyManagerConfigData Encoded config for policies to enable
/// @dev No need to assert anything beyond FundDeployer access.
/// Called atomically with init(), but after ComptrollerLib has been deployed,
/// giving access to its state and interface
function configureExtensions(
bytes calldata _feeManagerConfigData,
bytes calldata _policyManagerConfigData
) external override onlyFundDeployer {
if (_feeManagerConfigData.length > 0) {
IExtension(FEE_MANAGER).setConfigForFund(_feeManagerConfigData);
}
if (_policyManagerConfigData.length > 0) {
IExtension(POLICY_MANAGER).setConfigForFund(_policyManagerConfigData);
}
}
/// @notice Activates the fund by attaching a VaultProxy and activating all Extensions
/// @param _vaultProxy The VaultProxy to attach to the fund
/// @param _isMigration True if a migrated fund is being activated
/// @dev No need to assert anything beyond FundDeployer access.
function activate(address _vaultProxy, bool _isMigration) external override onlyFundDeployer {
vaultProxy = _vaultProxy;
emit VaultProxySet(_vaultProxy);
if (_isMigration) {
// Distribute any shares in the VaultProxy to the fund owner.
// This is a mechanism to ensure that even in the edge case of a fund being unable
// to payout fee shares owed during migration, these shares are not lost.
uint256 sharesDue = ERC20(_vaultProxy).balanceOf(_vaultProxy);
if (sharesDue > 0) {
IVault(_vaultProxy).transferShares(
_vaultProxy,
IVault(_vaultProxy).getOwner(),
sharesDue
);
emit MigratedSharesDuePaid(sharesDue);
}
}
// Note: a future release could consider forcing the adding of a tracked asset here,
// just in case a fund is migrating from an old configuration where they are not able
// to remove an asset to get under the tracked assets limit
IVault(_vaultProxy).addTrackedAsset(denominationAsset);
// Activate extensions
IExtension(FEE_MANAGER).activateForFund(_isMigration);
IExtension(INTEGRATION_MANAGER).activateForFund(_isMigration);
IExtension(POLICY_MANAGER).activateForFund(_isMigration);
}
/// @notice Remove the config for a fund
/// @dev No need to assert anything beyond FundDeployer access.
/// Calling onlyNotPaused here rather than in the FundDeployer allows
/// the owner to potentially override the pause and rescue unpaid fees.
function destruct()
external
override
onlyFundDeployer
onlyNotPaused
allowsPermissionedVaultAction
{
// Failsafe to protect the libs against selfdestruct
require(!isLib, "destruct: Only delegate callable");
// Deactivate the extensions
IExtension(FEE_MANAGER).deactivateForFund();
IExtension(INTEGRATION_MANAGER).deactivateForFund();
IExtension(POLICY_MANAGER).deactivateForFund();
// Delete storage of ComptrollerProxy
// There should never be ETH in the ComptrollerLib, so no need to waste gas
// to get the fund owner
selfdestruct(address(0));
}
////////////////
// ACCOUNTING //
////////////////
/// @notice Calculates the gross asset value (GAV) of the fund
/// @param _requireFinality True if all assets must have exact final balances settled
/// @return gav_ The fund GAV
/// @return isValid_ True if the conversion rates used to derive the GAV are all valid
function calcGav(bool _requireFinality) public override returns (uint256 gav_, bool isValid_) {
address vaultProxyAddress = vaultProxy;
address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets();
if (assets.length == 0) {
return (0, true);
}
uint256[] memory balances = new uint256[](assets.length);
for (uint256 i; i < assets.length; i++) {
balances[i] = __finalizeIfSynthAndGetAssetBalance(
vaultProxyAddress,
assets[i],
_requireFinality
);
}
(gav_, isValid_) = IValueInterpreter(VALUE_INTERPRETER).calcCanonicalAssetsTotalValue(
assets,
balances,
denominationAsset
);
return (gav_, isValid_);
}
/// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset
/// @param _requireFinality True if all assets must have exact final balances settled
/// @return grossShareValue_ The amount of the denomination asset per share
/// @return isValid_ True if the conversion rates to derive the value are all valid
/// @dev Does not account for any fees outstanding.
function calcGrossShareValue(bool _requireFinality)
external
override
returns (uint256 grossShareValue_, bool isValid_)
{
uint256 gav;
(gav, isValid_) = calcGav(_requireFinality);
grossShareValue_ = __calcGrossShareValue(
gav,
ERC20(vaultProxy).totalSupply(),
10**uint256(ERC20(denominationAsset).decimals())
);
return (grossShareValue_, isValid_);
}
/// @dev Helper for calculating the gross share value
function __calcGrossShareValue(
uint256 _gav,
uint256 _sharesSupply,
uint256 _denominationAssetUnit
) private pure returns (uint256 grossShareValue_) {
if (_sharesSupply == 0) {
return _denominationAssetUnit;
}
return _gav.mul(SHARES_UNIT).div(_sharesSupply);
}
///////////////////
// PARTICIPATION //
///////////////////
// BUY SHARES
/// @notice Buys shares in the fund for multiple sets of criteria
/// @param _buyers The accounts for which to buy shares
/// @param _investmentAmounts The amounts of the fund's denomination asset
/// with which to buy shares for the corresponding _buyers
/// @param _minSharesQuantities The minimum quantities of shares to buy
/// with the corresponding _investmentAmounts
/// @return sharesReceivedAmounts_ The actual amounts of shares received
/// by the corresponding _buyers
/// @dev Param arrays have indexes corresponding to individual __buyShares() orders.
function buyShares(
address[] calldata _buyers,
uint256[] calldata _investmentAmounts,
uint256[] calldata _minSharesQuantities
)
external
onlyNotPaused
locksReentrance
allowsPermissionedVaultAction
returns (uint256[] memory sharesReceivedAmounts_)
{
require(_buyers.length > 0, "buyShares: Empty _buyers");
require(
_buyers.length == _investmentAmounts.length &&
_buyers.length == _minSharesQuantities.length,
"buyShares: Unequal arrays"
);
address vaultProxyCopy = vaultProxy;
__assertIsActive(vaultProxyCopy);
require(
!IDispatcher(DISPATCHER).hasMigrationRequest(vaultProxyCopy),
"buyShares: Pending migration"
);
(uint256 gav, bool gavIsValid) = calcGav(true);
require(gavIsValid, "buyShares: Invalid GAV");
__buySharesSetupHook(msg.sender, _investmentAmounts, gav);
address denominationAssetCopy = denominationAsset;
uint256 sharePrice = __calcGrossShareValue(
gav,
ERC20(vaultProxyCopy).totalSupply(),
10**uint256(ERC20(denominationAssetCopy).decimals())
);
sharesReceivedAmounts_ = new uint256[](_buyers.length);
for (uint256 i; i < _buyers.length; i++) {
sharesReceivedAmounts_[i] = __buyShares(
_buyers[i],
_investmentAmounts[i],
_minSharesQuantities[i],
vaultProxyCopy,
sharePrice,
gav,
denominationAssetCopy
);
gav = gav.add(_investmentAmounts[i]);
}
__buySharesCompletedHook(msg.sender, sharesReceivedAmounts_, gav);
return sharesReceivedAmounts_;
}
/// @dev Helper to buy shares
function __buyShares(
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity,
address _vaultProxy,
uint256 _sharePrice,
uint256 _preBuySharesGav,
address _denominationAsset
) private timelockedSharesAction(_buyer) returns (uint256 sharesReceived_) {
require(_investmentAmount > 0, "__buyShares: Empty _investmentAmount");
// Gives Extensions a chance to run logic prior to the minting of bought shares
__preBuySharesHook(_buyer, _investmentAmount, _minSharesQuantity, _preBuySharesGav);
// Calculate the amount of shares to issue with the investment amount
uint256 sharesIssued = _investmentAmount.mul(SHARES_UNIT).div(_sharePrice);
// Mint shares to the buyer
uint256 prevBuyerShares = ERC20(_vaultProxy).balanceOf(_buyer);
IVault(_vaultProxy).mintShares(_buyer, sharesIssued);
// Transfer the investment asset to the fund.
// Does not follow the checks-effects-interactions pattern, but it is preferred
// to have the final state of the VaultProxy prior to running __postBuySharesHook().
ERC20(_denominationAsset).safeTransferFrom(msg.sender, _vaultProxy, _investmentAmount);
// Gives Extensions a chance to run logic after shares are issued
__postBuySharesHook(_buyer, _investmentAmount, sharesIssued, _preBuySharesGav);
// The number of actual shares received may differ from shares issued due to
// how the PostBuyShares hooks are invoked by Extensions (i.e., fees)
sharesReceived_ = ERC20(_vaultProxy).balanceOf(_buyer).sub(prevBuyerShares);
require(
sharesReceived_ >= _minSharesQuantity,
"__buyShares: Shares received < _minSharesQuantity"
);
emit SharesBought(msg.sender, _buyer, _investmentAmount, sharesIssued, sharesReceived_);
return sharesReceived_;
}
/// @dev Helper for Extension actions after all __buyShares() calls are made
function __buySharesCompletedHook(
address _caller,
uint256[] memory _sharesReceivedAmounts,
uint256 _gav
) private {
IPolicyManager(POLICY_MANAGER).validatePolicies(
address(this),
IPolicyManager.PolicyHook.BuySharesCompleted,
abi.encode(_caller, _sharesReceivedAmounts, _gav)
);
IFeeManager(FEE_MANAGER).invokeHook(
IFeeManager.FeeHook.BuySharesCompleted,
abi.encode(_caller, _sharesReceivedAmounts),
_gav
);
}
/// @dev Helper for Extension actions before any __buyShares() calls are made
function __buySharesSetupHook(
address _caller,
uint256[] memory _investmentAmounts,
uint256 _gav
) private {
IPolicyManager(POLICY_MANAGER).validatePolicies(
address(this),
IPolicyManager.PolicyHook.BuySharesSetup,
abi.encode(_caller, _investmentAmounts, _gav)
);
IFeeManager(FEE_MANAGER).invokeHook(
IFeeManager.FeeHook.BuySharesSetup,
abi.encode(_caller, _investmentAmounts),
_gav
);
}
/// @dev Helper for Extension actions immediately prior to issuing shares.
/// This could be cleaned up so both Extensions take the same encoded args and handle GAV
/// in the same way, but there is not the obvious need for gas savings of recycling
/// the GAV value for the current policies as there is for the fees.
function __preBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity,
uint256 _gav
) private {
IFeeManager(FEE_MANAGER).invokeHook(
IFeeManager.FeeHook.PreBuyShares,
abi.encode(_buyer, _investmentAmount, _minSharesQuantity),
_gav
);
IPolicyManager(POLICY_MANAGER).validatePolicies(
address(this),
IPolicyManager.PolicyHook.PreBuyShares,
abi.encode(_buyer, _investmentAmount, _minSharesQuantity, _gav)
);
}
/// @dev Helper for Extension actions immediately after issuing shares.
/// Same comment applies from __preBuySharesHook() above.
function __postBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _sharesIssued,
uint256 _preBuySharesGav
) private {
uint256 gav = _preBuySharesGav.add(_investmentAmount);
IFeeManager(FEE_MANAGER).invokeHook(
IFeeManager.FeeHook.PostBuyShares,
abi.encode(_buyer, _investmentAmount, _sharesIssued),
gav
);
IPolicyManager(POLICY_MANAGER).validatePolicies(
address(this),
IPolicyManager.PolicyHook.PostBuyShares,
abi.encode(_buyer, _investmentAmount, _sharesIssued, gav)
);
}
// REDEEM SHARES
/// @notice Redeem all of the sender's shares for a proportionate slice of the fund's assets
/// @return payoutAssets_ The assets paid out to the redeemer
/// @return payoutAmounts_ The amount of each asset paid out to the redeemer
/// @dev See __redeemShares() for further detail
function redeemShares()
external
returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_)
{
return
__redeemShares(
msg.sender,
ERC20(vaultProxy).balanceOf(msg.sender),
new address[](0),
new address[](0)
);
}
/// @notice Redeem a specified quantity of the sender's shares for a proportionate slice of
/// the fund's assets, optionally specifying additional assets and assets to skip.
/// @param _sharesQuantity The quantity of shares to redeem
/// @param _additionalAssets Additional (non-tracked) assets to claim
/// @param _assetsToSkip Tracked assets to forfeit
/// @return payoutAssets_ The assets paid out to the redeemer
/// @return payoutAmounts_ The amount of each asset paid out to the redeemer
/// @dev Any claim to passed _assetsToSkip will be forfeited entirely. This should generally
/// only be exercised if a bad asset is causing redemption to fail.
function redeemSharesDetailed(
uint256 _sharesQuantity,
address[] calldata _additionalAssets,
address[] calldata _assetsToSkip
) external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) {
return __redeemShares(msg.sender, _sharesQuantity, _additionalAssets, _assetsToSkip);
}
/// @dev Helper to parse an array of payout assets during redemption, taking into account
/// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets.
/// All input arrays are assumed to be unique.
function __parseRedemptionPayoutAssets(
address[] memory _trackedAssets,
address[] memory _additionalAssets,
address[] memory _assetsToSkip
) private pure returns (address[] memory payoutAssets_) {
address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip);
if (_additionalAssets.length == 0) {
return trackedAssetsToPayout;
}
// Add additional assets. Duplicates of trackedAssets are ignored.
bool[] memory indexesToAdd = new bool[](_additionalAssets.length);
uint256 additionalItemsCount;
for (uint256 i; i < _additionalAssets.length; i++) {
if (!trackedAssetsToPayout.contains(_additionalAssets[i])) {
indexesToAdd[i] = true;
additionalItemsCount++;
}
}
if (additionalItemsCount == 0) {
return trackedAssetsToPayout;
}
payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount));
for (uint256 i; i < trackedAssetsToPayout.length; i++) {
payoutAssets_[i] = trackedAssetsToPayout[i];
}
uint256 payoutAssetsIndex = trackedAssetsToPayout.length;
for (uint256 i; i < _additionalAssets.length; i++) {
if (indexesToAdd[i]) {
payoutAssets_[payoutAssetsIndex] = _additionalAssets[i];
payoutAssetsIndex++;
}
}
return payoutAssets_;
}
/// @dev Helper for system actions immediately prior to redeeming shares.
/// Policy validation is not currently allowed on redemption, to ensure continuous redeemability.
function __preRedeemSharesHook(address _redeemer, uint256 _sharesQuantity)
private
allowsPermissionedVaultAction
{
try
IFeeManager(FEE_MANAGER).invokeHook(
IFeeManager.FeeHook.PreRedeemShares,
abi.encode(_redeemer, _sharesQuantity),
0
)
{} catch (bytes memory reason) {
emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesQuantity);
}
}
/// @dev Helper to redeem shares.
/// This function should never fail without a way to bypass the failure, which is assured
/// through two mechanisms:
/// 1. The FeeManager is called with the try/catch pattern to assure that calls to it
/// can never block redemption.
/// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited)
/// by explicitly specifying _assetsToSkip.
/// Because of these assurances, shares should always be redeemable, with the exception
/// of the timelock period on shares actions that must be respected.
function __redeemShares(
address _redeemer,
uint256 _sharesQuantity,
address[] memory _additionalAssets,
address[] memory _assetsToSkip
)
private
locksReentrance
returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_)
{
require(_sharesQuantity > 0, "__redeemShares: _sharesQuantity must be >0");
require(
_additionalAssets.isUniqueSet(),
"__redeemShares: _additionalAssets contains duplicates"
);
require(_assetsToSkip.isUniqueSet(), "__redeemShares: _assetsToSkip contains duplicates");
IVault vaultProxyContract = IVault(vaultProxy);
// Only apply the sharesActionTimelock when a migration is not pending
if (!IDispatcher(DISPATCHER).hasMigrationRequest(address(vaultProxyContract))) {
__assertSharesActionNotTimelocked(_redeemer);
acctToLastSharesAction[_redeemer] = block.timestamp;
}
// When a fund is paused, settling fees will be skipped
if (!__fundIsPaused()) {
// Note that if a fee with `SettlementType.Direct` is charged here (i.e., not `Mint`),
// then those fee shares will be transferred from the user's balance rather
// than reallocated from the sharesQuantity being redeemed.
__preRedeemSharesHook(_redeemer, _sharesQuantity);
}
// Check the shares quantity against the user's balance after settling fees
ERC20 sharesContract = ERC20(address(vaultProxyContract));
require(
_sharesQuantity <= sharesContract.balanceOf(_redeemer),
"__redeemShares: Insufficient shares"
);
// Parse the payout assets given optional params to add or skip assets.
// Note that there is no validation that the _additionalAssets are known assets to
// the protocol. This means that the redeemer could specify a malicious asset,
// but since all state-changing, user-callable functions on this contract share the
// non-reentrant modifier, there is nowhere to perform a reentrancy attack.
payoutAssets_ = __parseRedemptionPayoutAssets(
vaultProxyContract.getTrackedAssets(),
_additionalAssets,
_assetsToSkip
);
require(payoutAssets_.length > 0, "__redeemShares: No payout assets");
// Destroy the shares.
// Must get the shares supply before doing so.
uint256 sharesSupply = sharesContract.totalSupply();
vaultProxyContract.burnShares(_redeemer, _sharesQuantity);
// Calculate and transfer payout asset amounts due to redeemer
payoutAmounts_ = new uint256[](payoutAssets_.length);
address denominationAssetCopy = denominationAsset;
for (uint256 i; i < payoutAssets_.length; i++) {
uint256 assetBalance = __finalizeIfSynthAndGetAssetBalance(
address(vaultProxyContract),
payoutAssets_[i],
true
);
// If all remaining shares are being redeemed, the logic changes slightly
if (_sharesQuantity == sharesSupply) {
payoutAmounts_[i] = assetBalance;
// Remove every tracked asset, except the denomination asset
if (payoutAssets_[i] != denominationAssetCopy) {
vaultProxyContract.removeTrackedAsset(payoutAssets_[i]);
}
} else {
payoutAmounts_[i] = assetBalance.mul(_sharesQuantity).div(sharesSupply);
}
// Transfer payout asset to redeemer
if (payoutAmounts_[i] > 0) {
vaultProxyContract.withdrawAssetTo(payoutAssets_[i], _redeemer, payoutAmounts_[i]);
}
}
emit SharesRedeemed(_redeemer, _sharesQuantity, payoutAssets_, payoutAmounts_);
return (payoutAssets_, payoutAmounts_);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `denominationAsset` variable
/// @return denominationAsset_ The `denominationAsset` variable value
function getDenominationAsset() external view override returns (address denominationAsset_) {
return denominationAsset;
}
/// @notice Gets the routes for the various contracts used by all funds
/// @return dispatcher_ The `DISPATCHER` variable value
/// @return feeManager_ The `FEE_MANAGER` variable value
/// @return fundDeployer_ The `FUND_DEPLOYER` variable value
/// @return integrationManager_ The `INTEGRATION_MANAGER` variable value
/// @return policyManager_ The `POLICY_MANAGER` variable value
/// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value
/// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value
function getLibRoutes()
external
view
returns (
address dispatcher_,
address feeManager_,
address fundDeployer_,
address integrationManager_,
address policyManager_,
address primitivePriceFeed_,
address valueInterpreter_
)
{
return (
DISPATCHER,
FEE_MANAGER,
FUND_DEPLOYER,
INTEGRATION_MANAGER,
POLICY_MANAGER,
PRIMITIVE_PRICE_FEED,
VALUE_INTERPRETER
);
}
/// @notice Gets the `overridePause` variable
/// @return overridePause_ The `overridePause` variable value
function getOverridePause() external view returns (bool overridePause_) {
return overridePause;
}
/// @notice Gets the `sharesActionTimelock` variable
/// @return sharesActionTimelock_ The `sharesActionTimelock` variable value
function getSharesActionTimelock() external view returns (uint256 sharesActionTimelock_) {
return sharesActionTimelock;
}
/// @notice Gets the `vaultProxy` variable
/// @return vaultProxy_ The `vaultProxy` variable value
function getVaultProxy() external view override returns (address vaultProxy_) {
return vaultProxy;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../../persistent/dispatcher/IDispatcher.sol";
import "../../../../persistent/vault/VaultLibBase1.sol";
import "./IVault.sol";
/// @title VaultLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice The per-release proxiable library contract for VaultProxy
/// @dev The difference in terminology between "asset" and "trackedAsset" is intentional.
/// A fund might actually have asset balances of un-tracked assets,
/// but only tracked assets are used in gav calculations.
/// Note that this contract inherits VaultLibSafeMath (a verbatim Open Zeppelin SafeMath copy)
/// from SharesTokenBase via VaultLibBase1
contract VaultLib is VaultLibBase1, IVault {
using SafeERC20 for ERC20;
// Before updating TRACKED_ASSETS_LIMIT in the future, it is important to consider:
// 1. The highest tracked assets limit ever allowed in the protocol
// 2. That the next value will need to be respected by all future releases
uint256 private constant TRACKED_ASSETS_LIMIT = 20;
modifier onlyAccessor() {
require(msg.sender == accessor, "Only the designated accessor can make this call");
_;
}
/////////////
// GENERAL //
/////////////
/// @notice Sets the account that is allowed to migrate a fund to new releases
/// @param _nextMigrator The account to set as the allowed migrator
/// @dev Set to address(0) to remove the migrator.
function setMigrator(address _nextMigrator) external {
require(msg.sender == owner, "setMigrator: Only the owner can call this function");
address prevMigrator = migrator;
require(_nextMigrator != prevMigrator, "setMigrator: Value already set");
migrator = _nextMigrator;
emit MigratorSet(prevMigrator, _nextMigrator);
}
///////////
// VAULT //
///////////
/// @notice Adds a tracked asset to the fund
/// @param _asset The asset to add
/// @dev Allows addition of already tracked assets to fail silently.
function addTrackedAsset(address _asset) external override onlyAccessor {
if (!isTrackedAsset(_asset)) {
require(
trackedAssets.length < TRACKED_ASSETS_LIMIT,
"addTrackedAsset: Limit exceeded"
);
assetToIsTracked[_asset] = true;
trackedAssets.push(_asset);
emit TrackedAssetAdded(_asset);
}
}
/// @notice Grants an allowance to a spender to use the fund's asset
/// @param _asset The asset for which to grant an allowance
/// @param _target The spender of the allowance
/// @param _amount The amount of the allowance
function approveAssetSpender(
address _asset,
address _target,
uint256 _amount
) external override onlyAccessor {
ERC20(_asset).approve(_target, _amount);
}
/// @notice Makes an arbitrary call with this contract as the sender
/// @param _contract The contract to call
/// @param _callData The call data for the call
function callOnContract(address _contract, bytes calldata _callData)
external
override
onlyAccessor
{
(bool success, bytes memory returnData) = _contract.call(_callData);
require(success, string(returnData));
}
/// @notice Removes a tracked asset from the fund
/// @param _asset The asset to remove
function removeTrackedAsset(address _asset) external override onlyAccessor {
__removeTrackedAsset(_asset);
}
/// @notice Withdraws an asset from the VaultProxy to a given account
/// @param _asset The asset to withdraw
/// @param _target The account to which to withdraw the asset
/// @param _amount The amount of asset to withdraw
function withdrawAssetTo(
address _asset,
address _target,
uint256 _amount
) external override onlyAccessor {
ERC20(_asset).safeTransfer(_target, _amount);
emit AssetWithdrawn(_asset, _target, _amount);
}
/// @dev Helper to the get the Vault's balance of a given asset
function __getAssetBalance(address _asset) private view returns (uint256 balance_) {
return ERC20(_asset).balanceOf(address(this));
}
/// @dev Helper to remove an asset from a fund's tracked assets.
/// Allows removal of non-tracked asset to fail silently.
function __removeTrackedAsset(address _asset) private {
if (isTrackedAsset(_asset)) {
assetToIsTracked[_asset] = false;
uint256 trackedAssetsCount = trackedAssets.length;
for (uint256 i = 0; i < trackedAssetsCount; i++) {
if (trackedAssets[i] == _asset) {
if (i < trackedAssetsCount - 1) {
trackedAssets[i] = trackedAssets[trackedAssetsCount - 1];
}
trackedAssets.pop();
break;
}
}
emit TrackedAssetRemoved(_asset);
}
}
////////////
// SHARES //
////////////
/// @notice Burns fund shares from a particular account
/// @param _target The account for which to burn shares
/// @param _amount The amount of shares to burn
function burnShares(address _target, uint256 _amount) external override onlyAccessor {
__burn(_target, _amount);
}
/// @notice Mints fund shares to a particular account
/// @param _target The account for which to burn shares
/// @param _amount The amount of shares to mint
function mintShares(address _target, uint256 _amount) external override onlyAccessor {
__mint(_target, _amount);
}
/// @notice Transfers fund shares from one account to another
/// @param _from The account from which to transfer shares
/// @param _to The account to which to transfer shares
/// @param _amount The amount of shares to transfer
function transferShares(
address _from,
address _to,
uint256 _amount
) external override onlyAccessor {
__transfer(_from, _to, _amount);
}
// ERC20 overrides
/// @dev Disallows the standard ERC20 approve() function
function approve(address, uint256) public override returns (bool) {
revert("Unimplemented");
}
/// @notice Gets the `symbol` value of the shares token
/// @return symbol_ The `symbol` value
/// @dev Defers the shares symbol value to the Dispatcher contract
function symbol() public view override returns (string memory symbol_) {
return IDispatcher(creator).getSharesTokenSymbol();
}
/// @dev Disallows the standard ERC20 transfer() function
function transfer(address, uint256) public override returns (bool) {
revert("Unimplemented");
}
/// @dev Disallows the standard ERC20 transferFrom() function
function transferFrom(
address,
address,
uint256
) public override returns (bool) {
revert("Unimplemented");
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `accessor` variable
/// @return accessor_ The `accessor` variable value
function getAccessor() external view override returns (address accessor_) {
return accessor;
}
/// @notice Gets the `creator` variable
/// @return creator_ The `creator` variable value
function getCreator() external view returns (address creator_) {
return creator;
}
/// @notice Gets the `migrator` variable
/// @return migrator_ The `migrator` variable value
function getMigrator() external view returns (address migrator_) {
return migrator;
}
/// @notice Gets the `owner` variable
/// @return owner_ The `owner` variable value
function getOwner() external view override returns (address owner_) {
return owner;
}
/// @notice Gets the `trackedAssets` variable
/// @return trackedAssets_ The `trackedAssets` variable value
function getTrackedAssets() external view override returns (address[] memory trackedAssets_) {
return trackedAssets;
}
/// @notice Check whether an address is a tracked asset of the fund
/// @param _asset The address to check
/// @return isTrackedAsset_ True if the address is a tracked asset of the fund
function isTrackedAsset(address _asset) public view override returns (bool isTrackedAsset_) {
return assetToIsTracked[_asset];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol";
import "../price-feeds/derivatives/IDerivativePriceFeed.sol";
import "../price-feeds/primitives/IPrimitivePriceFeed.sol";
import "./IValueInterpreter.sol";
/// @title ValueInterpreter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Interprets price feeds to provide covert value between asset pairs
/// @dev This contract contains several "live" value calculations, which for this release are simply
/// aliases to their "canonical" value counterparts since the only primitive price feed (Chainlink)
/// is immutable in this contract and only has one type of value. Including the "live" versions of
/// functions only serves as a placeholder for infrastructural components and plugins (e.g., policies)
/// to explicitly define the types of values that they should (and will) be using in a future release.
contract ValueInterpreter is IValueInterpreter {
using SafeMath for uint256;
address private immutable AGGREGATED_DERIVATIVE_PRICE_FEED;
address private immutable PRIMITIVE_PRICE_FEED;
constructor(address _primitivePriceFeed, address _aggregatedDerivativePriceFeed) public {
AGGREGATED_DERIVATIVE_PRICE_FEED = _aggregatedDerivativePriceFeed;
PRIMITIVE_PRICE_FEED = _primitivePriceFeed;
}
// EXTERNAL FUNCTIONS
/// @notice An alias of calcCanonicalAssetsTotalValue
function calcLiveAssetsTotalValue(
address[] calldata _baseAssets,
uint256[] calldata _amounts,
address _quoteAsset
) external override returns (uint256 value_, bool isValid_) {
return calcCanonicalAssetsTotalValue(_baseAssets, _amounts, _quoteAsset);
}
/// @notice An alias of calcCanonicalAssetValue
function calcLiveAssetValue(
address _baseAsset,
uint256 _amount,
address _quoteAsset
) external override returns (uint256 value_, bool isValid_) {
return calcCanonicalAssetValue(_baseAsset, _amount, _quoteAsset);
}
// PUBLIC FUNCTIONS
/// @notice Calculates the total value of given amounts of assets in a single quote asset
/// @param _baseAssets The assets to convert
/// @param _amounts The amounts of the _baseAssets to convert
/// @param _quoteAsset The asset to which to convert
/// @return value_ The sum value of _baseAssets, denominated in the _quoteAsset
/// @return isValid_ True if the price feed rates used to derive value are all valid
/// @dev Does not alter protocol state,
/// but not a view because calls to price feeds can potentially update third party state
function calcCanonicalAssetsTotalValue(
address[] memory _baseAssets,
uint256[] memory _amounts,
address _quoteAsset
) public override returns (uint256 value_, bool isValid_) {
require(
_baseAssets.length == _amounts.length,
"calcCanonicalAssetsTotalValue: Arrays unequal lengths"
);
require(
IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset),
"calcCanonicalAssetsTotalValue: Unsupported _quoteAsset"
);
isValid_ = true;
for (uint256 i; i < _baseAssets.length; i++) {
(uint256 assetValue, bool assetValueIsValid) = __calcAssetValue(
_baseAssets[i],
_amounts[i],
_quoteAsset
);
value_ = value_.add(assetValue);
if (!assetValueIsValid) {
isValid_ = false;
}
}
return (value_, isValid_);
}
/// @notice Calculates the value of a given amount of one asset in terms of another asset
/// @param _baseAsset The asset from which to convert
/// @param _amount The amount of the _baseAsset to convert
/// @param _quoteAsset The asset to which to convert
/// @return value_ The equivalent quantity in the _quoteAsset
/// @return isValid_ True if the price feed rates used to derive value are all valid
/// @dev Does not alter protocol state,
/// but not a view because calls to price feeds can potentially update third party state
function calcCanonicalAssetValue(
address _baseAsset,
uint256 _amount,
address _quoteAsset
) public override returns (uint256 value_, bool isValid_) {
if (_baseAsset == _quoteAsset || _amount == 0) {
return (_amount, true);
}
require(
IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset),
"calcCanonicalAssetValue: Unsupported _quoteAsset"
);
return __calcAssetValue(_baseAsset, _amount, _quoteAsset);
}
// PRIVATE FUNCTIONS
/// @dev Helper to differentially calculate an asset value
/// based on if it is a primitive or derivative asset.
function __calcAssetValue(
address _baseAsset,
uint256 _amount,
address _quoteAsset
) private returns (uint256 value_, bool isValid_) {
if (_baseAsset == _quoteAsset || _amount == 0) {
return (_amount, true);
}
// Handle case that asset is a primitive
if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_baseAsset)) {
return
IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).calcCanonicalValue(
_baseAsset,
_amount,
_quoteAsset
);
}
// Handle case that asset is a derivative
address derivativePriceFeed = IAggregatedDerivativePriceFeed(
AGGREGATED_DERIVATIVE_PRICE_FEED
)
.getPriceFeedForDerivative(_baseAsset);
if (derivativePriceFeed != address(0)) {
return __calcDerivativeValue(derivativePriceFeed, _baseAsset, _amount, _quoteAsset);
}
revert("__calcAssetValue: Unsupported _baseAsset");
}
/// @dev Helper to calculate the value of a derivative in an arbitrary asset.
/// Handles multiple underlying assets (e.g., Uniswap and Balancer pool tokens).
/// Handles underlying assets that are also derivatives (e.g., a cDAI-ETH LP)
function __calcDerivativeValue(
address _derivativePriceFeed,
address _derivative,
uint256 _amount,
address _quoteAsset
) private returns (uint256 value_, bool isValid_) {
(address[] memory underlyings, uint256[] memory underlyingAmounts) = IDerivativePriceFeed(
_derivativePriceFeed
)
.calcUnderlyingValues(_derivative, _amount);
require(underlyings.length > 0, "__calcDerivativeValue: No underlyings");
require(
underlyings.length == underlyingAmounts.length,
"__calcDerivativeValue: Arrays unequal lengths"
);
// Let validity be negated if any of the underlying value calculations are invalid
isValid_ = true;
for (uint256 i = 0; i < underlyings.length; i++) {
(uint256 underlyingValue, bool underlyingValueIsValid) = __calcAssetValue(
underlyings[i],
underlyingAmounts[i],
_quoteAsset
);
if (!underlyingValueIsValid) {
isValid_ = false;
}
value_ = value_.add(underlyingValue);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `AGGREGATED_DERIVATIVE_PRICE_FEED` variable
/// @return aggregatedDerivativePriceFeed_ The `AGGREGATED_DERIVATIVE_PRICE_FEED` variable value
function getAggregatedDerivativePriceFeed()
external
view
returns (address aggregatedDerivativePriceFeed_)
{
return AGGREGATED_DERIVATIVE_PRICE_FEED;
}
/// @notice Gets the `PRIMITIVE_PRICE_FEED` variable
/// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value
function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) {
return PRIMITIVE_PRICE_FEED;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IDispatcher Interface
/// @author Enzyme Council <[email protected]>
interface IDispatcher {
function cancelMigration(address _vaultProxy, bool _bypassFailure) external;
function claimOwnership() external;
function deployVaultProxy(
address _vaultLib,
address _owner,
address _vaultAccessor,
string calldata _fundName
) external returns (address vaultProxy_);
function executeMigration(address _vaultProxy, bool _bypassFailure) external;
function getCurrentFundDeployer() external view returns (address currentFundDeployer_);
function getFundDeployerForVaultProxy(address _vaultProxy)
external
view
returns (address fundDeployer_);
function getMigrationRequestDetailsForVaultProxy(address _vaultProxy)
external
view
returns (
address nextFundDeployer_,
address nextVaultAccessor_,
address nextVaultLib_,
uint256 executableTimestamp_
);
function getMigrationTimelock() external view returns (uint256 migrationTimelock_);
function getNominatedOwner() external view returns (address nominatedOwner_);
function getOwner() external view returns (address owner_);
function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_);
function getTimelockRemainingForMigrationRequest(address _vaultProxy)
external
view
returns (uint256 secondsRemaining_);
function hasExecutableMigrationRequest(address _vaultProxy)
external
view
returns (bool hasExecutableRequest_);
function hasMigrationRequest(address _vaultProxy)
external
view
returns (bool hasMigrationRequest_);
function removeNominatedOwner() external;
function setCurrentFundDeployer(address _nextFundDeployer) external;
function setMigrationTimelock(uint256 _nextTimelock) external;
function setNominatedOwner(address _nextNominatedOwner) external;
function setSharesTokenSymbol(string calldata _nextSymbol) external;
function signalMigration(
address _vaultProxy,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title FeeManager Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the FeeManager
interface IFeeManager {
// No fees for the current release are implemented post-redeemShares
enum FeeHook {
Continuous,
BuySharesSetup,
PreBuyShares,
PostBuyShares,
BuySharesCompleted,
PreRedeemShares
}
enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding}
function invokeHook(
FeeHook,
bytes calldata,
uint256
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IPrimitivePriceFeed Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for primitive price feeds
interface IPrimitivePriceFeed {
function calcCanonicalValue(
address,
uint256,
address
) external view returns (uint256, bool);
function calcLiveValue(
address,
uint256,
address
) external view returns (uint256, bool);
function isSupportedAsset(address) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IValueInterpreter interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for ValueInterpreter
interface IValueInterpreter {
function calcCanonicalAssetValue(
address,
uint256,
address
) external returns (uint256, bool);
function calcCanonicalAssetsTotalValue(
address[] calldata,
uint256[] calldata,
address
) external returns (uint256, bool);
function calcLiveAssetValue(
address,
uint256,
address
) external returns (uint256, bool);
function calcLiveAssetsTotalValue(
address[] calldata,
uint256[] calldata,
address
) external returns (uint256, bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol";
import "../interfaces/ISynthetixAddressResolver.sol";
import "../interfaces/ISynthetixExchanger.sol";
/// @title AssetFinalityResolver Contract
/// @author Enzyme Council <[email protected]>
/// @notice A contract that helps achieve asset finality
abstract contract AssetFinalityResolver {
address internal immutable SYNTHETIX_ADDRESS_RESOLVER;
address internal immutable SYNTHETIX_PRICE_FEED;
constructor(address _synthetixPriceFeed, address _synthetixAddressResolver) public {
SYNTHETIX_ADDRESS_RESOLVER = _synthetixAddressResolver;
SYNTHETIX_PRICE_FEED = _synthetixPriceFeed;
}
/// @dev Helper to finalize a Synth balance at a given target address and return its balance
function __finalizeIfSynthAndGetAssetBalance(
address _target,
address _asset,
bool _requireFinality
) internal returns (uint256 assetBalance_) {
bytes32 currencyKey = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED).getCurrencyKeyForSynth(
_asset
);
if (currencyKey != 0) {
address synthetixExchanger = ISynthetixAddressResolver(SYNTHETIX_ADDRESS_RESOLVER)
.requireAndGetAddress(
"Exchanger",
"finalizeAndGetAssetBalance: Missing Exchanger"
);
try ISynthetixExchanger(synthetixExchanger).settle(_target, currencyKey) {} catch {
require(!_requireFinality, "finalizeAndGetAssetBalance: Cannot settle Synth");
}
}
return ERC20(_asset).balanceOf(_target);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `SYNTHETIX_ADDRESS_RESOLVER` variable
/// @return synthetixAddressResolver_ The `SYNTHETIX_ADDRESS_RESOLVER` variable value
function getSynthetixAddressResolver()
external
view
returns (address synthetixAddressResolver_)
{
return SYNTHETIX_ADDRESS_RESOLVER;
}
/// @notice Gets the `SYNTHETIX_PRICE_FEED` variable
/// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value
function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) {
return SYNTHETIX_PRICE_FEED;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/ISynthetix.sol";
import "../../../../interfaces/ISynthetixAddressResolver.sol";
import "../../../../interfaces/ISynthetixExchangeRates.sol";
import "../../../../interfaces/ISynthetixProxyERC20.sol";
import "../../../../interfaces/ISynthetixSynth.sol";
import "../../../utils/DispatcherOwnerMixin.sol";
import "../IDerivativePriceFeed.sol";
/// @title SynthetixPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice A price feed that uses Synthetix oracles as price sources
contract SynthetixPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin {
using SafeMath for uint256;
event SynthAdded(address indexed synth, bytes32 currencyKey);
event SynthCurrencyKeyUpdated(
address indexed synth,
bytes32 prevCurrencyKey,
bytes32 nextCurrencyKey
);
uint256 private constant SYNTH_UNIT = 10**18;
address private immutable ADDRESS_RESOLVER;
address private immutable SUSD;
mapping(address => bytes32) private synthToCurrencyKey;
constructor(
address _dispatcher,
address _addressResolver,
address _sUSD,
address[] memory _synths
) public DispatcherOwnerMixin(_dispatcher) {
ADDRESS_RESOLVER = _addressResolver;
SUSD = _sUSD;
address[] memory sUSDSynths = new address[](1);
sUSDSynths[0] = _sUSD;
__addSynths(sUSDSynths);
__addSynths(_synths);
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
underlyings_ = new address[](1);
underlyings_[0] = SUSD;
underlyingAmounts_ = new uint256[](1);
bytes32 currencyKey = getCurrencyKeyForSynth(_derivative);
require(currencyKey != 0, "calcUnderlyingValues: _derivative is not supported");
address exchangeRates = ISynthetixAddressResolver(ADDRESS_RESOLVER).requireAndGetAddress(
"ExchangeRates",
"calcUnderlyingValues: Missing ExchangeRates"
);
(uint256 rate, bool isInvalid) = ISynthetixExchangeRates(exchangeRates).rateAndInvalid(
currencyKey
);
require(!isInvalid, "calcUnderlyingValues: _derivative rate is not valid");
underlyingAmounts_[0] = _derivativeAmount.mul(rate).div(SYNTH_UNIT);
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks whether an asset is a supported primitive of the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is a supported primitive
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return getCurrencyKeyForSynth(_asset) != 0;
}
/////////////////////
// SYNTHS REGISTRY //
/////////////////////
/// @notice Adds Synths to the price feed
/// @param _synths Synths to add
function addSynths(address[] calldata _synths) external onlyDispatcherOwner {
require(_synths.length > 0, "addSynths: Empty _synths");
__addSynths(_synths);
}
/// @notice Updates the cached currencyKey value for specified Synths
/// @param _synths Synths to update
/// @dev Anybody can call this function
function updateSynthCurrencyKeys(address[] calldata _synths) external {
require(_synths.length > 0, "updateSynthCurrencyKeys: Empty _synths");
for (uint256 i; i < _synths.length; i++) {
bytes32 prevCurrencyKey = synthToCurrencyKey[_synths[i]];
require(prevCurrencyKey != 0, "updateSynthCurrencyKeys: Synth not set");
bytes32 nextCurrencyKey = __getCurrencyKey(_synths[i]);
require(
nextCurrencyKey != prevCurrencyKey,
"updateSynthCurrencyKeys: Synth has correct currencyKey"
);
synthToCurrencyKey[_synths[i]] = nextCurrencyKey;
emit SynthCurrencyKeyUpdated(_synths[i], prevCurrencyKey, nextCurrencyKey);
}
}
/// @dev Helper to add Synths
function __addSynths(address[] memory _synths) private {
for (uint256 i; i < _synths.length; i++) {
require(synthToCurrencyKey[_synths[i]] == 0, "__addSynths: Value already set");
bytes32 currencyKey = __getCurrencyKey(_synths[i]);
require(currencyKey != 0, "__addSynths: No currencyKey");
synthToCurrencyKey[_synths[i]] = currencyKey;
emit SynthAdded(_synths[i], currencyKey);
}
}
/// @dev Helper to query a currencyKey from Synthetix
function __getCurrencyKey(address _synthProxy) private view returns (bytes32 currencyKey_) {
return ISynthetixSynth(ISynthetixProxyERC20(_synthProxy).target()).currencyKey();
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `ADDRESS_RESOLVER` variable
/// @return addressResolver_ The `ADDRESS_RESOLVER` variable value
function getAddressResolver() external view returns (address) {
return ADDRESS_RESOLVER;
}
/// @notice Gets the currencyKey for multiple given Synths
/// @return currencyKeys_ The currencyKey values
function getCurrencyKeysForSynths(address[] calldata _synths)
external
view
returns (bytes32[] memory currencyKeys_)
{
currencyKeys_ = new bytes32[](_synths.length);
for (uint256 i; i < _synths.length; i++) {
currencyKeys_[i] = synthToCurrencyKey[_synths[i]];
}
return currencyKeys_;
}
/// @notice Gets the `SUSD` variable
/// @return susd_ The `SUSD` variable value
function getSUSD() external view returns (address susd_) {
return SUSD;
}
/// @notice Gets the currencyKey for a given Synth
/// @return currencyKey_ The currencyKey value
function getCurrencyKeyForSynth(address _synth) public view returns (bytes32 currencyKey_) {
return synthToCurrencyKey[_synth];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ISynthetixAddressResolver Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetixAddressResolver {
function requireAndGetAddress(bytes32, string calldata) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ISynthetixExchanger Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetixExchanger {
function getAmountsForExchange(
uint256,
bytes32,
bytes32
)
external
view
returns (
uint256,
uint256,
uint256
);
function settle(address, bytes32)
external
returns (
uint256,
uint256,
uint256
);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ISynthetix Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetix {
function exchangeOnBehalfWithTracking(
address,
bytes32,
uint256,
bytes32,
address,
bytes32
) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ISynthetixExchangeRates Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetixExchangeRates {
function rateAndInvalid(bytes32) external view returns (uint256, bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ISynthetixProxyERC20 Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetixProxyERC20 {
function target() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ISynthetixSynth Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetixSynth {
function currencyKey() external view returns (bytes32);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../persistent/dispatcher/IDispatcher.sol";
/// @title DispatcherOwnerMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract that defers ownership to the owner of Dispatcher
abstract contract DispatcherOwnerMixin {
address internal immutable DISPATCHER;
modifier onlyDispatcherOwner() {
require(
msg.sender == getOwner(),
"onlyDispatcherOwner: Only the Dispatcher owner can call this function"
);
_;
}
constructor(address _dispatcher) public {
DISPATCHER = _dispatcher;
}
/// @notice Gets the owner of this contract
/// @return owner_ The owner
/// @dev Ownership is deferred to the owner of the Dispatcher contract
function getOwner() public view returns (address owner_) {
return IDispatcher(DISPATCHER).getOwner();
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `DISPATCHER` variable
/// @return dispatcher_ The `DISPATCHER` variable value
function getDispatcher() external view returns (address dispatcher_) {
return DISPATCHER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IDerivativePriceFeed Interface
/// @author Enzyme Council <[email protected]>
/// @notice Simple interface for derivative price source oracle implementations
interface IDerivativePriceFeed {
function calcUnderlyingValues(address, uint256)
external
returns (address[] memory, uint256[] memory);
function isSupportedAsset(address) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./VaultLibBaseCore.sol";
/// @title VaultLibBase1 Contract
/// @author Enzyme Council <[email protected]>
/// @notice The first implementation of VaultLibBaseCore, with additional events and storage
/// @dev All subsequent implementations should inherit the previous implementation,
/// e.g., `VaultLibBase2 is VaultLibBase1`
/// DO NOT EDIT CONTRACT.
abstract contract VaultLibBase1 is VaultLibBaseCore {
event AssetWithdrawn(address indexed asset, address indexed target, uint256 amount);
event TrackedAssetAdded(address asset);
event TrackedAssetRemoved(address asset);
address[] internal trackedAssets;
mapping(address => bool) internal assetToIsTracked;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/IMigratableVault.sol";
import "./utils/ProxiableVaultLib.sol";
import "./utils/SharesTokenBase.sol";
/// @title VaultLibBaseCore Contract
/// @author Enzyme Council <[email protected]>
/// @notice A persistent contract containing all required storage variables and
/// required functions for a VaultLib implementation
/// @dev DO NOT EDIT CONTRACT. If new events or storage are necessary, they should be added to
/// a numbered VaultLibBaseXXX that inherits the previous base. See VaultLibBase1.
abstract contract VaultLibBaseCore is IMigratableVault, ProxiableVaultLib, SharesTokenBase {
event AccessorSet(address prevAccessor, address nextAccessor);
event MigratorSet(address prevMigrator, address nextMigrator);
event OwnerSet(address prevOwner, address nextOwner);
event VaultLibSet(address prevVaultLib, address nextVaultLib);
address internal accessor;
address internal creator;
address internal migrator;
address internal owner;
// EXTERNAL FUNCTIONS
/// @notice Initializes the VaultProxy with core configuration
/// @param _owner The address to set as the fund owner
/// @param _accessor The address to set as the permissioned accessor of the VaultLib
/// @param _fundName The name of the fund
/// @dev Serves as a per-proxy pseudo-constructor
function init(
address _owner,
address _accessor,
string calldata _fundName
) external override {
require(creator == address(0), "init: Proxy already initialized");
creator = msg.sender;
sharesName = _fundName;
__setAccessor(_accessor);
__setOwner(_owner);
emit VaultLibSet(address(0), getVaultLib());
}
/// @notice Sets the permissioned accessor of the VaultLib
/// @param _nextAccessor The address to set as the permissioned accessor of the VaultLib
function setAccessor(address _nextAccessor) external override {
require(msg.sender == creator, "setAccessor: Only callable by the contract creator");
__setAccessor(_nextAccessor);
}
/// @notice Sets the VaultLib target for the VaultProxy
/// @param _nextVaultLib The address to set as the VaultLib
/// @dev This function is absolutely critical. __updateCodeAddress() validates that the
/// target is a valid Proxiable contract instance.
/// Does not block _nextVaultLib from being the same as the current VaultLib
function setVaultLib(address _nextVaultLib) external override {
require(msg.sender == creator, "setVaultLib: Only callable by the contract creator");
address prevVaultLib = getVaultLib();
__updateCodeAddress(_nextVaultLib);
emit VaultLibSet(prevVaultLib, _nextVaultLib);
}
// PUBLIC FUNCTIONS
/// @notice Checks whether an account is allowed to migrate the VaultProxy
/// @param _who The account to check
/// @return canMigrate_ True if the account is allowed to migrate the VaultProxy
function canMigrate(address _who) public view virtual override returns (bool canMigrate_) {
return _who == owner || _who == migrator;
}
/// @notice Gets the VaultLib target for the VaultProxy
/// @return vaultLib_ The address of the VaultLib target
function getVaultLib() public view returns (address vaultLib_) {
assembly {
// solium-disable-line
vaultLib_ := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc)
}
return vaultLib_;
}
// INTERNAL FUNCTIONS
/// @dev Helper to set the permissioned accessor of the VaultProxy.
/// Does not prevent the prevAccessor from being the _nextAccessor.
function __setAccessor(address _nextAccessor) internal {
require(_nextAccessor != address(0), "__setAccessor: _nextAccessor cannot be empty");
address prevAccessor = accessor;
accessor = _nextAccessor;
emit AccessorSet(prevAccessor, _nextAccessor);
}
/// @dev Helper to set the owner of the VaultProxy
function __setOwner(address _nextOwner) internal {
require(_nextOwner != address(0), "__setOwner: _nextOwner cannot be empty");
address prevOwner = owner;
require(_nextOwner != prevOwner, "__setOwner: _nextOwner is the current owner");
owner = _nextOwner;
emit OwnerSet(prevOwner, _nextOwner);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ProxiableVaultLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice A contract that defines the upgrade behavior for VaultLib instances
/// @dev The recommended implementation of the target of a proxy according to EIP-1822 and EIP-1967
/// Code position in storage is `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`,
/// which is "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc".
abstract contract ProxiableVaultLib {
/// @dev Updates the target of the proxy to be the contract at _nextVaultLib
function __updateCodeAddress(address _nextVaultLib) internal {
require(
bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) ==
ProxiableVaultLib(_nextVaultLib).proxiableUUID(),
"__updateCodeAddress: _nextVaultLib not compatible"
);
assembly {
// solium-disable-line
sstore(
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc,
_nextVaultLib
)
}
}
/// @notice Returns a unique bytes32 hash for VaultLib instances
/// @return uuid_ The bytes32 hash representing the UUID
/// @dev The UUID is `bytes32(keccak256('mln.proxiable.vaultlib'))`
function proxiableUUID() public pure returns (bytes32 uuid_) {
return 0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./VaultLibSafeMath.sol";
/// @title StandardERC20 Contract
/// @author Enzyme Council <[email protected]>
/// @notice Contains the storage, events, and default logic of an ERC20-compliant contract.
/// @dev The logic can be overridden by VaultLib implementations.
/// Adapted from OpenZeppelin 3.2.0.
/// DO NOT EDIT THIS CONTRACT.
abstract contract SharesTokenBase {
using VaultLibSafeMath for uint256;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
string internal sharesName;
string internal sharesSymbol;
uint256 internal sharesTotalSupply;
mapping(address => uint256) internal sharesBalances;
mapping(address => mapping(address => uint256)) internal sharesAllowances;
// EXTERNAL FUNCTIONS
/// @dev Standard implementation of ERC20's approve(). Can be overridden.
function approve(address _spender, uint256 _amount) public virtual returns (bool) {
__approve(msg.sender, _spender, _amount);
return true;
}
/// @dev Standard implementation of ERC20's transfer(). Can be overridden.
function transfer(address _recipient, uint256 _amount) public virtual returns (bool) {
__transfer(msg.sender, _recipient, _amount);
return true;
}
/// @dev Standard implementation of ERC20's transferFrom(). Can be overridden.
function transferFrom(
address _sender,
address _recipient,
uint256 _amount
) public virtual returns (bool) {
__transfer(_sender, _recipient, _amount);
__approve(
_sender,
msg.sender,
sharesAllowances[_sender][msg.sender].sub(
_amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
// EXTERNAL FUNCTIONS - VIEW
/// @dev Standard implementation of ERC20's allowance(). Can be overridden.
function allowance(address _owner, address _spender) public view virtual returns (uint256) {
return sharesAllowances[_owner][_spender];
}
/// @dev Standard implementation of ERC20's balanceOf(). Can be overridden.
function balanceOf(address _account) public view virtual returns (uint256) {
return sharesBalances[_account];
}
/// @dev Standard implementation of ERC20's decimals(). Can not be overridden.
function decimals() public pure returns (uint8) {
return 18;
}
/// @dev Standard implementation of ERC20's name(). Can be overridden.
function name() public view virtual returns (string memory) {
return sharesName;
}
/// @dev Standard implementation of ERC20's symbol(). Can be overridden.
function symbol() public view virtual returns (string memory) {
return sharesSymbol;
}
/// @dev Standard implementation of ERC20's totalSupply(). Can be overridden.
function totalSupply() public view virtual returns (uint256) {
return sharesTotalSupply;
}
// INTERNAL FUNCTIONS
/// @dev Helper for approve(). Can be overridden.
function __approve(
address _owner,
address _spender,
uint256 _amount
) internal virtual {
require(_owner != address(0), "ERC20: approve from the zero address");
require(_spender != address(0), "ERC20: approve to the zero address");
sharesAllowances[_owner][_spender] = _amount;
emit Approval(_owner, _spender, _amount);
}
/// @dev Helper to burn tokens from an account. Can be overridden.
function __burn(address _account, uint256 _amount) internal virtual {
require(_account != address(0), "ERC20: burn from the zero address");
sharesBalances[_account] = sharesBalances[_account].sub(
_amount,
"ERC20: burn amount exceeds balance"
);
sharesTotalSupply = sharesTotalSupply.sub(_amount);
emit Transfer(_account, address(0), _amount);
}
/// @dev Helper to mint tokens to an account. Can be overridden.
function __mint(address _account, uint256 _amount) internal virtual {
require(_account != address(0), "ERC20: mint to the zero address");
sharesTotalSupply = sharesTotalSupply.add(_amount);
sharesBalances[_account] = sharesBalances[_account].add(_amount);
emit Transfer(address(0), _account, _amount);
}
/// @dev Helper to transfer tokens between accounts. Can be overridden.
function __transfer(
address _sender,
address _recipient,
uint256 _amount
) internal virtual {
require(_sender != address(0), "ERC20: transfer from the zero address");
require(_recipient != address(0), "ERC20: transfer to the zero address");
sharesBalances[_sender] = sharesBalances[_sender].sub(
_amount,
"ERC20: transfer amount exceeds balance"
);
sharesBalances[_recipient] = sharesBalances[_recipient].add(_amount);
emit Transfer(_sender, _recipient, _amount);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title VaultLibSafeMath library
/// @notice A narrowed, verbatim implementation of OpenZeppelin 3.2.0 SafeMath
/// for use with VaultLib
/// @dev Preferred to importing from npm to guarantee consistent logic and revert reasons
/// between VaultLib implementations
/// DO NOT EDIT THIS CONTRACT
library VaultLibSafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "VaultLibSafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "VaultLibSafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "VaultLibSafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "VaultLibSafeMath: division by zero");
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "VaultLibSafeMath: modulo by zero");
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./IDerivativePriceFeed.sol";
/// @title IDerivativePriceFeed Interface
/// @author Enzyme Council <[email protected]>
interface IAggregatedDerivativePriceFeed is IDerivativePriceFeed {
function getPriceFeedForDerivative(address) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../interfaces/IUniswapV2Pair.sol";
import "../../../../utils/MathHelpers.sol";
import "../../../utils/DispatcherOwnerMixin.sol";
import "../../../value-interpreter/ValueInterpreter.sol";
import "../../primitives/IPrimitivePriceFeed.sol";
import "../../utils/UniswapV2PoolTokenValueCalculator.sol";
import "../IDerivativePriceFeed.sol";
/// @title UniswapV2PoolPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price feed for Uniswap lending pool tokens
contract UniswapV2PoolPriceFeed is
IDerivativePriceFeed,
DispatcherOwnerMixin,
MathHelpers,
UniswapV2PoolTokenValueCalculator
{
event PoolTokenAdded(address indexed poolToken, address token0, address token1);
struct PoolTokenInfo {
address token0;
address token1;
uint8 token0Decimals;
uint8 token1Decimals;
}
uint256 private constant POOL_TOKEN_UNIT = 10**18;
address private immutable DERIVATIVE_PRICE_FEED;
address private immutable FACTORY;
address private immutable PRIMITIVE_PRICE_FEED;
address private immutable VALUE_INTERPRETER;
mapping(address => PoolTokenInfo) private poolTokenToInfo;
constructor(
address _dispatcher,
address _derivativePriceFeed,
address _primitivePriceFeed,
address _valueInterpreter,
address _factory,
address[] memory _poolTokens
) public DispatcherOwnerMixin(_dispatcher) {
DERIVATIVE_PRICE_FEED = _derivativePriceFeed;
FACTORY = _factory;
PRIMITIVE_PRICE_FEED = _primitivePriceFeed;
VALUE_INTERPRETER = _valueInterpreter;
__addPoolTokens(_poolTokens, _derivativePriceFeed, _primitivePriceFeed);
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
PoolTokenInfo memory poolTokenInfo = poolTokenToInfo[_derivative];
underlyings_ = new address[](2);
underlyings_[0] = poolTokenInfo.token0;
underlyings_[1] = poolTokenInfo.token1;
// Calculate the amounts underlying one unit of a pool token,
// taking into account the known, trusted rate between the two underlyings
(uint256 token0TrustedRateAmount, uint256 token1TrustedRateAmount) = __calcTrustedRate(
poolTokenInfo.token0,
poolTokenInfo.token1,
poolTokenInfo.token0Decimals,
poolTokenInfo.token1Decimals
);
(
uint256 token0DenormalizedRate,
uint256 token1DenormalizedRate
) = __calcTrustedPoolTokenValue(
FACTORY,
_derivative,
token0TrustedRateAmount,
token1TrustedRateAmount
);
// Define normalized rates for each underlying
underlyingAmounts_ = new uint256[](2);
underlyingAmounts_[0] = _derivativeAmount.mul(token0DenormalizedRate).div(POOL_TOKEN_UNIT);
underlyingAmounts_[1] = _derivativeAmount.mul(token1DenormalizedRate).div(POOL_TOKEN_UNIT);
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return poolTokenToInfo[_asset].token0 != address(0);
}
// PRIVATE FUNCTIONS
/// @dev Calculates the trusted rate of two assets based on our price feeds.
/// Uses the decimals-derived unit for whichever asset is used as the quote asset.
function __calcTrustedRate(
address _token0,
address _token1,
uint256 _token0Decimals,
uint256 _token1Decimals
) private returns (uint256 token0RateAmount_, uint256 token1RateAmount_) {
bool rateIsValid;
// The quote asset of the value lookup must be a supported primitive asset,
// so we cycle through the tokens until reaching a primitive.
// If neither is a primitive, will revert at the ValueInterpreter
if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_token0)) {
token1RateAmount_ = 10**_token1Decimals;
(token0RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER)
.calcCanonicalAssetValue(_token1, token1RateAmount_, _token0);
} else {
token0RateAmount_ = 10**_token0Decimals;
(token1RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER)
.calcCanonicalAssetValue(_token0, token0RateAmount_, _token1);
}
require(rateIsValid, "__calcTrustedRate: Invalid rate");
return (token0RateAmount_, token1RateAmount_);
}
//////////////////////////
// POOL TOKENS REGISTRY //
//////////////////////////
/// @notice Adds Uniswap pool tokens to the price feed
/// @param _poolTokens Uniswap pool tokens to add
function addPoolTokens(address[] calldata _poolTokens) external onlyDispatcherOwner {
require(_poolTokens.length > 0, "addPoolTokens: Empty _poolTokens");
__addPoolTokens(_poolTokens, DERIVATIVE_PRICE_FEED, PRIMITIVE_PRICE_FEED);
}
/// @dev Helper to add Uniswap pool tokens
function __addPoolTokens(
address[] memory _poolTokens,
address _derivativePriceFeed,
address _primitivePriceFeed
) private {
for (uint256 i; i < _poolTokens.length; i++) {
require(_poolTokens[i] != address(0), "__addPoolTokens: Empty poolToken");
require(
poolTokenToInfo[_poolTokens[i]].token0 == address(0),
"__addPoolTokens: Value already set"
);
IUniswapV2Pair uniswapV2Pair = IUniswapV2Pair(_poolTokens[i]);
address token0 = uniswapV2Pair.token0();
address token1 = uniswapV2Pair.token1();
require(
__poolTokenIsSupportable(
_derivativePriceFeed,
_primitivePriceFeed,
token0,
token1
),
"__addPoolTokens: Unsupported pool token"
);
poolTokenToInfo[_poolTokens[i]] = PoolTokenInfo({
token0: token0,
token1: token1,
token0Decimals: ERC20(token0).decimals(),
token1Decimals: ERC20(token1).decimals()
});
emit PoolTokenAdded(_poolTokens[i], token0, token1);
}
}
/// @dev Helper to determine if a pool token is supportable, based on whether price feeds are
/// available for its underlying feeds. At least one of the underlying tokens must be
/// a supported primitive asset, and the other must be a primitive or derivative.
function __poolTokenIsSupportable(
address _derivativePriceFeed,
address _primitivePriceFeed,
address _token0,
address _token1
) private view returns (bool isSupportable_) {
IDerivativePriceFeed derivativePriceFeedContract = IDerivativePriceFeed(
_derivativePriceFeed
);
IPrimitivePriceFeed primitivePriceFeedContract = IPrimitivePriceFeed(_primitivePriceFeed);
if (primitivePriceFeedContract.isSupportedAsset(_token0)) {
if (
primitivePriceFeedContract.isSupportedAsset(_token1) ||
derivativePriceFeedContract.isSupportedAsset(_token1)
) {
return true;
}
} else if (
derivativePriceFeedContract.isSupportedAsset(_token0) &&
primitivePriceFeedContract.isSupportedAsset(_token1)
) {
return true;
}
return false;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `DERIVATIVE_PRICE_FEED` variable value
/// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value
function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) {
return DERIVATIVE_PRICE_FEED;
}
/// @notice Gets the `FACTORY` variable value
/// @return factory_ The `FACTORY` variable value
function getFactory() external view returns (address factory_) {
return FACTORY;
}
/// @notice Gets the `PoolTokenInfo` for a given pool token
/// @param _poolToken The pool token for which to get the `PoolTokenInfo`
/// @return poolTokenInfo_ The `PoolTokenInfo` value
function getPoolTokenInfo(address _poolToken)
external
view
returns (PoolTokenInfo memory poolTokenInfo_)
{
return poolTokenToInfo[_poolToken];
}
/// @notice Gets the underlyings for a given pool token
/// @param _poolToken The pool token for which to get its underlyings
/// @return token0_ The UniswapV2Pair.token0 value
/// @return token1_ The UniswapV2Pair.token1 value
function getPoolTokenUnderlyings(address _poolToken)
external
view
returns (address token0_, address token1_)
{
return (poolTokenToInfo[_poolToken].token0, poolTokenToInfo[_poolToken].token1);
}
/// @notice Gets the `PRIMITIVE_PRICE_FEED` variable value
/// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value
function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) {
return PRIMITIVE_PRICE_FEED;
}
/// @notice Gets the `VALUE_INTERPRETER` variable value
/// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value
function getValueInterpreter() external view returns (address valueInterpreter_) {
return VALUE_INTERPRETER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IUniswapV2Pair Interface
/// @author Enzyme Council <[email protected]>
/// @notice Minimal interface for our interactions with the Uniswap V2's Pair contract
interface IUniswapV2Pair {
function getReserves()
external
view
returns (
uint112,
uint112,
uint32
);
function kLast() external view returns (uint256);
function token0() external view returns (address);
function token1() external view returns (address);
function totalSupply() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../interfaces/IUniswapV2Factory.sol";
import "../../../interfaces/IUniswapV2Pair.sol";
/// @title UniswapV2PoolTokenValueCalculator Contract
/// @author Enzyme Council <[email protected]>
/// @notice Abstract contract for computing the value of Uniswap liquidity pool tokens
/// @dev Unless otherwise noted, these functions are adapted to our needs and style guide from
/// an un-merged Uniswap branch:
/// https://github.com/Uniswap/uniswap-v2-periphery/blob/267ba44471f3357071a2fe2573fe4da42d5ad969/contracts/libraries/UniswapV2LiquidityMathLibrary.sol
abstract contract UniswapV2PoolTokenValueCalculator {
using SafeMath for uint256;
uint256 private constant POOL_TOKEN_UNIT = 10**18;
// INTERNAL FUNCTIONS
/// @dev Given a Uniswap pool with token0 and token1 and their trusted rate,
/// returns the value of one pool token unit in terms of token0 and token1.
/// This is the only function used outside of this contract.
function __calcTrustedPoolTokenValue(
address _factory,
address _pair,
uint256 _token0TrustedRateAmount,
uint256 _token1TrustedRateAmount
) internal view returns (uint256 token0Amount_, uint256 token1Amount_) {
(uint256 reserve0, uint256 reserve1) = __calcReservesAfterArbitrage(
_pair,
_token0TrustedRateAmount,
_token1TrustedRateAmount
);
return __calcPoolTokenValue(_factory, _pair, reserve0, reserve1);
}
// PRIVATE FUNCTIONS
/// @dev Computes liquidity value given all the parameters of the pair
function __calcPoolTokenValue(
address _factory,
address _pair,
uint256 _reserve0,
uint256 _reserve1
) private view returns (uint256 token0Amount_, uint256 token1Amount_) {
IUniswapV2Pair pairContract = IUniswapV2Pair(_pair);
uint256 totalSupply = pairContract.totalSupply();
if (IUniswapV2Factory(_factory).feeTo() != address(0)) {
uint256 kLast = pairContract.kLast();
if (kLast > 0) {
uint256 rootK = __uniswapSqrt(_reserve0.mul(_reserve1));
uint256 rootKLast = __uniswapSqrt(kLast);
if (rootK > rootKLast) {
uint256 numerator = totalSupply.mul(rootK.sub(rootKLast));
uint256 denominator = rootK.mul(5).add(rootKLast);
uint256 feeLiquidity = numerator.div(denominator);
totalSupply = totalSupply.add(feeLiquidity);
}
}
}
return (
_reserve0.mul(POOL_TOKEN_UNIT).div(totalSupply),
_reserve1.mul(POOL_TOKEN_UNIT).div(totalSupply)
);
}
/// @dev Calculates the direction and magnitude of the profit-maximizing trade
function __calcProfitMaximizingTrade(
uint256 _token0TrustedRateAmount,
uint256 _token1TrustedRateAmount,
uint256 _reserve0,
uint256 _reserve1
) private pure returns (bool token0ToToken1_, uint256 amountIn_) {
token0ToToken1_ =
_reserve0.mul(_token1TrustedRateAmount).div(_reserve1) < _token0TrustedRateAmount;
uint256 leftSide;
uint256 rightSide;
if (token0ToToken1_) {
leftSide = __uniswapSqrt(
_reserve0.mul(_reserve1).mul(_token0TrustedRateAmount).mul(1000).div(
_token1TrustedRateAmount.mul(997)
)
);
rightSide = _reserve0.mul(1000).div(997);
} else {
leftSide = __uniswapSqrt(
_reserve0.mul(_reserve1).mul(_token1TrustedRateAmount).mul(1000).div(
_token0TrustedRateAmount.mul(997)
)
);
rightSide = _reserve1.mul(1000).div(997);
}
if (leftSide < rightSide) {
return (false, 0);
}
// Calculate the amount that must be sent to move the price to the profit-maximizing price
amountIn_ = leftSide.sub(rightSide);
return (token0ToToken1_, amountIn_);
}
/// @dev Calculates the pool reserves after an arbitrage moves the price to
/// the profit-maximizing rate, given an externally-observed trusted rate
/// between the two pooled assets
function __calcReservesAfterArbitrage(
address _pair,
uint256 _token0TrustedRateAmount,
uint256 _token1TrustedRateAmount
) private view returns (uint256 reserve0_, uint256 reserve1_) {
(reserve0_, reserve1_, ) = IUniswapV2Pair(_pair).getReserves();
// Skip checking whether the reserve is 0, as this is extremely unlikely given how
// initial pool liquidity is locked, and since we maintain a list of registered pool tokens
// Calculate how much to swap to arb to the trusted price
(bool token0ToToken1, uint256 amountIn) = __calcProfitMaximizingTrade(
_token0TrustedRateAmount,
_token1TrustedRateAmount,
reserve0_,
reserve1_
);
if (amountIn == 0) {
return (reserve0_, reserve1_);
}
// Adjust the reserves to account for the arb trade to the trusted price
if (token0ToToken1) {
uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve0_, reserve1_);
reserve0_ = reserve0_.add(amountIn);
reserve1_ = reserve1_.sub(amountOut);
} else {
uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve1_, reserve0_);
reserve1_ = reserve1_.add(amountIn);
reserve0_ = reserve0_.sub(amountOut);
}
return (reserve0_, reserve1_);
}
/// @dev Uniswap square root function. See:
/// https://github.com/Uniswap/uniswap-lib/blob/6ddfedd5716ba85b905bf34d7f1f3c659101a1bc/contracts/libraries/Babylonian.sol
function __uniswapSqrt(uint256 _y) private pure returns (uint256 z_) {
if (_y > 3) {
z_ = _y;
uint256 x = _y / 2 + 1;
while (x < z_) {
z_ = x;
x = (_y / x + x) / 2;
}
} else if (_y != 0) {
z_ = 1;
}
// else z_ = 0
return z_;
}
/// @dev Simplified version of UniswapV2Library's getAmountOut() function. See:
/// https://github.com/Uniswap/uniswap-v2-periphery/blob/87edfdcaf49ccc52591502993db4c8c08ea9eec0/contracts/libraries/UniswapV2Library.sol#L42-L50
function __uniswapV2GetAmountOut(
uint256 _amountIn,
uint256 _reserveIn,
uint256 _reserveOut
) private pure returns (uint256 amountOut_) {
uint256 amountInWithFee = _amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(_reserveOut);
uint256 denominator = _reserveIn.mul(1000).add(amountInWithFee);
return numerator.div(denominator);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IUniswapV2Factory Interface
/// @author Enzyme Council <[email protected]>
/// @notice Minimal interface for our interactions with the Uniswap V2's Factory contract
interface IUniswapV2Factory {
function feeTo() external view returns (address);
function getPair(address, address) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/IChainlinkAggregator.sol";
import "../../../../utils/MakerDaoMath.sol";
import "../IDerivativePriceFeed.sol";
/// @title WdgldPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for WDGLD <https://dgld.ch/>
contract WdgldPriceFeed is IDerivativePriceFeed, MakerDaoMath {
using SafeMath for uint256;
address private immutable XAU_AGGREGATOR;
address private immutable ETH_AGGREGATOR;
address private immutable WDGLD;
address private immutable WETH;
// GTR_CONSTANT aggregates all the invariants in the GTR formula to save gas
uint256 private constant GTR_CONSTANT = 999990821653213975346065101;
uint256 private constant GTR_PRECISION = 10**27;
uint256 private constant WDGLD_GENESIS_TIMESTAMP = 1568700000;
constructor(
address _wdgld,
address _weth,
address _ethAggregator,
address _xauAggregator
) public {
WDGLD = _wdgld;
WETH = _weth;
ETH_AGGREGATOR = _ethAggregator;
XAU_AGGREGATOR = _xauAggregator;
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only WDGLD is supported");
underlyings_ = new address[](1);
underlyings_[0] = WETH;
underlyingAmounts_ = new uint256[](1);
// Get price rates from xau and eth aggregators
int256 xauToUsdRate = IChainlinkAggregator(XAU_AGGREGATOR).latestAnswer();
int256 ethToUsdRate = IChainlinkAggregator(ETH_AGGREGATOR).latestAnswer();
require(xauToUsdRate > 0 && ethToUsdRate > 0, "calcUnderlyingValues: rate invalid");
uint256 wdgldToXauRate = calcWdgldToXauRate();
// 10**17 is a combination of ETH_UNIT / WDGLD_UNIT * GTR_PRECISION
underlyingAmounts_[0] = _derivativeAmount
.mul(wdgldToXauRate)
.mul(uint256(xauToUsdRate))
.div(uint256(ethToUsdRate))
.div(10**17);
return (underlyings_, underlyingAmounts_);
}
/// @notice Calculates the rate of WDGLD to XAU.
/// @return wdgldToXauRate_ The current rate of WDGLD to XAU
/// @dev Full formula available <https://dgld.ch/assets/documents/dgld-whitepaper.pdf>
function calcWdgldToXauRate() public view returns (uint256 wdgldToXauRate_) {
return
__rpow(
GTR_CONSTANT,
((block.timestamp).sub(WDGLD_GENESIS_TIMESTAMP)).div(28800), // 60 * 60 * 8 (8 hour periods)
GTR_PRECISION
)
.div(10);
}
/// @notice Checks if an asset is supported by this price feed
/// @param _asset The asset to check
/// @return isSupported_ True if supported
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return _asset == WDGLD;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `ETH_AGGREGATOR` address
/// @return ethAggregatorAddress_ The `ETH_AGGREGATOR` address
function getEthAggregator() external view returns (address ethAggregatorAddress_) {
return ETH_AGGREGATOR;
}
/// @notice Gets the `WDGLD` token address
/// @return wdgld_ The `WDGLD` token address
function getWdgld() external view returns (address wdgld_) {
return WDGLD;
}
/// @notice Gets the `WETH` token address
/// @return weth_ The `WETH` token address
function getWeth() external view returns (address weth_) {
return WETH;
}
/// @notice Gets the `XAU_AGGREGATOR` address
/// @return xauAggregatorAddress_ The `XAU_AGGREGATOR` address
function getXauAggregator() external view returns (address xauAggregatorAddress_) {
return XAU_AGGREGATOR;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IChainlinkAggregator Interface
/// @author Enzyme Council <[email protected]>
interface IChainlinkAggregator {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2018 Rain <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
pragma solidity 0.6.12;
/// @title MakerDaoMath Contract
/// @author Enzyme Council <[email protected]>
/// @notice Helper functions for math operations adapted from MakerDao contracts
abstract contract MakerDaoMath {
/// @dev Performs scaled, fixed-point exponentiation.
/// Verbatim code, adapted to our style guide for variable naming only, see:
/// https://github.com/makerdao/dss/blob/master/src/pot.sol#L83-L105
// prettier-ignore
function __rpow(uint256 _x, uint256 _n, uint256 _base) internal pure returns (uint256 z_) {
assembly {
switch _x case 0 {switch _n case 0 {z_ := _base} default {z_ := 0}}
default {
switch mod(_n, 2) case 0 { z_ := _base } default { z_ := _x }
let half := div(_base, 2)
for { _n := div(_n, 2) } _n { _n := div(_n,2) } {
let xx := mul(_x, _x)
if iszero(eq(div(xx, _x), _x)) { revert(0,0) }
let xxRound := add(xx, half)
if lt(xxRound, xx) { revert(0,0) }
_x := div(xxRound, _base)
if mod(_n,2) {
let zx := mul(z_, _x)
if and(iszero(iszero(_x)), iszero(eq(div(zx, _x), z_))) { revert(0,0) }
let zxRound := add(zx, half)
if lt(zxRound, zx) { revert(0,0) }
z_ := div(zxRound, _base)
}
}
}
}
return z_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../core/fund/vault/VaultLib.sol";
import "../../../utils/MakerDaoMath.sol";
import "./utils/FeeBase.sol";
/// @title ManagementFee Contract
/// @author Enzyme Council <[email protected]>
/// @notice A management fee with a configurable annual rate
contract ManagementFee is FeeBase, MakerDaoMath {
using SafeMath for uint256;
event FundSettingsAdded(address indexed comptrollerProxy, uint256 scaledPerSecondRate);
event Settled(
address indexed comptrollerProxy,
uint256 sharesQuantity,
uint256 secondsSinceSettlement
);
struct FeeInfo {
uint256 scaledPerSecondRate;
uint256 lastSettled;
}
uint256 private constant RATE_SCALE_BASE = 10**27;
mapping(address => FeeInfo) private comptrollerProxyToFeeInfo;
constructor(address _feeManager) public FeeBase(_feeManager) {}
// EXTERNAL FUNCTIONS
/// @notice Activates the fee for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _vaultProxy The VaultProxy of the fund
function activateForFund(address _comptrollerProxy, address _vaultProxy)
external
override
onlyFeeManager
{
// It is only necessary to set `lastSettled` for a migrated fund
if (VaultLib(_vaultProxy).totalSupply() > 0) {
comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp;
}
}
/// @notice Add the initial fee settings for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _settingsData Encoded settings to apply to the fee for a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData)
external
override
onlyFeeManager
{
uint256 scaledPerSecondRate = abi.decode(_settingsData, (uint256));
require(
scaledPerSecondRate > 0,
"addFundSettings: scaledPerSecondRate must be greater than 0"
);
comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({
scaledPerSecondRate: scaledPerSecondRate,
lastSettled: 0
});
emit FundSettingsAdded(_comptrollerProxy, scaledPerSecondRate);
}
/// @notice Provides a constant string identifier for a fee
/// @return identifier_ The identifier string
function identifier() external pure override returns (string memory identifier_) {
return "MANAGEMENT";
}
/// @notice Gets the hooks that are implemented by the fee
/// @return implementedHooksForSettle_ The hooks during which settle() is implemented
/// @return implementedHooksForUpdate_ The hooks during which update() is implemented
/// @return usesGavOnSettle_ True if GAV is used during the settle() implementation
/// @return usesGavOnUpdate_ True if GAV is used during the update() implementation
/// @dev Used only during fee registration
function implementedHooks()
external
view
override
returns (
IFeeManager.FeeHook[] memory implementedHooksForSettle_,
IFeeManager.FeeHook[] memory implementedHooksForUpdate_,
bool usesGavOnSettle_,
bool usesGavOnUpdate_
)
{
implementedHooksForSettle_ = new IFeeManager.FeeHook[](3);
implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous;
implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup;
implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares;
return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false);
}
/// @notice Settle the fee and calculate shares due
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _vaultProxy The VaultProxy of the fund
/// @return settlementType_ The type of settlement
/// @return (unused) The payer of shares due
/// @return sharesDue_ The amount of shares due
function settle(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook,
bytes calldata,
uint256
)
external
override
onlyFeeManager
returns (
IFeeManager.SettlementType settlementType_,
address,
uint256 sharesDue_
)
{
FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy];
// If this fee was settled in the current block, we can return early
uint256 secondsSinceSettlement = block.timestamp.sub(feeInfo.lastSettled);
if (secondsSinceSettlement == 0) {
return (IFeeManager.SettlementType.None, address(0), 0);
}
// If there are shares issued for the fund, calculate the shares due
VaultLib vaultProxyContract = VaultLib(_vaultProxy);
uint256 sharesSupply = vaultProxyContract.totalSupply();
if (sharesSupply > 0) {
// This assumes that all shares in the VaultProxy are shares outstanding,
// which is fine for this release. Even if they are not, they are still shares that
// are only claimable by the fund owner.
uint256 netSharesSupply = sharesSupply.sub(vaultProxyContract.balanceOf(_vaultProxy));
if (netSharesSupply > 0) {
sharesDue_ = netSharesSupply
.mul(
__rpow(feeInfo.scaledPerSecondRate, secondsSinceSettlement, RATE_SCALE_BASE)
.sub(RATE_SCALE_BASE)
)
.div(RATE_SCALE_BASE);
}
}
// Must settle even when no shares are due, for the case that settlement is being
// done when there are no shares in the fund (i.e. at the first investment, or at the
// first investment after all shares have been redeemed)
comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp;
emit Settled(_comptrollerProxy, sharesDue_, secondsSinceSettlement);
if (sharesDue_ == 0) {
return (IFeeManager.SettlementType.None, address(0), 0);
}
return (IFeeManager.SettlementType.Mint, address(0), sharesDue_);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the feeInfo for a given fund
/// @param _comptrollerProxy The ComptrollerProxy contract of the fund
/// @return feeInfo_ The feeInfo
function getFeeInfoForFund(address _comptrollerProxy)
external
view
returns (FeeInfo memory feeInfo_)
{
return comptrollerProxyToFeeInfo[_comptrollerProxy];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../IFee.sol";
/// @title FeeBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Abstract base contract for all fees
abstract contract FeeBase is IFee {
address internal immutable FEE_MANAGER;
modifier onlyFeeManager {
require(msg.sender == FEE_MANAGER, "Only the FeeManger can make this call");
_;
}
constructor(address _feeManager) public {
FEE_MANAGER = _feeManager;
}
/// @notice Allows Fee to run logic during fund activation
/// @dev Unimplemented by default, may be overrode.
function activateForFund(address, address) external virtual override {
return;
}
/// @notice Runs payout logic for a fee that utilizes shares outstanding as its settlement type
/// @dev Returns false by default, can be overridden by fee
function payout(address, address) external virtual override returns (bool) {
return false;
}
/// @notice Update fee state after all settlement has occurred during a given fee hook
/// @dev Unimplemented by default, can be overridden by fee
function update(
address,
address,
IFeeManager.FeeHook,
bytes calldata,
uint256
) external virtual override {
return;
}
/// @notice Helper to parse settlement arguments from encoded data for PreBuyShares fee hook
function __decodePreBuySharesSettlementData(bytes memory _settlementData)
internal
pure
returns (
address buyer_,
uint256 investmentAmount_,
uint256 minSharesQuantity_
)
{
return abi.decode(_settlementData, (address, uint256, uint256));
}
/// @notice Helper to parse settlement arguments from encoded data for PreRedeemShares fee hook
function __decodePreRedeemSharesSettlementData(bytes memory _settlementData)
internal
pure
returns (address redeemer_, uint256 sharesQuantity_)
{
return abi.decode(_settlementData, (address, uint256));
}
/// @notice Helper to parse settlement arguments from encoded data for PostBuyShares fee hook
function __decodePostBuySharesSettlementData(bytes memory _settlementData)
internal
pure
returns (
address buyer_,
uint256 investmentAmount_,
uint256 sharesBought_
)
{
return abi.decode(_settlementData, (address, uint256, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `FEE_MANAGER` variable
/// @return feeManager_ The `FEE_MANAGER` variable value
function getFeeManager() external view returns (address feeManager_) {
return FEE_MANAGER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./IFeeManager.sol";
/// @title Fee Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all fees
interface IFee {
function activateForFund(address _comptrollerProxy, address _vaultProxy) external;
function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external;
function identifier() external pure returns (string memory identifier_);
function implementedHooks()
external
view
returns (
IFeeManager.FeeHook[] memory implementedHooksForSettle_,
IFeeManager.FeeHook[] memory implementedHooksForUpdate_,
bool usesGavOnSettle_,
bool usesGavOnUpdate_
);
function payout(address _comptrollerProxy, address _vaultProxy)
external
returns (bool isPayable_);
function settle(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook _hook,
bytes calldata _settlementData,
uint256 _gav
)
external
returns (
IFeeManager.SettlementType settlementType_,
address payer_,
uint256 sharesDue_
);
function update(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook _hook,
bytes calldata _settlementData,
uint256 _gav
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/SignedSafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../core/fund/comptroller/ComptrollerLib.sol";
import "../FeeManager.sol";
import "./utils/FeeBase.sol";
/// @title PerformanceFee Contract
/// @author Enzyme Council <[email protected]>
/// @notice A performance-based fee with configurable rate and crystallization period, using
/// a high watermark
/// @dev This contract assumes that all shares in the VaultProxy are shares outstanding,
/// which is fine for this release. Even if they are not, they are still shares that
/// are only claimable by the fund owner.
contract PerformanceFee is FeeBase {
using SafeMath for uint256;
using SignedSafeMath for int256;
event ActivatedForFund(address indexed comptrollerProxy, uint256 highWaterMark);
event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate, uint256 period);
event LastSharePriceUpdated(
address indexed comptrollerProxy,
uint256 prevSharePrice,
uint256 nextSharePrice
);
event PaidOut(
address indexed comptrollerProxy,
uint256 prevHighWaterMark,
uint256 nextHighWaterMark,
uint256 aggregateValueDue
);
event PerformanceUpdated(
address indexed comptrollerProxy,
uint256 prevAggregateValueDue,
uint256 nextAggregateValueDue,
int256 sharesOutstandingDiff
);
struct FeeInfo {
uint256 rate;
uint256 period;
uint256 activated;
uint256 lastPaid;
uint256 highWaterMark;
uint256 lastSharePrice;
uint256 aggregateValueDue;
}
uint256 private constant RATE_DIVISOR = 10**18;
uint256 private constant SHARE_UNIT = 10**18;
mapping(address => FeeInfo) private comptrollerProxyToFeeInfo;
constructor(address _feeManager) public FeeBase(_feeManager) {}
// EXTERNAL FUNCTIONS
/// @notice Activates the fee for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
function activateForFund(address _comptrollerProxy, address) external override onlyFeeManager {
FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy];
// We must not force asset finality, otherwise funds that have Synths as tracked assets
// would be susceptible to a DoS attack when attempting to migrate to a release that uses
// this fee: an attacker trades a negligible amount of a tracked Synth with the VaultProxy
// as the recipient, thus causing `calcGrossShareValue(true)` to fail.
(uint256 grossSharePrice, bool sharePriceIsValid) = ComptrollerLib(_comptrollerProxy)
.calcGrossShareValue(false);
require(sharePriceIsValid, "activateForFund: Invalid share price");
feeInfo.highWaterMark = grossSharePrice;
feeInfo.lastSharePrice = grossSharePrice;
feeInfo.activated = block.timestamp;
emit ActivatedForFund(_comptrollerProxy, grossSharePrice);
}
/// @notice Add the initial fee settings for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _settingsData Encoded settings to apply to the policy for the fund
/// @dev `highWaterMark`, `lastSharePrice`, and `activated` are set during activation
function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData)
external
override
onlyFeeManager
{
(uint256 feeRate, uint256 feePeriod) = abi.decode(_settingsData, (uint256, uint256));
require(feeRate > 0, "addFundSettings: feeRate must be greater than 0");
require(feePeriod > 0, "addFundSettings: feePeriod must be greater than 0");
comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({
rate: feeRate,
period: feePeriod,
activated: 0,
lastPaid: 0,
highWaterMark: 0,
lastSharePrice: 0,
aggregateValueDue: 0
});
emit FundSettingsAdded(_comptrollerProxy, feeRate, feePeriod);
}
/// @notice Provides a constant string identifier for a fee
/// @return identifier_ The identifier string
function identifier() external pure override returns (string memory identifier_) {
return "PERFORMANCE";
}
/// @notice Gets the hooks that are implemented by the fee
/// @return implementedHooksForSettle_ The hooks during which settle() is implemented
/// @return implementedHooksForUpdate_ The hooks during which update() is implemented
/// @return usesGavOnSettle_ True if GAV is used during the settle() implementation
/// @return usesGavOnUpdate_ True if GAV is used during the update() implementation
/// @dev Used only during fee registration
function implementedHooks()
external
view
override
returns (
IFeeManager.FeeHook[] memory implementedHooksForSettle_,
IFeeManager.FeeHook[] memory implementedHooksForUpdate_,
bool usesGavOnSettle_,
bool usesGavOnUpdate_
)
{
implementedHooksForSettle_ = new IFeeManager.FeeHook[](3);
implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous;
implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup;
implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares;
implementedHooksForUpdate_ = new IFeeManager.FeeHook[](3);
implementedHooksForUpdate_[0] = IFeeManager.FeeHook.Continuous;
implementedHooksForUpdate_[1] = IFeeManager.FeeHook.BuySharesCompleted;
implementedHooksForUpdate_[2] = IFeeManager.FeeHook.PreRedeemShares;
return (implementedHooksForSettle_, implementedHooksForUpdate_, true, true);
}
/// @notice Checks whether the shares outstanding for the fee can be paid out, and updates
/// the info for the fee's last payout
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return isPayable_ True if shares outstanding can be paid out
function payout(address _comptrollerProxy, address)
external
override
onlyFeeManager
returns (bool isPayable_)
{
if (!payoutAllowed(_comptrollerProxy)) {
return false;
}
FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy];
feeInfo.lastPaid = block.timestamp;
uint256 prevHighWaterMark = feeInfo.highWaterMark;
uint256 nextHighWaterMark = __calcUint256Max(feeInfo.lastSharePrice, prevHighWaterMark);
uint256 prevAggregateValueDue = feeInfo.aggregateValueDue;
// Update state as necessary
if (prevAggregateValueDue > 0) {
feeInfo.aggregateValueDue = 0;
}
if (nextHighWaterMark > prevHighWaterMark) {
feeInfo.highWaterMark = nextHighWaterMark;
}
emit PaidOut(
_comptrollerProxy,
prevHighWaterMark,
nextHighWaterMark,
prevAggregateValueDue
);
return true;
}
/// @notice Settles the fee and calculates shares due
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _vaultProxy The VaultProxy of the fund
/// @param _gav The GAV of the fund
/// @return settlementType_ The type of settlement
/// @return (unused) The payer of shares due
/// @return sharesDue_ The amount of shares due
function settle(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook,
bytes calldata,
uint256 _gav
)
external
override
onlyFeeManager
returns (
IFeeManager.SettlementType settlementType_,
address,
uint256 sharesDue_
)
{
if (_gav == 0) {
return (IFeeManager.SettlementType.None, address(0), 0);
}
int256 settlementSharesDue = __settleAndUpdatePerformance(
_comptrollerProxy,
_vaultProxy,
_gav
);
if (settlementSharesDue == 0) {
return (IFeeManager.SettlementType.None, address(0), 0);
} else if (settlementSharesDue > 0) {
// Settle by minting shares outstanding for custody
return (
IFeeManager.SettlementType.MintSharesOutstanding,
address(0),
uint256(settlementSharesDue)
);
} else {
// Settle by burning from shares outstanding
return (
IFeeManager.SettlementType.BurnSharesOutstanding,
address(0),
uint256(-settlementSharesDue)
);
}
}
/// @notice Updates the fee state after all fees have finished settle()
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _vaultProxy The VaultProxy of the fund
/// @param _hook The FeeHook being executed
/// @param _settlementData Encoded args to use in calculating the settlement
/// @param _gav The GAV of the fund
function update(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook _hook,
bytes calldata _settlementData,
uint256 _gav
) external override onlyFeeManager {
uint256 prevSharePrice = comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice;
uint256 nextSharePrice = __calcNextSharePrice(
_comptrollerProxy,
_vaultProxy,
_hook,
_settlementData,
_gav
);
if (nextSharePrice == prevSharePrice) {
return;
}
comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice = nextSharePrice;
emit LastSharePriceUpdated(_comptrollerProxy, prevSharePrice, nextSharePrice);
}
// PUBLIC FUNCTIONS
/// @notice Checks whether the shares outstanding can be paid out
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return payoutAllowed_ True if the fee payment is due
/// @dev Payout is allowed if fees have not yet been settled in a crystallization period,
/// and at least 1 crystallization period has passed since activation
function payoutAllowed(address _comptrollerProxy) public view returns (bool payoutAllowed_) {
FeeInfo memory feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy];
uint256 period = feeInfo.period;
uint256 timeSinceActivated = block.timestamp.sub(feeInfo.activated);
// Check if at least 1 crystallization period has passed since activation
if (timeSinceActivated < period) {
return false;
}
// Check that a full crystallization period has passed since the last payout
uint256 timeSincePeriodStart = timeSinceActivated % period;
uint256 periodStart = block.timestamp.sub(timeSincePeriodStart);
return feeInfo.lastPaid < periodStart;
}
// PRIVATE FUNCTIONS
/// @dev Helper to calculate the aggregated value accumulated to a fund since the last
/// settlement (happening at investment/redemption)
/// Validated:
/// _netSharesSupply > 0
/// _sharePriceWithoutPerformance != _prevSharePrice
function __calcAggregateValueDue(
uint256 _netSharesSupply,
uint256 _sharePriceWithoutPerformance,
uint256 _prevSharePrice,
uint256 _prevAggregateValueDue,
uint256 _feeRate,
uint256 _highWaterMark
) private pure returns (uint256) {
int256 superHWMValueSinceLastSettled = (
int256(__calcUint256Max(_highWaterMark, _sharePriceWithoutPerformance)).sub(
int256(__calcUint256Max(_highWaterMark, _prevSharePrice))
)
)
.mul(int256(_netSharesSupply))
.div(int256(SHARE_UNIT));
int256 valueDueSinceLastSettled = superHWMValueSinceLastSettled.mul(int256(_feeRate)).div(
int256(RATE_DIVISOR)
);
return
uint256(
__calcInt256Max(0, int256(_prevAggregateValueDue).add(valueDueSinceLastSettled))
);
}
/// @dev Helper to calculate the max of two int values
function __calcInt256Max(int256 _a, int256 _b) private pure returns (int256) {
if (_a >= _b) {
return _a;
}
return _b;
}
/// @dev Helper to calculate the next `lastSharePrice` value
function __calcNextSharePrice(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook _hook,
bytes memory _settlementData,
uint256 _gav
) private view returns (uint256 nextSharePrice_) {
uint256 denominationAssetUnit = 10 **
uint256(ERC20(ComptrollerLib(_comptrollerProxy).getDenominationAsset()).decimals());
if (_gav == 0) {
return denominationAssetUnit;
}
// Get shares outstanding via VaultProxy balance and calc shares supply to get net shares supply
ERC20 vaultProxyContract = ERC20(_vaultProxy);
uint256 totalSharesSupply = vaultProxyContract.totalSupply();
uint256 nextNetSharesSupply = totalSharesSupply.sub(
vaultProxyContract.balanceOf(_vaultProxy)
);
if (nextNetSharesSupply == 0) {
return denominationAssetUnit;
}
uint256 nextGav = _gav;
// For both Continuous and BuySharesCompleted hooks, _gav and shares supply will not change,
// we only need additional calculations for PreRedeemShares
if (_hook == IFeeManager.FeeHook.PreRedeemShares) {
(, uint256 sharesDecrease) = __decodePreRedeemSharesSettlementData(_settlementData);
// Shares have not yet been burned
nextNetSharesSupply = nextNetSharesSupply.sub(sharesDecrease);
if (nextNetSharesSupply == 0) {
return denominationAssetUnit;
}
// Assets have not yet been withdrawn
uint256 gavDecrease = sharesDecrease
.mul(_gav)
.mul(SHARE_UNIT)
.div(totalSharesSupply)
.div(denominationAssetUnit);
nextGav = nextGav.sub(gavDecrease);
if (nextGav == 0) {
return denominationAssetUnit;
}
}
return nextGav.mul(SHARE_UNIT).div(nextNetSharesSupply);
}
/// @dev Helper to calculate the performance metrics for a fund.
/// Validated:
/// _totalSharesSupply > 0
/// _gav > 0
/// _totalSharesSupply != _totalSharesOutstanding
function __calcPerformance(
address _comptrollerProxy,
uint256 _totalSharesSupply,
uint256 _totalSharesOutstanding,
uint256 _prevAggregateValueDue,
FeeInfo memory feeInfo,
uint256 _gav
) private view returns (uint256 nextAggregateValueDue_, int256 sharesDue_) {
// Use the 'shares supply net shares outstanding' for performance calcs.
// Cannot be 0, as _totalSharesSupply != _totalSharesOutstanding
uint256 netSharesSupply = _totalSharesSupply.sub(_totalSharesOutstanding);
uint256 sharePriceWithoutPerformance = _gav.mul(SHARE_UNIT).div(netSharesSupply);
// If gross share price has not changed, can exit early
uint256 prevSharePrice = feeInfo.lastSharePrice;
if (sharePriceWithoutPerformance == prevSharePrice) {
return (_prevAggregateValueDue, 0);
}
nextAggregateValueDue_ = __calcAggregateValueDue(
netSharesSupply,
sharePriceWithoutPerformance,
prevSharePrice,
_prevAggregateValueDue,
feeInfo.rate,
feeInfo.highWaterMark
);
sharesDue_ = __calcSharesDue(
_comptrollerProxy,
netSharesSupply,
_gav,
nextAggregateValueDue_
);
return (nextAggregateValueDue_, sharesDue_);
}
/// @dev Helper to calculate sharesDue during settlement.
/// Validated:
/// _netSharesSupply > 0
/// _gav > 0
function __calcSharesDue(
address _comptrollerProxy,
uint256 _netSharesSupply,
uint256 _gav,
uint256 _nextAggregateValueDue
) private view returns (int256 sharesDue_) {
// If _nextAggregateValueDue > _gav, then no shares can be created.
// This is a known limitation of the model, which is only reached for unrealistically
// high performance fee rates (> 100%). A revert is allowed in such a case.
uint256 sharesDueForAggregateValueDue = _nextAggregateValueDue.mul(_netSharesSupply).div(
_gav.sub(_nextAggregateValueDue)
);
// Shares due is the +/- diff or the total shares outstanding already minted
return
int256(sharesDueForAggregateValueDue).sub(
int256(
FeeManager(FEE_MANAGER).getFeeSharesOutstandingForFund(
_comptrollerProxy,
address(this)
)
)
);
}
/// @dev Helper to calculate the max of two uint values
function __calcUint256Max(uint256 _a, uint256 _b) private pure returns (uint256) {
if (_a >= _b) {
return _a;
}
return _b;
}
/// @dev Helper to settle the fee and update performance state.
/// Validated:
/// _gav > 0
function __settleAndUpdatePerformance(
address _comptrollerProxy,
address _vaultProxy,
uint256 _gav
) private returns (int256 sharesDue_) {
ERC20 sharesTokenContract = ERC20(_vaultProxy);
uint256 totalSharesSupply = sharesTokenContract.totalSupply();
if (totalSharesSupply == 0) {
return 0;
}
uint256 totalSharesOutstanding = sharesTokenContract.balanceOf(_vaultProxy);
if (totalSharesOutstanding == totalSharesSupply) {
return 0;
}
FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy];
uint256 prevAggregateValueDue = feeInfo.aggregateValueDue;
uint256 nextAggregateValueDue;
(nextAggregateValueDue, sharesDue_) = __calcPerformance(
_comptrollerProxy,
totalSharesSupply,
totalSharesOutstanding,
prevAggregateValueDue,
feeInfo,
_gav
);
if (nextAggregateValueDue == prevAggregateValueDue) {
return 0;
}
// Update fee state
feeInfo.aggregateValueDue = nextAggregateValueDue;
emit PerformanceUpdated(
_comptrollerProxy,
prevAggregateValueDue,
nextAggregateValueDue,
sharesDue_
);
return sharesDue_;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the feeInfo for a given fund
/// @param _comptrollerProxy The ComptrollerProxy contract of the fund
/// @return feeInfo_ The feeInfo
function getFeeInfoForFund(address _comptrollerProxy)
external
view
returns (FeeInfo memory feeInfo_)
{
return comptrollerProxyToFeeInfo[_comptrollerProxy];
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "../../core/fund/comptroller/IComptroller.sol";
import "../../core/fund/vault/IVault.sol";
import "../../utils/AddressArrayLib.sol";
import "../utils/ExtensionBase.sol";
import "../utils/FundDeployerOwnerMixin.sol";
import "../utils/PermissionedVaultActionMixin.sol";
import "./IFee.sol";
import "./IFeeManager.sol";
/// @title FeeManager Contract
/// @author Enzyme Council <[email protected]>
/// @notice Manages fees for funds
contract FeeManager is
IFeeManager,
ExtensionBase,
FundDeployerOwnerMixin,
PermissionedVaultActionMixin
{
using AddressArrayLib for address[];
using EnumerableSet for EnumerableSet.AddressSet;
using SafeMath for uint256;
event AllSharesOutstandingForcePaidForFund(
address indexed comptrollerProxy,
address payee,
uint256 sharesDue
);
event FeeDeregistered(address indexed fee, string indexed identifier);
event FeeEnabledForFund(
address indexed comptrollerProxy,
address indexed fee,
bytes settingsData
);
event FeeRegistered(
address indexed fee,
string indexed identifier,
FeeHook[] implementedHooksForSettle,
FeeHook[] implementedHooksForUpdate,
bool usesGavOnSettle,
bool usesGavOnUpdate
);
event FeeSettledForFund(
address indexed comptrollerProxy,
address indexed fee,
SettlementType indexed settlementType,
address payer,
address payee,
uint256 sharesDue
);
event SharesOutstandingPaidForFund(
address indexed comptrollerProxy,
address indexed fee,
uint256 sharesDue
);
event FeesRecipientSetForFund(
address indexed comptrollerProxy,
address prevFeesRecipient,
address nextFeesRecipient
);
EnumerableSet.AddressSet private registeredFees;
mapping(address => bool) private feeToUsesGavOnSettle;
mapping(address => bool) private feeToUsesGavOnUpdate;
mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsSettle;
mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsUpdate;
mapping(address => address[]) private comptrollerProxyToFees;
mapping(address => mapping(address => uint256))
private comptrollerProxyToFeeToSharesOutstanding;
constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {}
// EXTERNAL FUNCTIONS
/// @notice Activate already-configured fees for use in the calling fund
function activateForFund(bool) external override {
address vaultProxy = __setValidatedVaultProxy(msg.sender);
address[] memory enabledFees = comptrollerProxyToFees[msg.sender];
for (uint256 i; i < enabledFees.length; i++) {
IFee(enabledFees[i]).activateForFund(msg.sender, vaultProxy);
}
}
/// @notice Deactivate fees for a fund
/// @dev msg.sender is validated during __invokeHook()
function deactivateForFund() external override {
// Settle continuous fees one last time, but without calling Fee.update()
__invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, false);
// Force payout of remaining shares outstanding
__forcePayoutAllSharesOutstanding(msg.sender);
// Clean up storage
__deleteFundStorage(msg.sender);
}
/// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy
/// @param _actionId An ID representing the desired action
/// @param _callArgs Encoded arguments specific to the _actionId
/// @dev This is the only way to call a function on this contract that updates VaultProxy state.
/// For both of these actions, any caller is allowed, so we don't use the caller param.
function receiveCallFromComptroller(
address,
uint256 _actionId,
bytes calldata _callArgs
) external override {
if (_actionId == 0) {
// Settle and update all continuous fees
__invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, true);
} else if (_actionId == 1) {
__payoutSharesOutstandingForFees(msg.sender, _callArgs);
} else {
revert("receiveCallFromComptroller: Invalid _actionId");
}
}
/// @notice Enable and configure fees for use in the calling fund
/// @param _configData Encoded config data
/// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate.
/// The order of `fees` determines the order in which fees of the same FeeHook will be applied.
/// It is recommended to run ManagementFee before PerformanceFee in order to achieve precise
/// PerformanceFee calcs.
function setConfigForFund(bytes calldata _configData) external override {
(address[] memory fees, bytes[] memory settingsData) = abi.decode(
_configData,
(address[], bytes[])
);
// Sanity checks
require(
fees.length == settingsData.length,
"setConfigForFund: fees and settingsData array lengths unequal"
);
require(fees.isUniqueSet(), "setConfigForFund: fees cannot include duplicates");
// Enable each fee with settings
for (uint256 i; i < fees.length; i++) {
require(isRegisteredFee(fees[i]), "setConfigForFund: Fee is not registered");
// Set fund config on fee
IFee(fees[i]).addFundSettings(msg.sender, settingsData[i]);
// Enable fee for fund
comptrollerProxyToFees[msg.sender].push(fees[i]);
emit FeeEnabledForFund(msg.sender, fees[i], settingsData[i]);
}
}
/// @notice Allows all fees for a particular FeeHook to implement settle() and update() logic
/// @param _hook The FeeHook to invoke
/// @param _settlementData The encoded settlement parameters specific to the FeeHook
/// @param _gav The GAV for a fund if known in the invocating code, otherwise 0
function invokeHook(
FeeHook _hook,
bytes calldata _settlementData,
uint256 _gav
) external override {
__invokeHook(msg.sender, _hook, _settlementData, _gav, true);
}
// PRIVATE FUNCTIONS
/// @dev Helper to destroy local storage to get gas refund,
/// and to prevent further calls to fee manager
function __deleteFundStorage(address _comptrollerProxy) private {
delete comptrollerProxyToFees[_comptrollerProxy];
delete comptrollerProxyToVaultProxy[_comptrollerProxy];
}
/// @dev Helper to force the payout of shares outstanding across all fees.
/// For the current release, all shares in the VaultProxy are assumed to be
/// shares outstanding from fees. If not, then they were sent there by mistake
/// and are otherwise unrecoverable. We can therefore take the VaultProxy's
/// shares balance as the totalSharesOutstanding to payout to the fund owner.
function __forcePayoutAllSharesOutstanding(address _comptrollerProxy) private {
address vaultProxy = getVaultProxyForFund(_comptrollerProxy);
uint256 totalSharesOutstanding = ERC20(vaultProxy).balanceOf(vaultProxy);
if (totalSharesOutstanding == 0) {
return;
}
// Destroy any shares outstanding storage
address[] memory fees = comptrollerProxyToFees[_comptrollerProxy];
for (uint256 i; i < fees.length; i++) {
delete comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]];
}
// Distribute all shares outstanding to the fees recipient
address payee = IVault(vaultProxy).getOwner();
__transferShares(_comptrollerProxy, vaultProxy, payee, totalSharesOutstanding);
emit AllSharesOutstandingForcePaidForFund(
_comptrollerProxy,
payee,
totalSharesOutstanding
);
}
/// @dev Helper to get the canonical value of GAV if not yet set and required by fee
function __getGavAsNecessary(
address _comptrollerProxy,
address _fee,
uint256 _gavOrZero
) private returns (uint256 gav_) {
if (_gavOrZero == 0 && feeUsesGavOnUpdate(_fee)) {
// Assumes that any fee that requires GAV would need to revert if invalid or not final
bool gavIsValid;
(gav_, gavIsValid) = IComptroller(_comptrollerProxy).calcGav(true);
require(gavIsValid, "__getGavAsNecessary: Invalid GAV");
} else {
gav_ = _gavOrZero;
}
return gav_;
}
/// @dev Helper to run settle() on all enabled fees for a fund that implement a given hook, and then to
/// optionally run update() on the same fees. This order allows fees an opportunity to update
/// their local state after all VaultProxy state transitions (i.e., minting, burning,
/// transferring shares) have finished. To optimize for the expensive operation of calculating
/// GAV, once one fee requires GAV, we recycle that `gav` value for subsequent fees.
/// Assumes that _gav is either 0 or has already been validated.
function __invokeHook(
address _comptrollerProxy,
FeeHook _hook,
bytes memory _settlementData,
uint256 _gavOrZero,
bool _updateFees
) private {
address[] memory fees = comptrollerProxyToFees[_comptrollerProxy];
if (fees.length == 0) {
return;
}
address vaultProxy = getVaultProxyForFund(_comptrollerProxy);
// This check isn't strictly necessary, but its cost is insignificant,
// and helps to preserve data integrity.
require(vaultProxy != address(0), "__invokeHook: Fund is not active");
// First, allow all fees to implement settle()
uint256 gav = __settleFees(
_comptrollerProxy,
vaultProxy,
fees,
_hook,
_settlementData,
_gavOrZero
);
// Second, allow fees to implement update()
// This function does not allow any further altering of VaultProxy state
// (i.e., burning, minting, or transferring shares)
if (_updateFees) {
__updateFees(_comptrollerProxy, vaultProxy, fees, _hook, _settlementData, gav);
}
}
/// @dev Helper to payout the shares outstanding for the specified fees.
/// Does not call settle() on fees.
/// Only callable via ComptrollerProxy.callOnExtension().
function __payoutSharesOutstandingForFees(address _comptrollerProxy, bytes memory _callArgs)
private
{
address[] memory fees = abi.decode(_callArgs, (address[]));
address vaultProxy = getVaultProxyForFund(msg.sender);
uint256 sharesOutstandingDue;
for (uint256 i; i < fees.length; i++) {
if (!IFee(fees[i]).payout(_comptrollerProxy, vaultProxy)) {
continue;
}
uint256 sharesOutstandingForFee
= comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]];
if (sharesOutstandingForFee == 0) {
continue;
}
sharesOutstandingDue = sharesOutstandingDue.add(sharesOutstandingForFee);
// Delete shares outstanding and distribute from VaultProxy to the fees recipient
comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]] = 0;
emit SharesOutstandingPaidForFund(_comptrollerProxy, fees[i], sharesOutstandingForFee);
}
if (sharesOutstandingDue > 0) {
__transferShares(
_comptrollerProxy,
vaultProxy,
IVault(vaultProxy).getOwner(),
sharesOutstandingDue
);
}
}
/// @dev Helper to settle a fee
function __settleFee(
address _comptrollerProxy,
address _vaultProxy,
address _fee,
FeeHook _hook,
bytes memory _settlementData,
uint256 _gav
) private {
(SettlementType settlementType, address payer, uint256 sharesDue) = IFee(_fee).settle(
_comptrollerProxy,
_vaultProxy,
_hook,
_settlementData,
_gav
);
if (settlementType == SettlementType.None) {
return;
}
address payee;
if (settlementType == SettlementType.Direct) {
payee = IVault(_vaultProxy).getOwner();
__transferShares(_comptrollerProxy, payer, payee, sharesDue);
} else if (settlementType == SettlementType.Mint) {
payee = IVault(_vaultProxy).getOwner();
__mintShares(_comptrollerProxy, payee, sharesDue);
} else if (settlementType == SettlementType.Burn) {
__burnShares(_comptrollerProxy, payer, sharesDue);
} else if (settlementType == SettlementType.MintSharesOutstanding) {
comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]
.add(sharesDue);
payee = _vaultProxy;
__mintShares(_comptrollerProxy, payee, sharesDue);
} else if (settlementType == SettlementType.BurnSharesOutstanding) {
comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]
.sub(sharesDue);
payer = _vaultProxy;
__burnShares(_comptrollerProxy, payer, sharesDue);
} else {
revert("__settleFee: Invalid SettlementType");
}
emit FeeSettledForFund(_comptrollerProxy, _fee, settlementType, payer, payee, sharesDue);
}
/// @dev Helper to settle fees that implement a given fee hook
function __settleFees(
address _comptrollerProxy,
address _vaultProxy,
address[] memory _fees,
FeeHook _hook,
bytes memory _settlementData,
uint256 _gavOrZero
) private returns (uint256 gav_) {
gav_ = _gavOrZero;
for (uint256 i; i < _fees.length; i++) {
if (!feeSettlesOnHook(_fees[i], _hook)) {
continue;
}
gav_ = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav_);
__settleFee(_comptrollerProxy, _vaultProxy, _fees[i], _hook, _settlementData, gav_);
}
return gav_;
}
/// @dev Helper to update fees that implement a given fee hook
function __updateFees(
address _comptrollerProxy,
address _vaultProxy,
address[] memory _fees,
FeeHook _hook,
bytes memory _settlementData,
uint256 _gavOrZero
) private {
uint256 gav = _gavOrZero;
for (uint256 i; i < _fees.length; i++) {
if (!feeUpdatesOnHook(_fees[i], _hook)) {
continue;
}
gav = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav);
IFee(_fees[i]).update(_comptrollerProxy, _vaultProxy, _hook, _settlementData, gav);
}
}
///////////////////
// FEES REGISTRY //
///////////////////
/// @notice Remove fees from the list of registered fees
/// @param _fees Addresses of fees to be deregistered
function deregisterFees(address[] calldata _fees) external onlyFundDeployerOwner {
require(_fees.length > 0, "deregisterFees: _fees cannot be empty");
for (uint256 i; i < _fees.length; i++) {
require(isRegisteredFee(_fees[i]), "deregisterFees: fee is not registered");
registeredFees.remove(_fees[i]);
emit FeeDeregistered(_fees[i], IFee(_fees[i]).identifier());
}
}
/// @notice Add fees to the list of registered fees
/// @param _fees Addresses of fees to be registered
/// @dev Stores the hooks that a fee implements and whether each implementation uses GAV,
/// which fronts the gas for calls to check if a hook is implemented, and guarantees
/// that these hook implementation return values do not change post-registration.
function registerFees(address[] calldata _fees) external onlyFundDeployerOwner {
require(_fees.length > 0, "registerFees: _fees cannot be empty");
for (uint256 i; i < _fees.length; i++) {
require(!isRegisteredFee(_fees[i]), "registerFees: fee already registered");
registeredFees.add(_fees[i]);
IFee feeContract = IFee(_fees[i]);
(
FeeHook[] memory implementedHooksForSettle,
FeeHook[] memory implementedHooksForUpdate,
bool usesGavOnSettle,
bool usesGavOnUpdate
) = feeContract.implementedHooks();
// Stores the hooks for which each fee implements settle() and update()
for (uint256 j; j < implementedHooksForSettle.length; j++) {
feeToHookToImplementsSettle[_fees[i]][implementedHooksForSettle[j]] = true;
}
for (uint256 j; j < implementedHooksForUpdate.length; j++) {
feeToHookToImplementsUpdate[_fees[i]][implementedHooksForUpdate[j]] = true;
}
// Stores whether each fee requires GAV during its implementations for settle() and update()
if (usesGavOnSettle) {
feeToUsesGavOnSettle[_fees[i]] = true;
}
if (usesGavOnUpdate) {
feeToUsesGavOnUpdate[_fees[i]] = true;
}
emit FeeRegistered(
_fees[i],
feeContract.identifier(),
implementedHooksForSettle,
implementedHooksForUpdate,
usesGavOnSettle,
usesGavOnUpdate
);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Get a list of enabled fees for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return enabledFees_ An array of enabled fee addresses
function getEnabledFeesForFund(address _comptrollerProxy)
external
view
returns (address[] memory enabledFees_)
{
return comptrollerProxyToFees[_comptrollerProxy];
}
/// @notice Get the amount of shares outstanding for a particular fee for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _fee The fee address
/// @return sharesOutstanding_ The amount of shares outstanding
function getFeeSharesOutstandingForFund(address _comptrollerProxy, address _fee)
external
view
returns (uint256 sharesOutstanding_)
{
return comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee];
}
/// @notice Get all registered fees
/// @return registeredFees_ A list of all registered fee addresses
function getRegisteredFees() external view returns (address[] memory registeredFees_) {
registeredFees_ = new address[](registeredFees.length());
for (uint256 i; i < registeredFees_.length; i++) {
registeredFees_[i] = registeredFees.at(i);
}
return registeredFees_;
}
/// @notice Checks if a fee implements settle() on a particular hook
/// @param _fee The address of the fee to check
/// @param _hook The FeeHook to check
/// @return settlesOnHook_ True if the fee settles on the given hook
function feeSettlesOnHook(address _fee, FeeHook _hook)
public
view
returns (bool settlesOnHook_)
{
return feeToHookToImplementsSettle[_fee][_hook];
}
/// @notice Checks if a fee implements update() on a particular hook
/// @param _fee The address of the fee to check
/// @param _hook The FeeHook to check
/// @return updatesOnHook_ True if the fee updates on the given hook
function feeUpdatesOnHook(address _fee, FeeHook _hook)
public
view
returns (bool updatesOnHook_)
{
return feeToHookToImplementsUpdate[_fee][_hook];
}
/// @notice Checks if a fee uses GAV in its settle() implementation
/// @param _fee The address of the fee to check
/// @return usesGav_ True if the fee uses GAV during settle() implementation
function feeUsesGavOnSettle(address _fee) public view returns (bool usesGav_) {
return feeToUsesGavOnSettle[_fee];
}
/// @notice Checks if a fee uses GAV in its update() implementation
/// @param _fee The address of the fee to check
/// @return usesGav_ True if the fee uses GAV during update() implementation
function feeUsesGavOnUpdate(address _fee) public view returns (bool usesGav_) {
return feeToUsesGavOnUpdate[_fee];
}
/// @notice Check whether a fee is registered
/// @param _fee The address of the fee to check
/// @return isRegisteredFee_ True if the fee is registered
function isRegisteredFee(address _fee) public view returns (bool isRegisteredFee_) {
return registeredFees.contains(_fee);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../core/fund/comptroller/IComptroller.sol";
/// @title PermissionedVaultActionMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract for extensions that can make permissioned vault calls
abstract contract PermissionedVaultActionMixin {
/// @notice Adds a tracked asset to the fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset to add
function __addTrackedAsset(address _comptrollerProxy, address _asset) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.AddTrackedAsset,
abi.encode(_asset)
);
}
/// @notice Grants an allowance to a spender to use a fund's asset
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset for which to grant an allowance
/// @param _target The spender of the allowance
/// @param _amount The amount of the allowance
function __approveAssetSpender(
address _comptrollerProxy,
address _asset,
address _target,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.ApproveAssetSpender,
abi.encode(_asset, _target, _amount)
);
}
/// @notice Burns fund shares for a particular account
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _target The account for which to burn shares
/// @param _amount The amount of shares to burn
function __burnShares(
address _comptrollerProxy,
address _target,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.BurnShares,
abi.encode(_target, _amount)
);
}
/// @notice Mints fund shares to a particular account
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _target The account to which to mint shares
/// @param _amount The amount of shares to mint
function __mintShares(
address _comptrollerProxy,
address _target,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.MintShares,
abi.encode(_target, _amount)
);
}
/// @notice Removes a tracked asset from the fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset to remove
function __removeTrackedAsset(address _comptrollerProxy, address _asset) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.RemoveTrackedAsset,
abi.encode(_asset)
);
}
/// @notice Transfers fund shares from one account to another
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _from The account from which to transfer shares
/// @param _to The account to which to transfer shares
/// @param _amount The amount of shares to transfer
function __transferShares(
address _comptrollerProxy,
address _from,
address _to,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.TransferShares,
abi.encode(_from, _to, _amount)
);
}
/// @notice Withdraws an asset from the VaultProxy to a given account
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset to withdraw
/// @param _target The account to which to withdraw the asset
/// @param _amount The amount of asset to withdraw
function __withdrawAssetTo(
address _comptrollerProxy,
address _asset,
address _target,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.WithdrawAssetTo,
abi.encode(_asset, _target, _amount)
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../interfaces/IWETH.sol";
import "../core/fund/comptroller/ComptrollerLib.sol";
import "../extensions/fee-manager/FeeManager.sol";
/// @title FundActionsWrapper Contract
/// @author Enzyme Council <[email protected]>
/// @notice Logic related to wrapping fund actions, not necessary in the core protocol
contract FundActionsWrapper {
using SafeERC20 for ERC20;
address private immutable FEE_MANAGER;
address private immutable WETH_TOKEN;
mapping(address => bool) private accountToHasMaxWethAllowance;
constructor(address _feeManager, address _weth) public {
FEE_MANAGER = _feeManager;
WETH_TOKEN = _weth;
}
/// @dev Needed in case WETH not fully used during exchangeAndBuyShares,
/// to unwrap into ETH and refund
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Calculates the net value of 1 unit of shares in the fund's denomination asset
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return netShareValue_ The amount of the denomination asset per share
/// @return isValid_ True if the conversion rates to derive the value are all valid
/// @dev Accounts for fees outstanding. This is a convenience function for external consumption
/// that can be used to determine the cost of purchasing shares at any given point in time.
/// It essentially just bundles settling all fees that implement the Continuous hook and then
/// looking up the gross share value.
function calcNetShareValueForFund(address _comptrollerProxy)
external
returns (uint256 netShareValue_, bool isValid_)
{
ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy);
comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, "");
return comptrollerProxyContract.calcGrossShareValue(false);
}
/// @notice Exchanges ETH into a fund's denomination asset and then buys shares
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _buyer The account for which to buy shares
/// @param _minSharesQuantity The minimum quantity of shares to buy with the sent ETH
/// @param _exchange The exchange on which to execute the swap to the denomination asset
/// @param _exchangeApproveTarget The address that should be given an allowance of WETH
/// for the given _exchange
/// @param _exchangeData The data with which to call the exchange to execute the swap
/// to the denomination asset
/// @param _minInvestmentAmount The minimum amount of the denomination asset
/// to receive in the trade for investment (not necessary for WETH)
/// @return sharesReceivedAmount_ The actual amount of shares received
/// @dev Use a reasonable _minInvestmentAmount always, in case the exchange
/// does not perform as expected (low incoming asset amount, blend of assets, etc).
/// If the fund's denomination asset is WETH, _exchange, _exchangeApproveTarget, _exchangeData,
/// and _minInvestmentAmount will be ignored.
function exchangeAndBuyShares(
address _comptrollerProxy,
address _denominationAsset,
address _buyer,
uint256 _minSharesQuantity,
address _exchange,
address _exchangeApproveTarget,
bytes calldata _exchangeData,
uint256 _minInvestmentAmount
) external payable returns (uint256 sharesReceivedAmount_) {
// Wrap ETH into WETH
IWETH(payable(WETH_TOKEN)).deposit{value: msg.value}();
// If denominationAsset is WETH, can just buy shares directly
if (_denominationAsset == WETH_TOKEN) {
__approveMaxWethAsNeeded(_comptrollerProxy);
return __buyShares(_comptrollerProxy, _buyer, msg.value, _minSharesQuantity);
}
// Exchange ETH to the fund's denomination asset
__approveMaxWethAsNeeded(_exchangeApproveTarget);
(bool success, bytes memory returnData) = _exchange.call(_exchangeData);
require(success, string(returnData));
// Confirm the amount received in the exchange is above the min acceptable amount
uint256 investmentAmount = ERC20(_denominationAsset).balanceOf(address(this));
require(
investmentAmount >= _minInvestmentAmount,
"exchangeAndBuyShares: _minInvestmentAmount not met"
);
// Give the ComptrollerProxy max allowance for its denomination asset as necessary
__approveMaxAsNeeded(_denominationAsset, _comptrollerProxy, investmentAmount);
// Buy fund shares
sharesReceivedAmount_ = __buyShares(
_comptrollerProxy,
_buyer,
investmentAmount,
_minSharesQuantity
);
// Unwrap and refund any remaining WETH not used in the exchange
uint256 remainingWeth = ERC20(WETH_TOKEN).balanceOf(address(this));
if (remainingWeth > 0) {
IWETH(payable(WETH_TOKEN)).withdraw(remainingWeth);
(success, returnData) = msg.sender.call{value: remainingWeth}("");
require(success, string(returnData));
}
return sharesReceivedAmount_;
}
/// @notice Invokes the Continuous fee hook on all specified fees, and then attempts to payout
/// any shares outstanding on those fees
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _fees The fees for which to run these actions
/// @dev This is just a wrapper to execute two callOnExtension() actions atomically, in sequence.
/// The caller must pass in the fees that they want to run this logic on.
function invokeContinuousFeeHookAndPayoutSharesOutstandingForFund(
address _comptrollerProxy,
address[] calldata _fees
) external {
ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy);
comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, "");
comptrollerProxyContract.callOnExtension(FEE_MANAGER, 1, abi.encode(_fees));
}
// PUBLIC FUNCTIONS
/// @notice Gets all fees that implement the `Continuous` fee hook for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return continuousFees_ The fees that implement the `Continuous` fee hook
function getContinuousFeesForFund(address _comptrollerProxy)
public
view
returns (address[] memory continuousFees_)
{
FeeManager feeManagerContract = FeeManager(FEE_MANAGER);
address[] memory fees = feeManagerContract.getEnabledFeesForFund(_comptrollerProxy);
// Count the continuous fees
uint256 continuousFeesCount;
bool[] memory implementsContinuousHook = new bool[](fees.length);
for (uint256 i; i < fees.length; i++) {
if (feeManagerContract.feeSettlesOnHook(fees[i], IFeeManager.FeeHook.Continuous)) {
continuousFeesCount++;
implementsContinuousHook[i] = true;
}
}
// Return early if no continuous fees
if (continuousFeesCount == 0) {
return new address[](0);
}
// Create continuous fees array
continuousFees_ = new address[](continuousFeesCount);
uint256 continuousFeesIndex;
for (uint256 i; i < fees.length; i++) {
if (implementsContinuousHook[i]) {
continuousFees_[continuousFeesIndex] = fees[i];
continuousFeesIndex++;
}
}
return continuousFees_;
}
// PRIVATE FUNCTIONS
/// @dev Helper to approve a target with the max amount of an asset, only when necessary
function __approveMaxAsNeeded(
address _asset,
address _target,
uint256 _neededAmount
) internal {
if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) {
ERC20(_asset).safeApprove(_target, type(uint256).max);
}
}
/// @dev Helper to approve a target with the max amount of weth, only when necessary.
/// Since WETH does not decrease the allowance if it uint256(-1), only ever need to do this
/// once per target.
function __approveMaxWethAsNeeded(address _target) internal {
if (!accountHasMaxWethAllowance(_target)) {
ERC20(WETH_TOKEN).safeApprove(_target, type(uint256).max);
accountToHasMaxWethAllowance[_target] = true;
}
}
/// @dev Helper for buying shares
function __buyShares(
address _comptrollerProxy,
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity
) private returns (uint256 sharesReceivedAmount_) {
address[] memory buyers = new address[](1);
buyers[0] = _buyer;
uint256[] memory investmentAmounts = new uint256[](1);
investmentAmounts[0] = _investmentAmount;
uint256[] memory minSharesQuantities = new uint256[](1);
minSharesQuantities[0] = _minSharesQuantity;
return
ComptrollerLib(_comptrollerProxy).buyShares(
buyers,
investmentAmounts,
minSharesQuantities
)[0];
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `FEE_MANAGER` variable
/// @return feeManager_ The `FEE_MANAGER` variable value
function getFeeManager() external view returns (address feeManager_) {
return FEE_MANAGER;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
/// @notice Checks whether an account has the max allowance for WETH
/// @param _who The account to check
/// @return hasMaxWethAllowance_ True if the account has the max allowance
function accountHasMaxWethAllowance(address _who)
public
view
returns (bool hasMaxWethAllowance_)
{
return accountToHasMaxWethAllowance[_who];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title WETH Interface
/// @author Enzyme Council <[email protected]>
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../core/fund/comptroller/ComptrollerLib.sol";
import "../../core/fund/vault/VaultLib.sol";
import "./IAuthUserExecutedSharesRequestor.sol";
/// @title AuthUserExecutedSharesRequestorLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice Provides the logic for AuthUserExecutedSharesRequestorProxy instances,
/// in which shares requests are manually executed by a permissioned user
/// @dev This will not work with a `denominationAsset` that does not transfer
/// the exact expected amount or has an elastic supply.
contract AuthUserExecutedSharesRequestorLib is IAuthUserExecutedSharesRequestor {
using SafeERC20 for ERC20;
using SafeMath for uint256;
event RequestCanceled(
address indexed requestOwner,
uint256 investmentAmount,
uint256 minSharesQuantity
);
event RequestCreated(
address indexed requestOwner,
uint256 investmentAmount,
uint256 minSharesQuantity
);
event RequestExecuted(
address indexed caller,
address indexed requestOwner,
uint256 investmentAmount,
uint256 minSharesQuantity
);
event RequestExecutorAdded(address indexed account);
event RequestExecutorRemoved(address indexed account);
struct RequestInfo {
uint256 investmentAmount;
uint256 minSharesQuantity;
}
uint256 private constant CANCELLATION_COOLDOWN_TIMELOCK = 10 minutes;
address private comptrollerProxy;
address private denominationAsset;
address private fundOwner;
mapping(address => RequestInfo) private ownerToRequestInfo;
mapping(address => bool) private acctToIsRequestExecutor;
mapping(address => uint256) private ownerToLastRequestCancellation;
modifier onlyFundOwner() {
require(msg.sender == fundOwner, "Only fund owner callable");
_;
}
/// @notice Initializes a proxy instance that uses this library
/// @dev Serves as a per-proxy pseudo-constructor
function init(address _comptrollerProxy) external override {
require(comptrollerProxy == address(0), "init: Already initialized");
comptrollerProxy = _comptrollerProxy;
// Cache frequently-used values that require external calls
ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy);
denominationAsset = comptrollerProxyContract.getDenominationAsset();
fundOwner = VaultLib(comptrollerProxyContract.getVaultProxy()).getOwner();
}
/// @notice Cancels the shares request of the caller
function cancelRequest() external {
RequestInfo memory request = ownerToRequestInfo[msg.sender];
require(request.investmentAmount > 0, "cancelRequest: Request does not exist");
// Delete the request, start the cooldown period, and return the investment asset
delete ownerToRequestInfo[msg.sender];
ownerToLastRequestCancellation[msg.sender] = block.timestamp;
ERC20(denominationAsset).safeTransfer(msg.sender, request.investmentAmount);
emit RequestCanceled(msg.sender, request.investmentAmount, request.minSharesQuantity);
}
/// @notice Creates a shares request for the caller
/// @param _investmentAmount The amount of the fund's denomination asset to use to buy shares
/// @param _minSharesQuantity The minimum quantity of shares to buy with the _investmentAmount
function createRequest(uint256 _investmentAmount, uint256 _minSharesQuantity) external {
require(_investmentAmount > 0, "createRequest: _investmentAmount must be > 0");
require(
ownerToRequestInfo[msg.sender].investmentAmount == 0,
"createRequest: The request owner can only create one request before executed or canceled"
);
require(
ownerToLastRequestCancellation[msg.sender] <
block.timestamp.sub(CANCELLATION_COOLDOWN_TIMELOCK),
"createRequest: Cannot create request during cancellation cooldown period"
);
// Create the Request and take custody of investment asset
ownerToRequestInfo[msg.sender] = RequestInfo({
investmentAmount: _investmentAmount,
minSharesQuantity: _minSharesQuantity
});
ERC20(denominationAsset).safeTransferFrom(msg.sender, address(this), _investmentAmount);
emit RequestCreated(msg.sender, _investmentAmount, _minSharesQuantity);
}
/// @notice Executes multiple shares requests
/// @param _requestOwners The owners of the pending shares requests
function executeRequests(address[] calldata _requestOwners) external {
require(
msg.sender == fundOwner || isRequestExecutor(msg.sender),
"executeRequests: Invalid caller"
);
require(_requestOwners.length > 0, "executeRequests: _requestOwners can not be empty");
(
address[] memory buyers,
uint256[] memory investmentAmounts,
uint256[] memory minSharesQuantities,
uint256 totalInvestmentAmount
) = __convertRequestsToBuySharesParams(_requestOwners);
// Since ComptrollerProxy instances are fully trusted,
// we can approve them with the max amount of the denomination asset,
// and only top the approval back to max if ever necessary.
address comptrollerProxyCopy = comptrollerProxy;
ERC20 denominationAssetContract = ERC20(denominationAsset);
if (
denominationAssetContract.allowance(address(this), comptrollerProxyCopy) <
totalInvestmentAmount
) {
denominationAssetContract.safeApprove(comptrollerProxyCopy, type(uint256).max);
}
ComptrollerLib(comptrollerProxyCopy).buyShares(
buyers,
investmentAmounts,
minSharesQuantities
);
}
/// @dev Helper to convert raw shares requests into the format required by buyShares().
/// It also removes any empty requests, which is necessary to prevent a DoS attack where a user
/// cancels their request earlier in the same block (can be repeated from multiple accounts).
/// This function also removes shares requests and fires success events as it loops through them.
function __convertRequestsToBuySharesParams(address[] memory _requestOwners)
private
returns (
address[] memory buyers_,
uint256[] memory investmentAmounts_,
uint256[] memory minSharesQuantities_,
uint256 totalInvestmentAmount_
)
{
uint256 existingRequestsCount = _requestOwners.length;
uint256[] memory allInvestmentAmounts = new uint256[](_requestOwners.length);
// Loop through once to get the count of existing requests
for (uint256 i; i < _requestOwners.length; i++) {
allInvestmentAmounts[i] = ownerToRequestInfo[_requestOwners[i]].investmentAmount;
if (allInvestmentAmounts[i] == 0) {
existingRequestsCount--;
}
}
// Loop through a second time to format requests for buyShares(),
// and to delete the requests and emit events early so no further looping is needed.
buyers_ = new address[](existingRequestsCount);
investmentAmounts_ = new uint256[](existingRequestsCount);
minSharesQuantities_ = new uint256[](existingRequestsCount);
uint256 existingRequestsIndex;
for (uint256 i; i < _requestOwners.length; i++) {
if (allInvestmentAmounts[i] == 0) {
continue;
}
buyers_[existingRequestsIndex] = _requestOwners[i];
investmentAmounts_[existingRequestsIndex] = allInvestmentAmounts[i];
minSharesQuantities_[existingRequestsIndex] = ownerToRequestInfo[_requestOwners[i]]
.minSharesQuantity;
totalInvestmentAmount_ = totalInvestmentAmount_.add(allInvestmentAmounts[i]);
delete ownerToRequestInfo[_requestOwners[i]];
emit RequestExecuted(
msg.sender,
buyers_[existingRequestsIndex],
investmentAmounts_[existingRequestsIndex],
minSharesQuantities_[existingRequestsIndex]
);
existingRequestsIndex++;
}
return (buyers_, investmentAmounts_, minSharesQuantities_, totalInvestmentAmount_);
}
///////////////////////////////
// REQUEST EXECUTOR REGISTRY //
///////////////////////////////
/// @notice Adds accounts to request executors
/// @param _requestExecutors Accounts to add
function addRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner {
require(_requestExecutors.length > 0, "addRequestExecutors: Empty _requestExecutors");
for (uint256 i; i < _requestExecutors.length; i++) {
require(
!isRequestExecutor(_requestExecutors[i]),
"addRequestExecutors: Value already set"
);
require(
_requestExecutors[i] != fundOwner,
"addRequestExecutors: The fund owner cannot be added"
);
acctToIsRequestExecutor[_requestExecutors[i]] = true;
emit RequestExecutorAdded(_requestExecutors[i]);
}
}
/// @notice Removes accounts from request executors
/// @param _requestExecutors Accounts to remove
function removeRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner {
require(_requestExecutors.length > 0, "removeRequestExecutors: Empty _requestExecutors");
for (uint256 i; i < _requestExecutors.length; i++) {
require(
isRequestExecutor(_requestExecutors[i]),
"removeRequestExecutors: Account is not a request executor"
);
acctToIsRequestExecutor[_requestExecutors[i]] = false;
emit RequestExecutorRemoved(_requestExecutors[i]);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the value of `comptrollerProxy` variable
/// @return comptrollerProxy_ The `comptrollerProxy` variable value
function getComptrollerProxy() external view returns (address comptrollerProxy_) {
return comptrollerProxy;
}
/// @notice Gets the value of `denominationAsset` variable
/// @return denominationAsset_ The `denominationAsset` variable value
function getDenominationAsset() external view returns (address denominationAsset_) {
return denominationAsset;
}
/// @notice Gets the value of `fundOwner` variable
/// @return fundOwner_ The `fundOwner` variable value
function getFundOwner() external view returns (address fundOwner_) {
return fundOwner;
}
/// @notice Gets the request info of a user
/// @param _requestOwner The address of the user that creates the request
/// @return requestInfo_ The request info created by the user
function getSharesRequestInfoForOwner(address _requestOwner)
external
view
returns (RequestInfo memory requestInfo_)
{
return ownerToRequestInfo[_requestOwner];
}
/// @notice Checks whether an account is a request executor
/// @param _who The account to check
/// @return isRequestExecutor_ True if _who is a request executor
function isRequestExecutor(address _who) public view returns (bool isRequestExecutor_) {
return acctToIsRequestExecutor[_who];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IAuthUserExecutedSharesRequestor Interface
/// @author Enzyme Council <[email protected]>
interface IAuthUserExecutedSharesRequestor {
function init(address) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../core/fund/comptroller/ComptrollerLib.sol";
import "../../core/fund/vault/VaultLib.sol";
import "./AuthUserExecutedSharesRequestorProxy.sol";
import "./IAuthUserExecutedSharesRequestor.sol";
/// @title AuthUserExecutedSharesRequestorFactory Contract
/// @author Enzyme Council <[email protected]>
/// @notice Deploys and maintains a record of AuthUserExecutedSharesRequestorProxy instances
contract AuthUserExecutedSharesRequestorFactory {
event SharesRequestorProxyDeployed(
address indexed comptrollerProxy,
address sharesRequestorProxy
);
address private immutable AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB;
address private immutable DISPATCHER;
mapping(address => address) private comptrollerProxyToSharesRequestorProxy;
constructor(address _dispatcher, address _authUserExecutedSharesRequestorLib) public {
AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB = _authUserExecutedSharesRequestorLib;
DISPATCHER = _dispatcher;
}
/// @notice Deploys a shares requestor proxy instance for a given ComptrollerProxy instance
/// @param _comptrollerProxy The ComptrollerProxy for which to deploy the shares requestor proxy
/// @return sharesRequestorProxy_ The address of the newly-deployed shares requestor proxy
function deploySharesRequestorProxy(address _comptrollerProxy)
external
returns (address sharesRequestorProxy_)
{
// Confirm fund is genuine
VaultLib vaultProxyContract = VaultLib(ComptrollerLib(_comptrollerProxy).getVaultProxy());
require(
vaultProxyContract.getAccessor() == _comptrollerProxy,
"deploySharesRequestorProxy: Invalid VaultProxy for ComptrollerProxy"
);
require(
IDispatcher(DISPATCHER).getFundDeployerForVaultProxy(address(vaultProxyContract)) !=
address(0),
"deploySharesRequestorProxy: Not a genuine fund"
);
// Validate that the caller is the fund owner
require(
msg.sender == vaultProxyContract.getOwner(),
"deploySharesRequestorProxy: Only fund owner callable"
);
// Validate that a proxy does not already exist
require(
comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] == address(0),
"deploySharesRequestorProxy: Proxy already exists"
);
// Deploy the proxy
bytes memory constructData = abi.encodeWithSelector(
IAuthUserExecutedSharesRequestor.init.selector,
_comptrollerProxy
);
sharesRequestorProxy_ = address(
new AuthUserExecutedSharesRequestorProxy(
constructData,
AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB
)
);
comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] = sharesRequestorProxy_;
emit SharesRequestorProxyDeployed(_comptrollerProxy, sharesRequestorProxy_);
return sharesRequestorProxy_;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the value of the `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable
/// @return authUserExecutedSharesRequestorLib_ The `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable value
function getAuthUserExecutedSharesRequestorLib()
external
view
returns (address authUserExecutedSharesRequestorLib_)
{
return AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB;
}
/// @notice Gets the value of the `DISPATCHER` variable
/// @return dispatcher_ The `DISPATCHER` variable value
function getDispatcher() external view returns (address dispatcher_) {
return DISPATCHER;
}
/// @notice Gets the AuthUserExecutedSharesRequestorProxy associated with the given ComptrollerProxy
/// @param _comptrollerProxy The ComptrollerProxy for which to get the associated AuthUserExecutedSharesRequestorProxy
/// @return sharesRequestorProxy_ The associated AuthUserExecutedSharesRequestorProxy address
function getSharesRequestorProxyForComptrollerProxy(address _comptrollerProxy)
external
view
returns (address sharesRequestorProxy_)
{
return comptrollerProxyToSharesRequestorProxy[_comptrollerProxy];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/Proxy.sol";
contract AuthUserExecutedSharesRequestorProxy is Proxy {
constructor(bytes memory _constructData, address _authUserExecutedSharesRequestorLib)
public
Proxy(_constructData, _authUserExecutedSharesRequestorLib)
{}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title Proxy Contract
/// @author Enzyme Council <[email protected]>
/// @notice A proxy contract for all Proxy instances
/// @dev The recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12,
/// and using the EIP-1967 storage slot for the proxiable implementation.
/// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is
/// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"
/// See: https://eips.ethereum.org/EIPS/eip-1822
contract Proxy {
constructor(bytes memory _constructData, address _contractLogic) public {
assembly {
sstore(
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc,
_contractLogic
)
}
(bool success, bytes memory returnData) = _contractLogic.delegatecall(_constructData);
require(success, string(returnData));
}
fallback() external payable {
assembly {
let contractLogic := sload(
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc
)
calldatacopy(0x0, 0x0, calldatasize())
let success := delegatecall(
sub(gas(), 10000),
contractLogic,
0x0,
calldatasize(),
0,
0
)
let retSz := returndatasize()
returndatacopy(0, 0, retSz)
switch success
case 0 {
revert(0, retSz)
}
default {
return(0, retSz)
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../utils/Proxy.sol";
/// @title ComptrollerProxy Contract
/// @author Enzyme Council <[email protected]>
/// @notice A proxy contract for all ComptrollerProxy instances
contract ComptrollerProxy is Proxy {
constructor(bytes memory _constructData, address _comptrollerLib)
public
Proxy(_constructData, _comptrollerLib)
{}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../../persistent/dispatcher/IDispatcher.sol";
import "../../../persistent/utils/IMigrationHookHandler.sol";
import "../fund/comptroller/IComptroller.sol";
import "../fund/comptroller/ComptrollerProxy.sol";
import "../fund/vault/IVault.sol";
import "./IFundDeployer.sol";
/// @title FundDeployer Contract
/// @author Enzyme Council <[email protected]>
/// @notice The top-level contract of the release.
/// It primarily coordinates fund deployment and fund migration, but
/// it is also deferred to for contract access control and for allowed calls
/// that can be made with a fund's VaultProxy as the msg.sender.
contract FundDeployer is IFundDeployer, IMigrationHookHandler {
event ComptrollerLibSet(address comptrollerLib);
event ComptrollerProxyDeployed(
address indexed creator,
address comptrollerProxy,
address indexed denominationAsset,
uint256 sharesActionTimelock,
bytes feeManagerConfigData,
bytes policyManagerConfigData,
bool indexed forMigration
);
event NewFundCreated(
address indexed creator,
address comptrollerProxy,
address vaultProxy,
address indexed fundOwner,
string fundName,
address indexed denominationAsset,
uint256 sharesActionTimelock,
bytes feeManagerConfigData,
bytes policyManagerConfigData
);
event ReleaseStatusSet(ReleaseStatus indexed prevStatus, ReleaseStatus indexed nextStatus);
event VaultCallDeregistered(address indexed contractAddress, bytes4 selector);
event VaultCallRegistered(address indexed contractAddress, bytes4 selector);
// Constants
address private immutable CREATOR;
address private immutable DISPATCHER;
address private immutable VAULT_LIB;
// Pseudo-constants (can only be set once)
address private comptrollerLib;
// Storage
ReleaseStatus private releaseStatus;
mapping(address => mapping(bytes4 => bool)) private contractToSelectorToIsRegisteredVaultCall;
mapping(address => address) private pendingComptrollerProxyToCreator;
modifier onlyLiveRelease() {
require(releaseStatus == ReleaseStatus.Live, "Release is not Live");
_;
}
modifier onlyMigrator(address _vaultProxy) {
require(
IVault(_vaultProxy).canMigrate(msg.sender),
"Only a permissioned migrator can call this function"
);
_;
}
modifier onlyOwner() {
require(msg.sender == getOwner(), "Only the contract owner can call this function");
_;
}
modifier onlyPendingComptrollerProxyCreator(address _comptrollerProxy) {
require(
msg.sender == pendingComptrollerProxyToCreator[_comptrollerProxy],
"Only the ComptrollerProxy creator can call this function"
);
_;
}
constructor(
address _dispatcher,
address _vaultLib,
address[] memory _vaultCallContracts,
bytes4[] memory _vaultCallSelectors
) public {
if (_vaultCallContracts.length > 0) {
__registerVaultCalls(_vaultCallContracts, _vaultCallSelectors);
}
CREATOR = msg.sender;
DISPATCHER = _dispatcher;
VAULT_LIB = _vaultLib;
}
/////////////
// GENERAL //
/////////////
/// @notice Sets the comptrollerLib
/// @param _comptrollerLib The ComptrollerLib contract address
/// @dev Can only be set once
function setComptrollerLib(address _comptrollerLib) external onlyOwner {
require(
comptrollerLib == address(0),
"setComptrollerLib: This value can only be set once"
);
comptrollerLib = _comptrollerLib;
emit ComptrollerLibSet(_comptrollerLib);
}
/// @notice Sets the status of the protocol to a new state
/// @param _nextStatus The next status state to set
function setReleaseStatus(ReleaseStatus _nextStatus) external {
require(
msg.sender == IDispatcher(DISPATCHER).getOwner(),
"setReleaseStatus: Only the Dispatcher owner can call this function"
);
require(
_nextStatus != ReleaseStatus.PreLaunch,
"setReleaseStatus: Cannot return to PreLaunch status"
);
require(
comptrollerLib != address(0),
"setReleaseStatus: Can only set the release status when comptrollerLib is set"
);
ReleaseStatus prevStatus = releaseStatus;
require(_nextStatus != prevStatus, "setReleaseStatus: _nextStatus is the current status");
releaseStatus = _nextStatus;
emit ReleaseStatusSet(prevStatus, _nextStatus);
}
/// @notice Gets the current owner of the contract
/// @return owner_ The contract owner address
/// @dev Dynamically gets the owner based on the Protocol status. The owner is initially the
/// contract's deployer, for convenience in setting up configuration.
/// Ownership is claimed when the owner of the Dispatcher contract (the Enzyme Council)
/// sets the releaseStatus to `Live`.
function getOwner() public view override returns (address owner_) {
if (releaseStatus == ReleaseStatus.PreLaunch) {
return CREATOR;
}
return IDispatcher(DISPATCHER).getOwner();
}
///////////////////
// FUND CREATION //
///////////////////
/// @notice Creates a fully-configured ComptrollerProxy, to which a fund from a previous
/// release can migrate in a subsequent step
/// @param _denominationAsset The contract address of the denomination asset for the fund
/// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions"
/// (buying or selling shares) by the same user
/// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund
/// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund
/// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action
function createMigratedFundConfig(
address _denominationAsset,
uint256 _sharesActionTimelock,
bytes calldata _feeManagerConfigData,
bytes calldata _policyManagerConfigData
) external onlyLiveRelease returns (address comptrollerProxy_) {
comptrollerProxy_ = __deployComptrollerProxy(
_denominationAsset,
_sharesActionTimelock,
_feeManagerConfigData,
_policyManagerConfigData,
true
);
pendingComptrollerProxyToCreator[comptrollerProxy_] = msg.sender;
return comptrollerProxy_;
}
/// @notice Creates a new fund
/// @param _fundOwner The address of the owner for the fund
/// @param _fundName The name of the fund
/// @param _denominationAsset The contract address of the denomination asset for the fund
/// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions"
/// (buying or selling shares) by the same user
/// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund
/// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund
/// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action
function createNewFund(
address _fundOwner,
string calldata _fundName,
address _denominationAsset,
uint256 _sharesActionTimelock,
bytes calldata _feeManagerConfigData,
bytes calldata _policyManagerConfigData
) external onlyLiveRelease returns (address comptrollerProxy_, address vaultProxy_) {
return
__createNewFund(
_fundOwner,
_fundName,
_denominationAsset,
_sharesActionTimelock,
_feeManagerConfigData,
_policyManagerConfigData
);
}
/// @dev Helper to avoid the stack-too-deep error during createNewFund
function __createNewFund(
address _fundOwner,
string memory _fundName,
address _denominationAsset,
uint256 _sharesActionTimelock,
bytes memory _feeManagerConfigData,
bytes memory _policyManagerConfigData
) private returns (address comptrollerProxy_, address vaultProxy_) {
require(_fundOwner != address(0), "__createNewFund: _owner cannot be empty");
comptrollerProxy_ = __deployComptrollerProxy(
_denominationAsset,
_sharesActionTimelock,
_feeManagerConfigData,
_policyManagerConfigData,
false
);
vaultProxy_ = IDispatcher(DISPATCHER).deployVaultProxy(
VAULT_LIB,
_fundOwner,
comptrollerProxy_,
_fundName
);
IComptroller(comptrollerProxy_).activate(vaultProxy_, false);
emit NewFundCreated(
msg.sender,
comptrollerProxy_,
vaultProxy_,
_fundOwner,
_fundName,
_denominationAsset,
_sharesActionTimelock,
_feeManagerConfigData,
_policyManagerConfigData
);
return (comptrollerProxy_, vaultProxy_);
}
/// @dev Helper function to deploy a configured ComptrollerProxy
function __deployComptrollerProxy(
address _denominationAsset,
uint256 _sharesActionTimelock,
bytes memory _feeManagerConfigData,
bytes memory _policyManagerConfigData,
bool _forMigration
) private returns (address comptrollerProxy_) {
require(
_denominationAsset != address(0),
"__deployComptrollerProxy: _denominationAsset cannot be empty"
);
bytes memory constructData = abi.encodeWithSelector(
IComptroller.init.selector,
_denominationAsset,
_sharesActionTimelock
);
comptrollerProxy_ = address(new ComptrollerProxy(constructData, comptrollerLib));
if (_feeManagerConfigData.length > 0 || _policyManagerConfigData.length > 0) {
IComptroller(comptrollerProxy_).configureExtensions(
_feeManagerConfigData,
_policyManagerConfigData
);
}
emit ComptrollerProxyDeployed(
msg.sender,
comptrollerProxy_,
_denominationAsset,
_sharesActionTimelock,
_feeManagerConfigData,
_policyManagerConfigData,
_forMigration
);
return comptrollerProxy_;
}
//////////////////
// MIGRATION IN //
//////////////////
/// @notice Cancels fund migration
/// @param _vaultProxy The VaultProxy for which to cancel migration
function cancelMigration(address _vaultProxy) external {
__cancelMigration(_vaultProxy, false);
}
/// @notice Cancels fund migration, bypassing any failures.
/// Should be used in an emergency only.
/// @param _vaultProxy The VaultProxy for which to cancel migration
function cancelMigrationEmergency(address _vaultProxy) external {
__cancelMigration(_vaultProxy, true);
}
/// @notice Executes fund migration
/// @param _vaultProxy The VaultProxy for which to execute the migration
function executeMigration(address _vaultProxy) external {
__executeMigration(_vaultProxy, false);
}
/// @notice Executes fund migration, bypassing any failures.
/// Should be used in an emergency only.
/// @param _vaultProxy The VaultProxy for which to execute the migration
function executeMigrationEmergency(address _vaultProxy) external {
__executeMigration(_vaultProxy, true);
}
/// @dev Unimplemented
function invokeMigrationInCancelHook(
address,
address,
address,
address
) external virtual override {
return;
}
/// @notice Signal a fund migration
/// @param _vaultProxy The VaultProxy for which to signal the migration
/// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration
function signalMigration(address _vaultProxy, address _comptrollerProxy) external {
__signalMigration(_vaultProxy, _comptrollerProxy, false);
}
/// @notice Signal a fund migration, bypassing any failures.
/// Should be used in an emergency only.
/// @param _vaultProxy The VaultProxy for which to signal the migration
/// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration
function signalMigrationEmergency(address _vaultProxy, address _comptrollerProxy) external {
__signalMigration(_vaultProxy, _comptrollerProxy, true);
}
/// @dev Helper to cancel a migration
function __cancelMigration(address _vaultProxy, bool _bypassFailure)
private
onlyLiveRelease
onlyMigrator(_vaultProxy)
{
IDispatcher(DISPATCHER).cancelMigration(_vaultProxy, _bypassFailure);
}
/// @dev Helper to execute a migration
function __executeMigration(address _vaultProxy, bool _bypassFailure)
private
onlyLiveRelease
onlyMigrator(_vaultProxy)
{
IDispatcher dispatcherContract = IDispatcher(DISPATCHER);
(, address comptrollerProxy, , ) = dispatcherContract
.getMigrationRequestDetailsForVaultProxy(_vaultProxy);
dispatcherContract.executeMigration(_vaultProxy, _bypassFailure);
IComptroller(comptrollerProxy).activate(_vaultProxy, true);
delete pendingComptrollerProxyToCreator[comptrollerProxy];
}
/// @dev Helper to signal a migration
function __signalMigration(
address _vaultProxy,
address _comptrollerProxy,
bool _bypassFailure
)
private
onlyLiveRelease
onlyPendingComptrollerProxyCreator(_comptrollerProxy)
onlyMigrator(_vaultProxy)
{
IDispatcher(DISPATCHER).signalMigration(
_vaultProxy,
_comptrollerProxy,
VAULT_LIB,
_bypassFailure
);
}
///////////////////
// MIGRATION OUT //
///////////////////
/// @notice Allows "hooking into" specific moments in the migration pipeline
/// to execute arbitrary logic during a migration out of this release
/// @param _vaultProxy The VaultProxy being migrated
function invokeMigrationOutHook(
MigrationOutHook _hook,
address _vaultProxy,
address,
address,
address
) external override {
if (_hook != MigrationOutHook.PreMigrate) {
return;
}
require(
msg.sender == DISPATCHER,
"postMigrateOriginHook: Only Dispatcher can call this function"
);
// Must use PreMigrate hook to get the ComptrollerProxy from the VaultProxy
address comptrollerProxy = IVault(_vaultProxy).getAccessor();
// Wind down fund and destroy its config
IComptroller(comptrollerProxy).destruct();
}
//////////////
// REGISTRY //
//////////////
/// @notice De-registers allowed arbitrary contract calls that can be sent from the VaultProxy
/// @param _contracts The contracts of the calls to de-register
/// @param _selectors The selectors of the calls to de-register
function deregisterVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors)
external
onlyOwner
{
require(_contracts.length > 0, "deregisterVaultCalls: Empty _contracts");
require(
_contracts.length == _selectors.length,
"deregisterVaultCalls: Uneven input arrays"
);
for (uint256 i; i < _contracts.length; i++) {
require(
isRegisteredVaultCall(_contracts[i], _selectors[i]),
"deregisterVaultCalls: Call not registered"
);
contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = false;
emit VaultCallDeregistered(_contracts[i], _selectors[i]);
}
}
/// @notice Registers allowed arbitrary contract calls that can be sent from the VaultProxy
/// @param _contracts The contracts of the calls to register
/// @param _selectors The selectors of the calls to register
function registerVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors)
external
onlyOwner
{
require(_contracts.length > 0, "registerVaultCalls: Empty _contracts");
__registerVaultCalls(_contracts, _selectors);
}
/// @dev Helper to register allowed vault calls
function __registerVaultCalls(address[] memory _contracts, bytes4[] memory _selectors)
private
{
require(
_contracts.length == _selectors.length,
"__registerVaultCalls: Uneven input arrays"
);
for (uint256 i; i < _contracts.length; i++) {
require(
!isRegisteredVaultCall(_contracts[i], _selectors[i]),
"__registerVaultCalls: Call already registered"
);
contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = true;
emit VaultCallRegistered(_contracts[i], _selectors[i]);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `comptrollerLib` variable value
/// @return comptrollerLib_ The `comptrollerLib` variable value
function getComptrollerLib() external view returns (address comptrollerLib_) {
return comptrollerLib;
}
/// @notice Gets the `CREATOR` variable value
/// @return creator_ The `CREATOR` variable value
function getCreator() external view returns (address creator_) {
return CREATOR;
}
/// @notice Gets the `DISPATCHER` variable value
/// @return dispatcher_ The `DISPATCHER` variable value
function getDispatcher() external view returns (address dispatcher_) {
return DISPATCHER;
}
/// @notice Gets the creator of a pending ComptrollerProxy
/// @return pendingComptrollerProxyCreator_ The pending ComptrollerProxy creator
function getPendingComptrollerProxyCreator(address _comptrollerProxy)
external
view
returns (address pendingComptrollerProxyCreator_)
{
return pendingComptrollerProxyToCreator[_comptrollerProxy];
}
/// @notice Gets the `releaseStatus` variable value
/// @return status_ The `releaseStatus` variable value
function getReleaseStatus() external view override returns (ReleaseStatus status_) {
return releaseStatus;
}
/// @notice Gets the `VAULT_LIB` variable value
/// @return vaultLib_ The `VAULT_LIB` variable value
function getVaultLib() external view returns (address vaultLib_) {
return VAULT_LIB;
}
/// @notice Checks if a contract call is registered
/// @param _contract The contract of the call to check
/// @param _selector The selector of the call to check
/// @return isRegistered_ True if the call is registered
function isRegisteredVaultCall(address _contract, bytes4 _selector)
public
view
override
returns (bool isRegistered_)
{
return contractToSelectorToIsRegisteredVaultCall[_contract][_selector];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IMigrationHookHandler Interface
/// @author Enzyme Council <[email protected]>
interface IMigrationHookHandler {
enum MigrationOutHook {PreSignal, PostSignal, PreMigrate, PostMigrate, PostCancel}
function invokeMigrationInCancelHook(
address _vaultProxy,
address _prevFundDeployer,
address _nextVaultAccessor,
address _nextVaultLib
) external;
function invokeMigrationOutHook(
MigrationOutHook _hook,
address _vaultProxy,
address _nextFundDeployer,
address _nextVaultAccessor,
address _nextVaultLib
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "../../core/fund/vault/IVault.sol";
import "../../infrastructure/price-feeds/derivatives/IDerivativePriceFeed.sol";
import "../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol";
import "../../utils/AddressArrayLib.sol";
import "../../utils/AssetFinalityResolver.sol";
import "../policy-manager/IPolicyManager.sol";
import "../utils/ExtensionBase.sol";
import "../utils/FundDeployerOwnerMixin.sol";
import "../utils/PermissionedVaultActionMixin.sol";
import "./integrations/IIntegrationAdapter.sol";
import "./IIntegrationManager.sol";
/// @title IntegrationManager
/// @author Enzyme Council <[email protected]>
/// @notice Extension to handle DeFi integration actions for funds
contract IntegrationManager is
IIntegrationManager,
ExtensionBase,
FundDeployerOwnerMixin,
PermissionedVaultActionMixin,
AssetFinalityResolver
{
using AddressArrayLib for address[];
using EnumerableSet for EnumerableSet.AddressSet;
using SafeMath for uint256;
event AdapterDeregistered(address indexed adapter, string indexed identifier);
event AdapterRegistered(address indexed adapter, string indexed identifier);
event AuthUserAddedForFund(address indexed comptrollerProxy, address indexed account);
event AuthUserRemovedForFund(address indexed comptrollerProxy, address indexed account);
event CallOnIntegrationExecutedForFund(
address indexed comptrollerProxy,
address vaultProxy,
address caller,
address indexed adapter,
bytes4 indexed selector,
bytes integrationData,
address[] incomingAssets,
uint256[] incomingAssetAmounts,
address[] outgoingAssets,
uint256[] outgoingAssetAmounts
);
address private immutable DERIVATIVE_PRICE_FEED;
address private immutable POLICY_MANAGER;
address private immutable PRIMITIVE_PRICE_FEED;
EnumerableSet.AddressSet private registeredAdapters;
mapping(address => mapping(address => bool)) private comptrollerProxyToAcctToIsAuthUser;
constructor(
address _fundDeployer,
address _policyManager,
address _derivativePriceFeed,
address _primitivePriceFeed,
address _synthetixPriceFeed,
address _synthetixAddressResolver
)
public
FundDeployerOwnerMixin(_fundDeployer)
AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver)
{
DERIVATIVE_PRICE_FEED = _derivativePriceFeed;
POLICY_MANAGER = _policyManager;
PRIMITIVE_PRICE_FEED = _primitivePriceFeed;
}
/////////////
// GENERAL //
/////////////
/// @notice Activates the extension by storing the VaultProxy
function activateForFund(bool) external override {
__setValidatedVaultProxy(msg.sender);
}
/// @notice Authorizes a user to act on behalf of a fund via the IntegrationManager
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _who The user to authorize
function addAuthUserForFund(address _comptrollerProxy, address _who) external {
__validateSetAuthUser(_comptrollerProxy, _who, true);
comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = true;
emit AuthUserAddedForFund(_comptrollerProxy, _who);
}
/// @notice Deactivate the extension by destroying storage
function deactivateForFund() external override {
delete comptrollerProxyToVaultProxy[msg.sender];
}
/// @notice Removes an authorized user from the IntegrationManager for the given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _who The authorized user to remove
function removeAuthUserForFund(address _comptrollerProxy, address _who) external {
__validateSetAuthUser(_comptrollerProxy, _who, false);
comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = false;
emit AuthUserRemovedForFund(_comptrollerProxy, _who);
}
/// @notice Checks whether an account is an authorized IntegrationManager user for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _who The account to check
/// @return isAuthUser_ True if the account is an authorized user or the fund owner
function isAuthUserForFund(address _comptrollerProxy, address _who)
public
view
returns (bool isAuthUser_)
{
return
comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] ||
_who == IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner();
}
/// @dev Helper to validate calls to update comptrollerProxyToAcctToIsAuthUser
function __validateSetAuthUser(
address _comptrollerProxy,
address _who,
bool _nextIsAuthUser
) private view {
require(
comptrollerProxyToVaultProxy[_comptrollerProxy] != address(0),
"__validateSetAuthUser: Fund has not been activated"
);
address fundOwner = IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner();
require(
msg.sender == fundOwner,
"__validateSetAuthUser: Only the fund owner can call this function"
);
require(_who != fundOwner, "__validateSetAuthUser: Cannot set for the fund owner");
if (_nextIsAuthUser) {
require(
!comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who],
"__validateSetAuthUser: Account is already an authorized user"
);
} else {
require(
comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who],
"__validateSetAuthUser: Account is not an authorized user"
);
}
}
///////////////////////////////
// CALL-ON-EXTENSION ACTIONS //
///////////////////////////////
/// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy
/// @param _caller The user who called for this action
/// @param _actionId An ID representing the desired action
/// @param _callArgs The encoded args for the action
function receiveCallFromComptroller(
address _caller,
uint256 _actionId,
bytes calldata _callArgs
) external override {
// Since we validate and store the ComptrollerProxy-VaultProxy pairing during
// activateForFund(), this function does not require further validation of the
// sending ComptrollerProxy
address vaultProxy = comptrollerProxyToVaultProxy[msg.sender];
require(vaultProxy != address(0), "receiveCallFromComptroller: Fund is not active");
require(
isAuthUserForFund(msg.sender, _caller),
"receiveCallFromComptroller: Not an authorized user"
);
// Dispatch the action
if (_actionId == 0) {
__callOnIntegration(_caller, vaultProxy, _callArgs);
} else if (_actionId == 1) {
__addZeroBalanceTrackedAssets(vaultProxy, _callArgs);
} else if (_actionId == 2) {
__removeZeroBalanceTrackedAssets(vaultProxy, _callArgs);
} else {
revert("receiveCallFromComptroller: Invalid _actionId");
}
}
/// @dev Adds assets with a zero balance as tracked assets of the fund
function __addZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs) private {
address[] memory assets = abi.decode(_callArgs, (address[]));
for (uint256 i; i < assets.length; i++) {
require(
__finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0,
"__addZeroBalanceTrackedAssets: Balance is not zero"
);
__addTrackedAsset(msg.sender, assets[i]);
}
}
/// @dev Removes assets with a zero balance from tracked assets of the fund
function __removeZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs)
private
{
address[] memory assets = abi.decode(_callArgs, (address[]));
address denominationAsset = IComptroller(msg.sender).getDenominationAsset();
for (uint256 i; i < assets.length; i++) {
require(
assets[i] != denominationAsset,
"__removeZeroBalanceTrackedAssets: Cannot remove denomination asset"
);
require(
__finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0,
"__removeZeroBalanceTrackedAssets: Balance is not zero"
);
__removeTrackedAsset(msg.sender, assets[i]);
}
}
/////////////////////////
// CALL ON INTEGRATION //
/////////////////////////
/// @notice Universal method for calling third party contract functions through adapters
/// @param _caller The caller of this function via the ComptrollerProxy
/// @param _vaultProxy The VaultProxy of the fund
/// @param _callArgs The encoded args for this function
/// - _adapter Adapter of the integration on which to execute a call
/// - _selector Method selector of the adapter method to execute
/// - _integrationData Encoded arguments specific to the adapter
/// @dev msg.sender is the ComptrollerProxy.
/// Refer to specific adapter to see how to encode its arguments.
function __callOnIntegration(
address _caller,
address _vaultProxy,
bytes memory _callArgs
) private {
(
address adapter,
bytes4 selector,
bytes memory integrationData
) = __decodeCallOnIntegrationArgs(_callArgs);
__preCoIHook(adapter, selector);
/// Passing decoded _callArgs leads to stack-too-deep error
(
address[] memory incomingAssets,
uint256[] memory incomingAssetAmounts,
address[] memory outgoingAssets,
uint256[] memory outgoingAssetAmounts
) = __callOnIntegrationInner(_vaultProxy, _callArgs);
__postCoIHook(
adapter,
selector,
incomingAssets,
incomingAssetAmounts,
outgoingAssets,
outgoingAssetAmounts
);
__emitCoIEvent(
_vaultProxy,
_caller,
adapter,
selector,
integrationData,
incomingAssets,
incomingAssetAmounts,
outgoingAssets,
outgoingAssetAmounts
);
}
/// @dev Helper to execute the bulk of logic of callOnIntegration.
/// Avoids the stack-too-deep-error.
function __callOnIntegrationInner(address vaultProxy, bytes memory _callArgs)
private
returns (
address[] memory incomingAssets_,
uint256[] memory incomingAssetAmounts_,
address[] memory outgoingAssets_,
uint256[] memory outgoingAssetAmounts_
)
{
(
address[] memory expectedIncomingAssets,
uint256[] memory preCallIncomingAssetBalances,
uint256[] memory minIncomingAssetAmounts,
SpendAssetsHandleType spendAssetsHandleType,
address[] memory spendAssets,
uint256[] memory maxSpendAssetAmounts,
uint256[] memory preCallSpendAssetBalances
) = __preProcessCoI(vaultProxy, _callArgs);
__executeCoI(
vaultProxy,
_callArgs,
abi.encode(
spendAssetsHandleType,
spendAssets,
maxSpendAssetAmounts,
expectedIncomingAssets
)
);
(
incomingAssets_,
incomingAssetAmounts_,
outgoingAssets_,
outgoingAssetAmounts_
) = __postProcessCoI(
vaultProxy,
expectedIncomingAssets,
preCallIncomingAssetBalances,
minIncomingAssetAmounts,
spendAssetsHandleType,
spendAssets,
maxSpendAssetAmounts,
preCallSpendAssetBalances
);
return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_);
}
/// @dev Helper to decode CoI args
function __decodeCallOnIntegrationArgs(bytes memory _callArgs)
private
pure
returns (
address adapter_,
bytes4 selector_,
bytes memory integrationData_
)
{
return abi.decode(_callArgs, (address, bytes4, bytes));
}
/// @dev Helper to emit the CallOnIntegrationExecuted event.
/// Avoids stack-too-deep error.
function __emitCoIEvent(
address _vaultProxy,
address _caller,
address _adapter,
bytes4 _selector,
bytes memory _integrationData,
address[] memory _incomingAssets,
uint256[] memory _incomingAssetAmounts,
address[] memory _outgoingAssets,
uint256[] memory _outgoingAssetAmounts
) private {
emit CallOnIntegrationExecutedForFund(
msg.sender,
_vaultProxy,
_caller,
_adapter,
_selector,
_integrationData,
_incomingAssets,
_incomingAssetAmounts,
_outgoingAssets,
_outgoingAssetAmounts
);
}
/// @dev Helper to execute a call to an integration
/// @dev Avoids stack-too-deep error
function __executeCoI(
address _vaultProxy,
bytes memory _callArgs,
bytes memory _encodedAssetTransferArgs
) private {
(
address adapter,
bytes4 selector,
bytes memory integrationData
) = __decodeCallOnIntegrationArgs(_callArgs);
(bool success, bytes memory returnData) = adapter.call(
abi.encodeWithSelector(
selector,
_vaultProxy,
integrationData,
_encodedAssetTransferArgs
)
);
require(success, string(returnData));
}
/// @dev Helper to get the vault's balance of a particular asset
function __getVaultAssetBalance(address _vaultProxy, address _asset)
private
view
returns (uint256)
{
return ERC20(_asset).balanceOf(_vaultProxy);
}
/// @dev Helper to check if an asset is supported
function __isSupportedAsset(address _asset) private view returns (bool isSupported_) {
return
IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_asset) ||
IDerivativePriceFeed(DERIVATIVE_PRICE_FEED).isSupportedAsset(_asset);
}
/// @dev Helper for the actions to take on external contracts prior to executing CoI
function __preCoIHook(address _adapter, bytes4 _selector) private {
IPolicyManager(POLICY_MANAGER).validatePolicies(
msg.sender,
IPolicyManager.PolicyHook.PreCallOnIntegration,
abi.encode(_adapter, _selector)
);
}
/// @dev Helper for the internal actions to take prior to executing CoI
function __preProcessCoI(address _vaultProxy, bytes memory _callArgs)
private
returns (
address[] memory expectedIncomingAssets_,
uint256[] memory preCallIncomingAssetBalances_,
uint256[] memory minIncomingAssetAmounts_,
SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory maxSpendAssetAmounts_,
uint256[] memory preCallSpendAssetBalances_
)
{
(
address adapter,
bytes4 selector,
bytes memory integrationData
) = __decodeCallOnIntegrationArgs(_callArgs);
require(adapterIsRegistered(adapter), "callOnIntegration: Adapter is not registered");
// Note that expected incoming and spend assets are allowed to overlap
// (e.g., a fee for the incomingAsset charged in a spend asset)
(
spendAssetsHandleType_,
spendAssets_,
maxSpendAssetAmounts_,
expectedIncomingAssets_,
minIncomingAssetAmounts_
) = IIntegrationAdapter(adapter).parseAssetsForMethod(selector, integrationData);
require(
spendAssets_.length == maxSpendAssetAmounts_.length,
"__preProcessCoI: Spend assets arrays unequal"
);
require(
expectedIncomingAssets_.length == minIncomingAssetAmounts_.length,
"__preProcessCoI: Incoming assets arrays unequal"
);
require(spendAssets_.isUniqueSet(), "__preProcessCoI: Duplicate spend asset");
require(
expectedIncomingAssets_.isUniqueSet(),
"__preProcessCoI: Duplicate incoming asset"
);
IVault vaultProxyContract = IVault(_vaultProxy);
preCallIncomingAssetBalances_ = new uint256[](expectedIncomingAssets_.length);
for (uint256 i = 0; i < expectedIncomingAssets_.length; i++) {
require(
expectedIncomingAssets_[i] != address(0),
"__preProcessCoI: Empty incoming asset address"
);
require(
minIncomingAssetAmounts_[i] > 0,
"__preProcessCoI: minIncomingAssetAmount must be >0"
);
require(
__isSupportedAsset(expectedIncomingAssets_[i]),
"__preProcessCoI: Non-receivable incoming asset"
);
// Get pre-call balance of each incoming asset.
// If the asset is not tracked by the fund, allow the balance to default to 0.
if (vaultProxyContract.isTrackedAsset(expectedIncomingAssets_[i])) {
// We do not require incoming asset finality, but we attempt to finalize so that
// the final incoming asset amount is more accurate. There is no need to finalize
// post-tx.
preCallIncomingAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance(
_vaultProxy,
expectedIncomingAssets_[i],
false
);
}
}
// Get pre-call balances of spend assets and grant approvals to adapter
preCallSpendAssetBalances_ = new uint256[](spendAssets_.length);
for (uint256 i = 0; i < spendAssets_.length; i++) {
require(spendAssets_[i] != address(0), "__preProcessCoI: Empty spend asset");
require(maxSpendAssetAmounts_[i] > 0, "__preProcessCoI: Empty max spend asset amount");
// A spend asset must either be a tracked asset of the fund or a supported asset,
// in order to prevent seeding the fund with a malicious token and performing arbitrary
// actions within an adapter.
require(
vaultProxyContract.isTrackedAsset(spendAssets_[i]) ||
__isSupportedAsset(spendAssets_[i]),
"__preProcessCoI: Non-spendable spend asset"
);
// If spend asset is also an incoming asset, no need to record its balance
if (!expectedIncomingAssets_.contains(spendAssets_[i])) {
// By requiring spend asset finality before CoI, we will know whether or
// not the asset balance was entirely spent during the call. There is no need
// to finalize post-tx.
preCallSpendAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance(
_vaultProxy,
spendAssets_[i],
true
);
}
// Grant spend assets access to the adapter.
// Note that spendAssets_ is already asserted to a unique set.
if (spendAssetsHandleType_ == SpendAssetsHandleType.Approve) {
// Use exact approve amount rather than increasing allowances,
// because all adapters finish their actions atomically.
__approveAssetSpender(
msg.sender,
spendAssets_[i],
adapter,
maxSpendAssetAmounts_[i]
);
} else if (spendAssetsHandleType_ == SpendAssetsHandleType.Transfer) {
__withdrawAssetTo(msg.sender, spendAssets_[i], adapter, maxSpendAssetAmounts_[i]);
} else if (spendAssetsHandleType_ == SpendAssetsHandleType.Remove) {
__removeTrackedAsset(msg.sender, spendAssets_[i]);
}
}
}
/// @dev Helper for the actions to take on external contracts after executing CoI
function __postCoIHook(
address _adapter,
bytes4 _selector,
address[] memory _incomingAssets,
uint256[] memory _incomingAssetAmounts,
address[] memory _outgoingAssets,
uint256[] memory _outgoingAssetAmounts
) private {
IPolicyManager(POLICY_MANAGER).validatePolicies(
msg.sender,
IPolicyManager.PolicyHook.PostCallOnIntegration,
abi.encode(
_adapter,
_selector,
_incomingAssets,
_incomingAssetAmounts,
_outgoingAssets,
_outgoingAssetAmounts
)
);
}
/// @dev Helper to reconcile and format incoming and outgoing assets after executing CoI
function __postProcessCoI(
address _vaultProxy,
address[] memory _expectedIncomingAssets,
uint256[] memory _preCallIncomingAssetBalances,
uint256[] memory _minIncomingAssetAmounts,
SpendAssetsHandleType _spendAssetsHandleType,
address[] memory _spendAssets,
uint256[] memory _maxSpendAssetAmounts,
uint256[] memory _preCallSpendAssetBalances
)
private
returns (
address[] memory incomingAssets_,
uint256[] memory incomingAssetAmounts_,
address[] memory outgoingAssets_,
uint256[] memory outgoingAssetAmounts_
)
{
address[] memory increasedSpendAssets;
uint256[] memory increasedSpendAssetAmounts;
(
outgoingAssets_,
outgoingAssetAmounts_,
increasedSpendAssets,
increasedSpendAssetAmounts
) = __reconcileCoISpendAssets(
_vaultProxy,
_spendAssetsHandleType,
_spendAssets,
_maxSpendAssetAmounts,
_preCallSpendAssetBalances
);
(incomingAssets_, incomingAssetAmounts_) = __reconcileCoIIncomingAssets(
_vaultProxy,
_expectedIncomingAssets,
_preCallIncomingAssetBalances,
_minIncomingAssetAmounts,
increasedSpendAssets,
increasedSpendAssetAmounts
);
return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_);
}
/// @dev Helper to process incoming asset balance changes.
/// See __reconcileCoISpendAssets() for explanation on "increasedSpendAssets".
function __reconcileCoIIncomingAssets(
address _vaultProxy,
address[] memory _expectedIncomingAssets,
uint256[] memory _preCallIncomingAssetBalances,
uint256[] memory _minIncomingAssetAmounts,
address[] memory _increasedSpendAssets,
uint256[] memory _increasedSpendAssetAmounts
) private returns (address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_) {
// Incoming assets = expected incoming assets + spend assets with increased balances
uint256 incomingAssetsCount = _expectedIncomingAssets.length.add(
_increasedSpendAssets.length
);
// Calculate and validate incoming asset amounts
incomingAssets_ = new address[](incomingAssetsCount);
incomingAssetAmounts_ = new uint256[](incomingAssetsCount);
for (uint256 i = 0; i < _expectedIncomingAssets.length; i++) {
uint256 balanceDiff = __getVaultAssetBalance(_vaultProxy, _expectedIncomingAssets[i])
.sub(_preCallIncomingAssetBalances[i]);
require(
balanceDiff >= _minIncomingAssetAmounts[i],
"__reconcileCoIAssets: Received incoming asset less than expected"
);
// Even if the asset's previous balance was >0, it might not have been tracked
__addTrackedAsset(msg.sender, _expectedIncomingAssets[i]);
incomingAssets_[i] = _expectedIncomingAssets[i];
incomingAssetAmounts_[i] = balanceDiff;
}
// Append increaseSpendAssets to incomingAsset vars
if (_increasedSpendAssets.length > 0) {
uint256 incomingAssetIndex = _expectedIncomingAssets.length;
for (uint256 i = 0; i < _increasedSpendAssets.length; i++) {
incomingAssets_[incomingAssetIndex] = _increasedSpendAssets[i];
incomingAssetAmounts_[incomingAssetIndex] = _increasedSpendAssetAmounts[i];
incomingAssetIndex++;
}
}
return (incomingAssets_, incomingAssetAmounts_);
}
/// @dev Helper to process spend asset balance changes.
/// "outgoingAssets" are the spend assets with a decrease in balance.
/// "increasedSpendAssets" are the spend assets with an unexpected increase in balance.
/// For example, "increasedSpendAssets" can occur if an adapter has a pre-balance of
/// the spendAsset, which would be transferred to the fund at the end of the tx.
function __reconcileCoISpendAssets(
address _vaultProxy,
SpendAssetsHandleType _spendAssetsHandleType,
address[] memory _spendAssets,
uint256[] memory _maxSpendAssetAmounts,
uint256[] memory _preCallSpendAssetBalances
)
private
returns (
address[] memory outgoingAssets_,
uint256[] memory outgoingAssetAmounts_,
address[] memory increasedSpendAssets_,
uint256[] memory increasedSpendAssetAmounts_
)
{
// Determine spend asset balance changes
uint256[] memory postCallSpendAssetBalances = new uint256[](_spendAssets.length);
uint256 outgoingAssetsCount;
uint256 increasedSpendAssetsCount;
for (uint256 i = 0; i < _spendAssets.length; i++) {
// If spend asset's initial balance is 0, then it is an incoming asset
if (_preCallSpendAssetBalances[i] == 0) {
continue;
}
// Handle SpendAssetsHandleType.Remove separately
if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) {
outgoingAssetsCount++;
continue;
}
// Determine if the asset is outgoing or incoming, and store the post-balance for later use
postCallSpendAssetBalances[i] = __getVaultAssetBalance(_vaultProxy, _spendAssets[i]);
// If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing
if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) {
outgoingAssetsCount++;
} else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) {
increasedSpendAssetsCount++;
}
}
// Format outgoingAssets and increasedSpendAssets (spend assets with unexpected increase in balance)
outgoingAssets_ = new address[](outgoingAssetsCount);
outgoingAssetAmounts_ = new uint256[](outgoingAssetsCount);
increasedSpendAssets_ = new address[](increasedSpendAssetsCount);
increasedSpendAssetAmounts_ = new uint256[](increasedSpendAssetsCount);
uint256 outgoingAssetsIndex;
uint256 increasedSpendAssetsIndex;
for (uint256 i = 0; i < _spendAssets.length; i++) {
// If spend asset's initial balance is 0, then it is an incoming asset.
if (_preCallSpendAssetBalances[i] == 0) {
continue;
}
// Handle SpendAssetsHandleType.Remove separately.
// No need to validate the max spend asset amount.
if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) {
outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i];
outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i];
outgoingAssetsIndex++;
continue;
}
// If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing
if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) {
if (postCallSpendAssetBalances[i] == 0) {
__removeTrackedAsset(msg.sender, _spendAssets[i]);
outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i];
} else {
outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i].sub(
postCallSpendAssetBalances[i]
);
}
require(
outgoingAssetAmounts_[outgoingAssetsIndex] <= _maxSpendAssetAmounts[i],
"__reconcileCoISpendAssets: Spent amount greater than expected"
);
outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i];
outgoingAssetsIndex++;
} else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) {
increasedSpendAssetAmounts_[increasedSpendAssetsIndex] = postCallSpendAssetBalances[i]
.sub(_preCallSpendAssetBalances[i]);
increasedSpendAssets_[increasedSpendAssetsIndex] = _spendAssets[i];
increasedSpendAssetsIndex++;
}
}
return (
outgoingAssets_,
outgoingAssetAmounts_,
increasedSpendAssets_,
increasedSpendAssetAmounts_
);
}
///////////////////////////
// INTEGRATIONS REGISTRY //
///////////////////////////
/// @notice Remove integration adapters from the list of registered adapters
/// @param _adapters Addresses of adapters to be deregistered
function deregisterAdapters(address[] calldata _adapters) external onlyFundDeployerOwner {
require(_adapters.length > 0, "deregisterAdapters: _adapters cannot be empty");
for (uint256 i; i < _adapters.length; i++) {
require(
adapterIsRegistered(_adapters[i]),
"deregisterAdapters: Adapter is not registered"
);
registeredAdapters.remove(_adapters[i]);
emit AdapterDeregistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier());
}
}
/// @notice Add integration adapters to the list of registered adapters
/// @param _adapters Addresses of adapters to be registered
function registerAdapters(address[] calldata _adapters) external onlyFundDeployerOwner {
require(_adapters.length > 0, "registerAdapters: _adapters cannot be empty");
for (uint256 i; i < _adapters.length; i++) {
require(_adapters[i] != address(0), "registerAdapters: Adapter cannot be empty");
require(
!adapterIsRegistered(_adapters[i]),
"registerAdapters: Adapter already registered"
);
registeredAdapters.add(_adapters[i]);
emit AdapterRegistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier());
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Checks if an integration adapter is registered
/// @param _adapter The adapter to check
/// @return isRegistered_ True if the adapter is registered
function adapterIsRegistered(address _adapter) public view returns (bool isRegistered_) {
return registeredAdapters.contains(_adapter);
}
/// @notice Gets the `DERIVATIVE_PRICE_FEED` variable
/// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value
function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) {
return DERIVATIVE_PRICE_FEED;
}
/// @notice Gets the `POLICY_MANAGER` variable
/// @return policyManager_ The `POLICY_MANAGER` variable value
function getPolicyManager() external view returns (address policyManager_) {
return POLICY_MANAGER;
}
/// @notice Gets the `PRIMITIVE_PRICE_FEED` variable
/// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value
function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) {
return PRIMITIVE_PRICE_FEED;
}
/// @notice Gets all registered integration adapters
/// @return registeredAdaptersArray_ A list of all registered integration adapters
function getRegisteredAdapters()
external
view
returns (address[] memory registeredAdaptersArray_)
{
registeredAdaptersArray_ = new address[](registeredAdapters.length());
for (uint256 i = 0; i < registeredAdaptersArray_.length; i++) {
registeredAdaptersArray_[i] = registeredAdapters.at(i);
}
return registeredAdaptersArray_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol";
import "../../../../interfaces/ISynthetix.sol";
import "../utils/AdapterBase.sol";
/// @title SynthetixAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for interacting with Synthetix
contract SynthetixAdapter is AdapterBase {
address private immutable ORIGINATOR;
address private immutable SYNTHETIX;
address private immutable SYNTHETIX_PRICE_FEED;
bytes32 private immutable TRACKING_CODE;
constructor(
address _integrationManager,
address _synthetixPriceFeed,
address _originator,
address _synthetix,
bytes32 _trackingCode
) public AdapterBase(_integrationManager) {
ORIGINATOR = _originator;
SYNTHETIX = _synthetix;
SYNTHETIX_PRICE_FEED = _synthetixPriceFeed;
TRACKING_CODE = _trackingCode;
}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "SYNTHETIX";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid");
(
address incomingAsset,
uint256 minIncomingAssetAmount,
address outgoingAsset,
uint256 outgoingAssetAmount
) = __decodeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = outgoingAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = incomingAsset;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
return (
IIntegrationManager.SpendAssetsHandleType.None,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Trades assets on Synthetix
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
function takeOrder(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata
) external onlyIntegrationManager {
(
address incomingAsset,
,
address outgoingAsset,
uint256 outgoingAssetAmount
) = __decodeCallArgs(_encodedCallArgs);
address[] memory synths = new address[](2);
synths[0] = outgoingAsset;
synths[1] = incomingAsset;
bytes32[] memory currencyKeys = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED)
.getCurrencyKeysForSynths(synths);
ISynthetix(SYNTHETIX).exchangeOnBehalfWithTracking(
_vaultProxy,
currencyKeys[0],
outgoingAssetAmount,
currencyKeys[1],
ORIGINATOR,
TRACKING_CODE
);
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the encoded call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address incomingAsset_,
uint256 minIncomingAssetAmount_,
address outgoingAsset_,
uint256 outgoingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (address, uint256, address, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `ORIGINATOR` variable
/// @return originator_ The `ORIGINATOR` variable value
function getOriginator() external view returns (address originator_) {
return ORIGINATOR;
}
/// @notice Gets the `SYNTHETIX` variable
/// @return synthetix_ The `SYNTHETIX` variable value
function getSynthetix() external view returns (address synthetix_) {
return SYNTHETIX;
}
/// @notice Gets the `SYNTHETIX_PRICE_FEED` variable
/// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value
function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) {
return SYNTHETIX_PRICE_FEED;
}
/// @notice Gets the `TRACKING_CODE` variable
/// @return trackingCode_ The `TRACKING_CODE` variable value
function getTrackingCode() external view returns (bytes32 trackingCode_) {
return TRACKING_CODE;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../interfaces/IChainlinkAggregator.sol";
import "../../utils/DispatcherOwnerMixin.sol";
import "./IPrimitivePriceFeed.sol";
/// @title ChainlinkPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice A price feed that uses Chainlink oracles as price sources
contract ChainlinkPriceFeed is IPrimitivePriceFeed, DispatcherOwnerMixin {
using SafeMath for uint256;
event EthUsdAggregatorSet(address prevEthUsdAggregator, address nextEthUsdAggregator);
event PrimitiveAdded(
address indexed primitive,
address aggregator,
RateAsset rateAsset,
uint256 unit
);
event PrimitiveRemoved(address indexed primitive);
event PrimitiveUpdated(
address indexed primitive,
address prevAggregator,
address nextAggregator
);
event StalePrimitiveRemoved(address indexed primitive);
event StaleRateThresholdSet(uint256 prevStaleRateThreshold, uint256 nextStaleRateThreshold);
enum RateAsset {ETH, USD}
struct AggregatorInfo {
address aggregator;
RateAsset rateAsset;
}
uint256 private constant ETH_UNIT = 10**18;
address private immutable WETH_TOKEN;
address private ethUsdAggregator;
uint256 private staleRateThreshold;
mapping(address => AggregatorInfo) private primitiveToAggregatorInfo;
mapping(address => uint256) private primitiveToUnit;
constructor(
address _dispatcher,
address _wethToken,
address _ethUsdAggregator,
address[] memory _primitives,
address[] memory _aggregators,
RateAsset[] memory _rateAssets
) public DispatcherOwnerMixin(_dispatcher) {
WETH_TOKEN = _wethToken;
staleRateThreshold = 25 hours; // 24 hour heartbeat + 1hr buffer
__setEthUsdAggregator(_ethUsdAggregator);
if (_primitives.length > 0) {
__addPrimitives(_primitives, _aggregators, _rateAssets);
}
}
// EXTERNAL FUNCTIONS
/// @notice Calculates the value of a base asset in terms of a quote asset (using a canonical rate)
/// @param _baseAsset The base asset
/// @param _baseAssetAmount The base asset amount to convert
/// @param _quoteAsset The quote asset
/// @return quoteAssetAmount_ The equivalent quote asset amount
/// @return isValid_ True if the rates used in calculations are deemed valid
function calcCanonicalValue(
address _baseAsset,
uint256 _baseAssetAmount,
address _quoteAsset
) public view override returns (uint256 quoteAssetAmount_, bool isValid_) {
// Case where _baseAsset == _quoteAsset is handled by ValueInterpreter
int256 baseAssetRate = __getLatestRateData(_baseAsset);
if (baseAssetRate <= 0) {
return (0, false);
}
int256 quoteAssetRate = __getLatestRateData(_quoteAsset);
if (quoteAssetRate <= 0) {
return (0, false);
}
(quoteAssetAmount_, isValid_) = __calcConversionAmount(
_baseAsset,
_baseAssetAmount,
uint256(baseAssetRate),
_quoteAsset,
uint256(quoteAssetRate)
);
return (quoteAssetAmount_, isValid_);
}
/// @notice Calculates the value of a base asset in terms of a quote asset (using a live rate)
/// @param _baseAsset The base asset
/// @param _baseAssetAmount The base asset amount to convert
/// @param _quoteAsset The quote asset
/// @return quoteAssetAmount_ The equivalent quote asset amount
/// @return isValid_ True if the rates used in calculations are deemed valid
/// @dev Live and canonical values are the same for Chainlink
function calcLiveValue(
address _baseAsset,
uint256 _baseAssetAmount,
address _quoteAsset
) external view override returns (uint256 quoteAssetAmount_, bool isValid_) {
return calcCanonicalValue(_baseAsset, _baseAssetAmount, _quoteAsset);
}
/// @notice Checks whether an asset is a supported primitive of the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is a supported primitive
function isSupportedAsset(address _asset) external view override returns (bool isSupported_) {
return _asset == WETH_TOKEN || primitiveToAggregatorInfo[_asset].aggregator != address(0);
}
/// @notice Sets the `ehUsdAggregator` variable value
/// @param _nextEthUsdAggregator The `ehUsdAggregator` value to set
function setEthUsdAggregator(address _nextEthUsdAggregator) external onlyDispatcherOwner {
__setEthUsdAggregator(_nextEthUsdAggregator);
}
// PRIVATE FUNCTIONS
/// @dev Helper to convert an amount from a _baseAsset to a _quoteAsset
function __calcConversionAmount(
address _baseAsset,
uint256 _baseAssetAmount,
uint256 _baseAssetRate,
address _quoteAsset,
uint256 _quoteAssetRate
) private view returns (uint256 quoteAssetAmount_, bool isValid_) {
RateAsset baseAssetRateAsset = getRateAssetForPrimitive(_baseAsset);
RateAsset quoteAssetRateAsset = getRateAssetForPrimitive(_quoteAsset);
uint256 baseAssetUnit = getUnitForPrimitive(_baseAsset);
uint256 quoteAssetUnit = getUnitForPrimitive(_quoteAsset);
// If rates are both in ETH or both in USD
if (baseAssetRateAsset == quoteAssetRateAsset) {
return (
__calcConversionAmountSameRateAsset(
_baseAssetAmount,
baseAssetUnit,
_baseAssetRate,
quoteAssetUnit,
_quoteAssetRate
),
true
);
}
int256 ethPerUsdRate = IChainlinkAggregator(ethUsdAggregator).latestAnswer();
if (ethPerUsdRate <= 0) {
return (0, false);
}
// If _baseAsset's rate is in ETH and _quoteAsset's rate is in USD
if (baseAssetRateAsset == RateAsset.ETH) {
return (
__calcConversionAmountEthRateAssetToUsdRateAsset(
_baseAssetAmount,
baseAssetUnit,
_baseAssetRate,
quoteAssetUnit,
_quoteAssetRate,
uint256(ethPerUsdRate)
),
true
);
}
// If _baseAsset's rate is in USD and _quoteAsset's rate is in ETH
return (
__calcConversionAmountUsdRateAssetToEthRateAsset(
_baseAssetAmount,
baseAssetUnit,
_baseAssetRate,
quoteAssetUnit,
_quoteAssetRate,
uint256(ethPerUsdRate)
),
true
);
}
/// @dev Helper to convert amounts where the base asset has an ETH rate and the quote asset has a USD rate
function __calcConversionAmountEthRateAssetToUsdRateAsset(
uint256 _baseAssetAmount,
uint256 _baseAssetUnit,
uint256 _baseAssetRate,
uint256 _quoteAssetUnit,
uint256 _quoteAssetRate,
uint256 _ethPerUsdRate
) private pure returns (uint256 quoteAssetAmount_) {
// Only allows two consecutive multiplication operations to avoid potential overflow.
// Intermediate step needed to resolve stack-too-deep error.
uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_ethPerUsdRate).div(
ETH_UNIT
);
return intermediateStep.mul(_quoteAssetUnit).div(_baseAssetUnit).div(_quoteAssetRate);
}
/// @dev Helper to convert amounts where base and quote assets both have ETH rates or both have USD rates
function __calcConversionAmountSameRateAsset(
uint256 _baseAssetAmount,
uint256 _baseAssetUnit,
uint256 _baseAssetRate,
uint256 _quoteAssetUnit,
uint256 _quoteAssetRate
) private pure returns (uint256 quoteAssetAmount_) {
// Only allows two consecutive multiplication operations to avoid potential overflow
return
_baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div(
_baseAssetUnit.mul(_quoteAssetRate)
);
}
/// @dev Helper to convert amounts where the base asset has a USD rate and the quote asset has an ETH rate
function __calcConversionAmountUsdRateAssetToEthRateAsset(
uint256 _baseAssetAmount,
uint256 _baseAssetUnit,
uint256 _baseAssetRate,
uint256 _quoteAssetUnit,
uint256 _quoteAssetRate,
uint256 _ethPerUsdRate
) private pure returns (uint256 quoteAssetAmount_) {
// Only allows two consecutive multiplication operations to avoid potential overflow
// Intermediate step needed to resolve stack-too-deep error.
uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div(
_ethPerUsdRate
);
return intermediateStep.mul(ETH_UNIT).div(_baseAssetUnit).div(_quoteAssetRate);
}
/// @dev Helper to get the latest rate for a given primitive
function __getLatestRateData(address _primitive) private view returns (int256 rate_) {
if (_primitive == WETH_TOKEN) {
return int256(ETH_UNIT);
}
address aggregator = primitiveToAggregatorInfo[_primitive].aggregator;
require(aggregator != address(0), "__getLatestRateData: Primitive does not exist");
return IChainlinkAggregator(aggregator).latestAnswer();
}
/// @dev Helper to set the `ethUsdAggregator` value
function __setEthUsdAggregator(address _nextEthUsdAggregator) private {
address prevEthUsdAggregator = ethUsdAggregator;
require(
_nextEthUsdAggregator != prevEthUsdAggregator,
"__setEthUsdAggregator: Value already set"
);
__validateAggregator(_nextEthUsdAggregator);
ethUsdAggregator = _nextEthUsdAggregator;
emit EthUsdAggregatorSet(prevEthUsdAggregator, _nextEthUsdAggregator);
}
/////////////////////////
// PRIMITIVES REGISTRY //
/////////////////////////
/// @notice Adds a list of primitives with the given aggregator and rateAsset values
/// @param _primitives The primitives to add
/// @param _aggregators The ordered aggregators corresponding to the list of _primitives
/// @param _rateAssets The ordered rate assets corresponding to the list of _primitives
function addPrimitives(
address[] calldata _primitives,
address[] calldata _aggregators,
RateAsset[] calldata _rateAssets
) external onlyDispatcherOwner {
require(_primitives.length > 0, "addPrimitives: _primitives cannot be empty");
__addPrimitives(_primitives, _aggregators, _rateAssets);
}
/// @notice Removes a list of primitives from the feed
/// @param _primitives The primitives to remove
function removePrimitives(address[] calldata _primitives) external onlyDispatcherOwner {
require(_primitives.length > 0, "removePrimitives: _primitives cannot be empty");
for (uint256 i; i < _primitives.length; i++) {
require(
primitiveToAggregatorInfo[_primitives[i]].aggregator != address(0),
"removePrimitives: Primitive not yet added"
);
delete primitiveToAggregatorInfo[_primitives[i]];
delete primitiveToUnit[_primitives[i]];
emit PrimitiveRemoved(_primitives[i]);
}
}
/// @notice Removes stale primitives from the feed
/// @param _primitives The stale primitives to remove
/// @dev Callable by anybody
function removeStalePrimitives(address[] calldata _primitives) external {
require(_primitives.length > 0, "removeStalePrimitives: _primitives cannot be empty");
for (uint256 i; i < _primitives.length; i++) {
address aggregatorAddress = primitiveToAggregatorInfo[_primitives[i]].aggregator;
require(aggregatorAddress != address(0), "removeStalePrimitives: Invalid primitive");
require(rateIsStale(aggregatorAddress), "removeStalePrimitives: Rate is not stale");
delete primitiveToAggregatorInfo[_primitives[i]];
delete primitiveToUnit[_primitives[i]];
emit StalePrimitiveRemoved(_primitives[i]);
}
}
/// @notice Sets the `staleRateThreshold` variable
/// @param _nextStaleRateThreshold The next `staleRateThreshold` value
function setStaleRateThreshold(uint256 _nextStaleRateThreshold) external onlyDispatcherOwner {
uint256 prevStaleRateThreshold = staleRateThreshold;
require(
_nextStaleRateThreshold != prevStaleRateThreshold,
"__setStaleRateThreshold: Value already set"
);
staleRateThreshold = _nextStaleRateThreshold;
emit StaleRateThresholdSet(prevStaleRateThreshold, _nextStaleRateThreshold);
}
/// @notice Updates the aggregators for given primitives
/// @param _primitives The primitives to update
/// @param _aggregators The ordered aggregators corresponding to the list of _primitives
function updatePrimitives(address[] calldata _primitives, address[] calldata _aggregators)
external
onlyDispatcherOwner
{
require(_primitives.length > 0, "updatePrimitives: _primitives cannot be empty");
require(
_primitives.length == _aggregators.length,
"updatePrimitives: Unequal _primitives and _aggregators array lengths"
);
for (uint256 i; i < _primitives.length; i++) {
address prevAggregator = primitiveToAggregatorInfo[_primitives[i]].aggregator;
require(prevAggregator != address(0), "updatePrimitives: Primitive not yet added");
require(_aggregators[i] != prevAggregator, "updatePrimitives: Value already set");
__validateAggregator(_aggregators[i]);
primitiveToAggregatorInfo[_primitives[i]].aggregator = _aggregators[i];
emit PrimitiveUpdated(_primitives[i], prevAggregator, _aggregators[i]);
}
}
/// @notice Checks whether the current rate is considered stale for the specified aggregator
/// @param _aggregator The Chainlink aggregator of which to check staleness
/// @return rateIsStale_ True if the rate is considered stale
function rateIsStale(address _aggregator) public view returns (bool rateIsStale_) {
return
IChainlinkAggregator(_aggregator).latestTimestamp() <
block.timestamp.sub(staleRateThreshold);
}
/// @dev Helper to add primitives to the feed
function __addPrimitives(
address[] memory _primitives,
address[] memory _aggregators,
RateAsset[] memory _rateAssets
) private {
require(
_primitives.length == _aggregators.length,
"__addPrimitives: Unequal _primitives and _aggregators array lengths"
);
require(
_primitives.length == _rateAssets.length,
"__addPrimitives: Unequal _primitives and _rateAssets array lengths"
);
for (uint256 i = 0; i < _primitives.length; i++) {
require(
primitiveToAggregatorInfo[_primitives[i]].aggregator == address(0),
"__addPrimitives: Value already set"
);
__validateAggregator(_aggregators[i]);
primitiveToAggregatorInfo[_primitives[i]] = AggregatorInfo({
aggregator: _aggregators[i],
rateAsset: _rateAssets[i]
});
// Store the amount that makes up 1 unit given the asset's decimals
uint256 unit = 10**uint256(ERC20(_primitives[i]).decimals());
primitiveToUnit[_primitives[i]] = unit;
emit PrimitiveAdded(_primitives[i], _aggregators[i], _rateAssets[i], unit);
}
}
/// @dev Helper to validate an aggregator by checking its return values for the expected interface
function __validateAggregator(address _aggregator) private view {
require(_aggregator != address(0), "__validateAggregator: Empty _aggregator");
require(
IChainlinkAggregator(_aggregator).latestAnswer() > 0,
"__validateAggregator: No rate detected"
);
require(!rateIsStale(_aggregator), "__validateAggregator: Stale rate detected");
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the aggregatorInfo variable value for a primitive
/// @param _primitive The primitive asset for which to get the aggregatorInfo value
/// @return aggregatorInfo_ The aggregatorInfo value
function getAggregatorInfoForPrimitive(address _primitive)
external
view
returns (AggregatorInfo memory aggregatorInfo_)
{
return primitiveToAggregatorInfo[_primitive];
}
/// @notice Gets the `ethUsdAggregator` variable value
/// @return ethUsdAggregator_ The `ethUsdAggregator` variable value
function getEthUsdAggregator() external view returns (address ethUsdAggregator_) {
return ethUsdAggregator;
}
/// @notice Gets the `staleRateThreshold` variable value
/// @return staleRateThreshold_ The `staleRateThreshold` variable value
function getStaleRateThreshold() external view returns (uint256 staleRateThreshold_) {
return staleRateThreshold;
}
/// @notice Gets the `WETH_TOKEN` variable value
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
/// @notice Gets the rateAsset variable value for a primitive
/// @return rateAsset_ The rateAsset variable value
/// @dev This isn't strictly necessary as WETH_TOKEN will be undefined and thus
/// the RateAsset will be the 0-position of the enum (i.e. ETH), but it makes the
/// behavior more explicit
function getRateAssetForPrimitive(address _primitive)
public
view
returns (RateAsset rateAsset_)
{
if (_primitive == WETH_TOKEN) {
return RateAsset.ETH;
}
return primitiveToAggregatorInfo[_primitive].rateAsset;
}
/// @notice Gets the unit variable value for a primitive
/// @return unit_ The unit variable value
function getUnitForPrimitive(address _primitive) public view returns (uint256 unit_) {
if (_primitive == WETH_TOKEN) {
return ETH_UNIT;
}
return primitiveToUnit[_primitive];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../release/infrastructure/value-interpreter/IValueInterpreter.sol";
import "../../release/infrastructure/price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol";
import "../../release/infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol";
/// @dev This contract acts as a centralized rate provider for mocks.
/// Suited for a dev environment, it doesn't take into account gas costs.
contract CentralizedRateProvider is Ownable {
using SafeMath for uint256;
address private immutable WETH;
uint256 private maxDeviationPerSender;
// Addresses are not immutable to facilitate lazy load (they're are not accessible at the mock env).
address private valueInterpreter;
address private aggregateDerivativePriceFeed;
address private primitivePriceFeed;
constructor(address _weth, uint256 _maxDeviationPerSender) public {
maxDeviationPerSender = _maxDeviationPerSender;
WETH = _weth;
}
/// @dev Calculates the value of a _baseAsset relative to a _quoteAsset.
/// Label to ValueInterprete's calcLiveAssetValue
function calcLiveAssetValue(
address _baseAsset,
uint256 _amount,
address _quoteAsset
) public returns (uint256 value_) {
uint256 baseDecimalsRate = 10**uint256(ERC20(_baseAsset).decimals());
uint256 quoteDecimalsRate = 10**uint256(ERC20(_quoteAsset).decimals());
// 1. Check if quote asset is a primitive. If it is, use ValueInterpreter normally.
if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_quoteAsset)) {
(value_, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue(
_baseAsset,
_amount,
_quoteAsset
);
return value_;
}
// 2. Otherwise, check if base asset is a primitive, and use inverse rate from Value Interpreter.
if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_baseAsset)) {
(uint256 inverseRate, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue(
_quoteAsset,
10**uint256(ERC20(_quoteAsset).decimals()),
_baseAsset
);
uint256 rate = uint256(baseDecimalsRate).mul(quoteDecimalsRate).div(inverseRate);
value_ = _amount.mul(rate).div(baseDecimalsRate);
return value_;
}
// 3. If both assets are derivatives, calculate the rate against ETH.
(uint256 baseToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue(
_baseAsset,
baseDecimalsRate,
WETH
);
(uint256 quoteToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue(
_quoteAsset,
quoteDecimalsRate,
WETH
);
value_ = _amount.mul(baseToWeth).mul(quoteDecimalsRate).div(quoteToWeth).div(
baseDecimalsRate
);
return value_;
}
/// @dev Calculates a randomized live value of an asset
/// Aggregation of two randomization seeds: msg.sender, and by block.number.
function calcLiveAssetValueRandomized(
address _baseAsset,
uint256 _amount,
address _quoteAsset,
uint256 _maxDeviationPerBlock
) external returns (uint256 value_) {
uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset);
// Range [liveAssetValue * (1 - _blockNumberDeviation), liveAssetValue * (1 + _blockNumberDeviation)]
uint256 senderRandomizedValue_ = __calcValueRandomizedByAddress(
liveAssetValue,
msg.sender,
maxDeviationPerSender
);
// Range [liveAssetValue * (1 - _maxDeviationPerBlock - maxDeviationPerSender), liveAssetValue * (1 + _maxDeviationPerBlock + maxDeviationPerSender)]
value_ = __calcValueRandomizedByUint(
senderRandomizedValue_,
block.number,
_maxDeviationPerBlock
);
return value_;
}
/// @dev Calculates the live value of an asset including a grade of pseudo randomization, using msg.sender as the source of randomness
function calcLiveAssetValueRandomizedByBlockNumber(
address _baseAsset,
uint256 _amount,
address _quoteAsset,
uint256 _maxDeviationPerBlock
) external returns (uint256 value_) {
uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset);
value_ = __calcValueRandomizedByUint(liveAssetValue, block.number, _maxDeviationPerBlock);
return value_;
}
/// @dev Calculates the live value of an asset including a grade of pseudo-randomization, using `block.number` as the source of randomness
function calcLiveAssetValueRandomizedBySender(
address _baseAsset,
uint256 _amount,
address _quoteAsset
) external returns (uint256 value_) {
uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset);
value_ = __calcValueRandomizedByAddress(liveAssetValue, msg.sender, maxDeviationPerSender);
return value_;
}
function setMaxDeviationPerSender(uint256 _maxDeviationPerSender) external onlyOwner {
maxDeviationPerSender = _maxDeviationPerSender;
}
/// @dev Connector from release environment, inject price variables into the provider.
function setReleasePriceAddresses(
address _valueInterpreter,
address _aggregateDerivativePriceFeed,
address _primitivePriceFeed
) external onlyOwner {
valueInterpreter = _valueInterpreter;
aggregateDerivativePriceFeed = _aggregateDerivativePriceFeed;
primitivePriceFeed = _primitivePriceFeed;
}
// PRIVATE FUNCTIONS
/// @dev Calculates a a pseudo-randomized value as a seed an address
function __calcValueRandomizedByAddress(
uint256 _meanValue,
address _seed,
uint256 _maxDeviation
) private pure returns (uint256 value_) {
// Value between [0, 100]
uint256 senderRandomFactor = uint256(uint8(_seed))
.mul(100)
.div(256)
.mul(_maxDeviation)
.div(100);
value_ = __calcDeviatedValue(_meanValue, senderRandomFactor, _maxDeviation);
return value_;
}
/// @dev Calculates a a pseudo-randomized value as a seed an uint256
function __calcValueRandomizedByUint(
uint256 _meanValue,
uint256 _seed,
uint256 _maxDeviation
) private pure returns (uint256 value_) {
// Depending on the _seed number, it will be one of {20, 40, 60, 80, 100}
uint256 randomFactor = (_seed.mod(2).mul(20))
.add((_seed.mod(3).mul(40)))
.mul(_maxDeviation)
.div(100);
value_ = __calcDeviatedValue(_meanValue, randomFactor, _maxDeviation);
return value_;
}
/// @dev Given a mean value and a max deviation, returns a value in the spectrum between 0 (_meanValue - maxDeviation) and 100 (_mean + maxDeviation)
/// TODO: Refactor to use 18 decimal precision
function __calcDeviatedValue(
uint256 _meanValue,
uint256 _offset,
uint256 _maxDeviation
) private pure returns (uint256 value_) {
return
_meanValue.add((_meanValue.mul((uint256(2)).mul(_offset)).div(uint256(100)))).sub(
_meanValue.mul(_maxDeviation).div(uint256(100))
);
}
///////////////////
// STATE GETTERS //
///////////////////
function getMaxDeviationPerSender() public view returns (uint256 maxDeviationPerSender_) {
return maxDeviationPerSender;
}
function getValueInterpreter() public view returns (address valueInterpreter_) {
return valueInterpreter;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../release/interfaces/IUniswapV2Pair.sol";
import "../prices/CentralizedRateProvider.sol";
import "../tokens/MockToken.sol";
/// @dev This price source mocks the integration with Uniswap Pair
/// Docs of Uniswap Pair implementation: <https://uniswap.org/docs/v2/smart-contracts/pair/>
contract MockUniswapV2PriceSource is MockToken("Uniswap V2", "UNI-V2", 18) {
using SafeMath for uint256;
address private immutable TOKEN_0;
address private immutable TOKEN_1;
address private immutable CENTRALIZED_RATE_PROVIDER;
constructor(
address _centralizedRateProvider,
address _token0,
address _token1
) public {
CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider;
TOKEN_0 = _token0;
TOKEN_1 = _token1;
}
/// @dev returns reserves for each token on the Uniswap Pair
/// Reserves will be used to calculate the pair price
/// Inherited from IUniswapV2Pair
function getReserves()
external
returns (
uint112 reserve0_,
uint112 reserve1_,
uint32 blockTimestampLast_
)
{
uint256 baseAmount = ERC20(TOKEN_0).balanceOf(address(this));
reserve0_ = uint112(baseAmount);
reserve1_ = uint112(
CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue(
TOKEN_0,
baseAmount,
TOKEN_1
)
);
return (reserve0_, reserve1_, blockTimestampLast_);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @dev Inherited from IUniswapV2Pair
function token0() public view returns (address) {
return TOKEN_0;
}
/// @dev Inherited from IUniswapV2Pair
function token1() public view returns (address) {
return TOKEN_1;
}
/// @dev Inherited from IUniswapV2Pair
function kLast() public pure returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract MockToken is ERC20Burnable, Ownable {
using SafeMath for uint256;
mapping(address => bool) private addressToIsMinter;
modifier onlyMinter() {
require(
addressToIsMinter[msg.sender] || owner() == msg.sender,
"msg.sender is not owner or minter"
);
_;
}
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) public ERC20(_name, _symbol) {
_setupDecimals(_decimals);
_mint(msg.sender, uint256(100000000).mul(10**uint256(_decimals)));
}
function mintFor(address _who, uint256 _amount) external onlyMinter {
_mint(_who, _amount);
}
function mint(uint256 _amount) external onlyMinter {
_mint(msg.sender, _amount);
}
function addMinters(address[] memory _minters) public onlyOwner {
for (uint256 i = 0; i < _minters.length; i++) {
addressToIsMinter[_minters[i]] = true;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./ERC20.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
using SafeMath for uint256;
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../release/core/fund/comptroller/ComptrollerLib.sol";
import "./MockToken.sol";
/// @title MockReentrancyToken Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mock ERC20 token implementation that is able to re-entrance redeemShares and buyShares functions
contract MockReentrancyToken is MockToken("Mock Reentrancy Token", "MRT", 18) {
bool public bad;
address public comptrollerProxy;
function makeItReentracyToken(address _comptrollerProxy) external {
bad = true;
comptrollerProxy = _comptrollerProxy;
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
if (bad) {
ComptrollerLib(comptrollerProxy).redeemShares();
} else {
_transfer(_msgSender(), recipient, amount);
}
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
if (bad) {
ComptrollerLib(comptrollerProxy).buyShares(
new address[](0),
new uint256[](0),
new uint256[](0)
);
} else {
_transfer(sender, recipient, amount);
}
return true;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./../../release/interfaces/ISynthetixProxyERC20.sol";
import "./../../release/interfaces/ISynthetixSynth.sol";
import "./MockToken.sol";
contract MockSynthetixToken is ISynthetixProxyERC20, ISynthetixSynth, MockToken {
using SafeMath for uint256;
bytes32 public override currencyKey;
uint256 public constant WAITING_PERIOD_SECS = 3 * 60;
mapping(address => uint256) public timelockByAccount;
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
bytes32 _currencyKey
) public MockToken(_name, _symbol, _decimals) {
currencyKey = _currencyKey;
}
function setCurrencyKey(bytes32 _currencyKey) external onlyOwner {
currencyKey = _currencyKey;
}
function _isLocked(address account) internal view returns (bool) {
return timelockByAccount[account] >= now;
}
function _beforeTokenTransfer(
address from,
address,
uint256
) internal override {
require(!_isLocked(from), "Cannot settle during waiting period");
}
function target() external view override returns (address) {
return address(this);
}
function isLocked(address account) external view returns (bool) {
return _isLocked(account);
}
function burnFrom(address account, uint256 amount) public override {
_burn(account, amount);
}
function lock(address account) public {
timelockByAccount[account] = now.add(WAITING_PERIOD_SECS);
}
function unlock(address account) public {
timelockByAccount[account] = 0;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/IUniswapV2Factory.sol";
import "../../../../interfaces/IUniswapV2Router2.sol";
import "../utils/AdapterBase.sol";
/// @title UniswapV2Adapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for interacting with Uniswap v2
contract UniswapV2Adapter is AdapterBase {
using SafeMath for uint256;
address private immutable FACTORY;
address private immutable ROUTER;
constructor(
address _integrationManager,
address _router,
address _factory
) public AdapterBase(_integrationManager) {
FACTORY = _factory;
ROUTER = _router;
}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "UNISWAP_V2";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == LEND_SELECTOR) {
(
address[2] memory outgoingAssets,
uint256[2] memory maxOutgoingAssetAmounts,
,
uint256 minIncomingAssetAmount
) = __decodeLendCallArgs(_encodedCallArgs);
spendAssets_ = new address[](2);
spendAssets_[0] = outgoingAssets[0];
spendAssets_[1] = outgoingAssets[1];
spendAssetAmounts_ = new uint256[](2);
spendAssetAmounts_[0] = maxOutgoingAssetAmounts[0];
spendAssetAmounts_[1] = maxOutgoingAssetAmounts[1];
incomingAssets_ = new address[](1);
// No need to validate not address(0), this will be caught in IntegrationManager
incomingAssets_[0] = IUniswapV2Factory(FACTORY).getPair(
outgoingAssets[0],
outgoingAssets[1]
);
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
} else if (_selector == REDEEM_SELECTOR) {
(
uint256 outgoingAssetAmount,
address[2] memory incomingAssets,
uint256[2] memory minIncomingAssetAmounts
) = __decodeRedeemCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
// No need to validate not address(0), this will be caught in IntegrationManager
spendAssets_[0] = IUniswapV2Factory(FACTORY).getPair(
incomingAssets[0],
incomingAssets[1]
);
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
incomingAssets_ = new address[](2);
incomingAssets_[0] = incomingAssets[0];
incomingAssets_[1] = incomingAssets[1];
minIncomingAssetAmounts_ = new uint256[](2);
minIncomingAssetAmounts_[0] = minIncomingAssetAmounts[0];
minIncomingAssetAmounts_[1] = minIncomingAssetAmounts[1];
} else if (_selector == TAKE_ORDER_SELECTOR) {
(
address[] memory path,
uint256 outgoingAssetAmount,
uint256 minIncomingAssetAmount
) = __decodeTakeOrderCallArgs(_encodedCallArgs);
require(path.length >= 2, "parseAssetsForMethod: _path must be >= 2");
spendAssets_ = new address[](1);
spendAssets_[0] = path[0];
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = path[path.length - 1];
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
} else {
revert("parseAssetsForMethod: _selector invalid");
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Lends assets for pool tokens on Uniswap
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
address[2] memory outgoingAssets,
uint256[2] memory maxOutgoingAssetAmounts,
uint256[2] memory minOutgoingAssetAmounts,
) = __decodeLendCallArgs(_encodedCallArgs);
__lend(
_vaultProxy,
outgoingAssets[0],
outgoingAssets[1],
maxOutgoingAssetAmounts[0],
maxOutgoingAssetAmounts[1],
minOutgoingAssetAmounts[0],
minOutgoingAssetAmounts[1]
);
}
/// @notice Redeems pool tokens on Uniswap
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
uint256 outgoingAssetAmount,
address[2] memory incomingAssets,
uint256[2] memory minIncomingAssetAmounts
) = __decodeRedeemCallArgs(_encodedCallArgs);
// More efficient to parse pool token from _encodedAssetTransferArgs than external call
(, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs(
_encodedAssetTransferArgs
);
__redeem(
_vaultProxy,
spendAssets[0],
outgoingAssetAmount,
incomingAssets[0],
incomingAssets[1],
minIncomingAssetAmounts[0],
minIncomingAssetAmounts[1]
);
}
/// @notice Trades assets on Uniswap
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function takeOrder(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
address[] memory path,
uint256 outgoingAssetAmount,
uint256 minIncomingAssetAmount
) = __decodeTakeOrderCallArgs(_encodedCallArgs);
__takeOrder(_vaultProxy, outgoingAssetAmount, minIncomingAssetAmount, path);
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the lend encoded call arguments
function __decodeLendCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address[2] memory outgoingAssets_,
uint256[2] memory maxOutgoingAssetAmounts_,
uint256[2] memory minOutgoingAssetAmounts_,
uint256 minIncomingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (address[2], uint256[2], uint256[2], uint256));
}
/// @dev Helper to decode the redeem encoded call arguments
function __decodeRedeemCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
uint256 outgoingAssetAmount_,
address[2] memory incomingAssets_,
uint256[2] memory minIncomingAssetAmounts_
)
{
return abi.decode(_encodedCallArgs, (uint256, address[2], uint256[2]));
}
/// @dev Helper to decode the take order encoded call arguments
function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address[] memory path_,
uint256 outgoingAssetAmount_,
uint256 minIncomingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (address[], uint256, uint256));
}
/// @dev Helper to execute lend. Avoids stack-too-deep error.
function __lend(
address _vaultProxy,
address _tokenA,
address _tokenB,
uint256 _amountADesired,
uint256 _amountBDesired,
uint256 _amountAMin,
uint256 _amountBMin
) private {
__approveMaxAsNeeded(_tokenA, ROUTER, _amountADesired);
__approveMaxAsNeeded(_tokenB, ROUTER, _amountBDesired);
// Execute lend on Uniswap
IUniswapV2Router2(ROUTER).addLiquidity(
_tokenA,
_tokenB,
_amountADesired,
_amountBDesired,
_amountAMin,
_amountBMin,
_vaultProxy,
block.timestamp.add(1)
);
}
/// @dev Helper to execute redeem. Avoids stack-too-deep error.
function __redeem(
address _vaultProxy,
address _poolToken,
uint256 _poolTokenAmount,
address _tokenA,
address _tokenB,
uint256 _amountAMin,
uint256 _amountBMin
) private {
__approveMaxAsNeeded(_poolToken, ROUTER, _poolTokenAmount);
// Execute redeem on Uniswap
IUniswapV2Router2(ROUTER).removeLiquidity(
_tokenA,
_tokenB,
_poolTokenAmount,
_amountAMin,
_amountBMin,
_vaultProxy,
block.timestamp.add(1)
);
}
/// @dev Helper to execute takeOrder. Avoids stack-too-deep error.
function __takeOrder(
address _vaultProxy,
uint256 _outgoingAssetAmount,
uint256 _minIncomingAssetAmount,
address[] memory _path
) private {
__approveMaxAsNeeded(_path[0], ROUTER, _outgoingAssetAmount);
// Execute fill
IUniswapV2Router2(ROUTER).swapExactTokensForTokens(
_outgoingAssetAmount,
_minIncomingAssetAmount,
_path,
_vaultProxy,
block.timestamp.add(1)
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `FACTORY` variable
/// @return factory_ The `FACTORY` variable value
function getFactory() external view returns (address factory_) {
return FACTORY;
}
/// @notice Gets the `ROUTER` variable
/// @return router_ The `ROUTER` variable value
function getRouter() external view returns (address router_) {
return ROUTER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title UniswapV2Router2 Interface
/// @author Enzyme Council <[email protected]>
/// @dev Minimal interface for our interactions with Uniswap V2's Router2
interface IUniswapV2Router2 {
function addLiquidity(
address,
address,
uint256,
uint256,
uint256,
uint256,
address,
uint256
)
external
returns (
uint256,
uint256,
uint256
);
function removeLiquidity(
address,
address,
uint256,
uint256,
uint256,
address,
uint256
) external returns (uint256, uint256);
function swapExactTokensForTokens(
uint256,
uint256,
address[] calldata,
address,
uint256
) external returns (uint256[] memory);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../interfaces/ICurveAddressProvider.sol";
import "../../../../interfaces/ICurveLiquidityGaugeToken.sol";
import "../../../../interfaces/ICurveLiquidityPool.sol";
import "../../../../interfaces/ICurveRegistry.sol";
import "../../../utils/DispatcherOwnerMixin.sol";
import "../IDerivativePriceFeed.sol";
/// @title CurvePriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price feed for Curve pool tokens
contract CurvePriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin {
using SafeMath for uint256;
event DerivativeAdded(
address indexed derivative,
address indexed pool,
address indexed invariantProxyAsset,
uint256 invariantProxyAssetDecimals
);
event DerivativeRemoved(address indexed derivative);
// Both pool tokens and liquidity gauge tokens are treated the same for pricing purposes.
// We take one asset as representative of the pool's invariant, e.g., WETH for ETH-based pools.
struct DerivativeInfo {
address pool;
address invariantProxyAsset;
uint256 invariantProxyAssetDecimals;
}
uint256 private constant VIRTUAL_PRICE_UNIT = 10**18;
address private immutable ADDRESS_PROVIDER;
mapping(address => DerivativeInfo) private derivativeToInfo;
constructor(address _dispatcher, address _addressProvider)
public
DispatcherOwnerMixin(_dispatcher)
{
ADDRESS_PROVIDER = _addressProvider;
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
public
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
DerivativeInfo memory derivativeInfo = derivativeToInfo[_derivative];
require(
derivativeInfo.pool != address(0),
"calcUnderlyingValues: _derivative is not supported"
);
underlyings_ = new address[](1);
underlyings_[0] = derivativeInfo.invariantProxyAsset;
underlyingAmounts_ = new uint256[](1);
if (derivativeInfo.invariantProxyAssetDecimals == 18) {
underlyingAmounts_[0] = _derivativeAmount
.mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price())
.div(VIRTUAL_PRICE_UNIT);
} else {
underlyingAmounts_[0] = _derivativeAmount
.mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price())
.mul(10**derivativeInfo.invariantProxyAssetDecimals)
.div(VIRTUAL_PRICE_UNIT.mul(2));
}
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return derivativeToInfo[_asset].pool != address(0);
}
//////////////////////////
// DERIVATIVES REGISTRY //
//////////////////////////
/// @notice Adds Curve LP and/or liquidity gauge tokens to the price feed
/// @param _derivatives Curve LP and/or liquidity gauge tokens to add
/// @param _invariantProxyAssets The ordered assets that act as proxies to the pool invariants,
/// corresponding to each item in _derivatives, e.g., WETH for ETH-based pools
function addDerivatives(
address[] calldata _derivatives,
address[] calldata _invariantProxyAssets
) external onlyDispatcherOwner {
require(_derivatives.length > 0, "addDerivatives: Empty _derivatives");
require(
_derivatives.length == _invariantProxyAssets.length,
"addDerivatives: Unequal arrays"
);
for (uint256 i; i < _derivatives.length; i++) {
require(_derivatives[i] != address(0), "addDerivatives: Empty derivative");
require(
_invariantProxyAssets[i] != address(0),
"addDerivatives: Empty invariantProxyAsset"
);
require(!isSupportedAsset(_derivatives[i]), "addDerivatives: Value already set");
// First, try assuming that the derivative is an LP token
ICurveRegistry curveRegistryContract = ICurveRegistry(
ICurveAddressProvider(ADDRESS_PROVIDER).get_registry()
);
address pool = curveRegistryContract.get_pool_from_lp_token(_derivatives[i]);
// If the derivative is not a valid LP token, try to treat it as a liquidity gauge token
if (pool == address(0)) {
// We cannot confirm whether a liquidity gauge token is a valid token
// for a particular liquidity gauge, due to some pools using
// old liquidity gauge contracts that did not incorporate a token
pool = curveRegistryContract.get_pool_from_lp_token(
ICurveLiquidityGaugeToken(_derivatives[i]).lp_token()
);
// Likely unreachable as above calls will revert on Curve, but doesn't hurt
require(
pool != address(0),
"addDerivatives: Not a valid LP token or liquidity gauge token"
);
}
uint256 invariantProxyAssetDecimals = ERC20(_invariantProxyAssets[i]).decimals();
derivativeToInfo[_derivatives[i]] = DerivativeInfo({
pool: pool,
invariantProxyAsset: _invariantProxyAssets[i],
invariantProxyAssetDecimals: invariantProxyAssetDecimals
});
// Confirm that a non-zero price can be returned for the registered derivative
(, uint256[] memory underlyingAmounts) = calcUnderlyingValues(
_derivatives[i],
1 ether
);
require(underlyingAmounts[0] > 0, "addDerivatives: could not calculate valid price");
emit DerivativeAdded(
_derivatives[i],
pool,
_invariantProxyAssets[i],
invariantProxyAssetDecimals
);
}
}
/// @notice Removes Curve LP and/or liquidity gauge tokens from the price feed
/// @param _derivatives Curve LP and/or liquidity gauge tokens to add
function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner {
require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives");
for (uint256 i; i < _derivatives.length; i++) {
require(_derivatives[i] != address(0), "removeDerivatives: Empty derivative");
require(isSupportedAsset(_derivatives[i]), "removeDerivatives: Value is not set");
delete derivativeToInfo[_derivatives[i]];
emit DerivativeRemoved(_derivatives[i]);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `ADDRESS_PROVIDER` variable
/// @return addressProvider_ The `ADDRESS_PROVIDER` variable value
function getAddressProvider() external view returns (address addressProvider_) {
return ADDRESS_PROVIDER;
}
/// @notice Gets the `DerivativeInfo` for a given derivative
/// @param _derivative The derivative for which to get the `DerivativeInfo`
/// @return derivativeInfo_ The `DerivativeInfo` value
function getDerivativeInfo(address _derivative)
external
view
returns (DerivativeInfo memory derivativeInfo_)
{
return derivativeToInfo[_derivative];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveAddressProvider interface
/// @author Enzyme Council <[email protected]>
interface ICurveAddressProvider {
function get_address(uint256) external view returns (address);
function get_registry() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveLiquidityGaugeToken interface
/// @author Enzyme Council <[email protected]>
/// @notice Common interface functions for all Curve liquidity gauge token contracts
interface ICurveLiquidityGaugeToken {
function lp_token() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveLiquidityPool interface
/// @author Enzyme Council <[email protected]>
interface ICurveLiquidityPool {
function coins(uint256) external view returns (address);
function get_virtual_price() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveRegistry interface
/// @author Enzyme Council <[email protected]>
interface ICurveRegistry {
function get_gauges(address) external view returns (address[10] memory, int128[10] memory);
function get_lp_token(address) external view returns (address);
function get_pool_from_lp_token(address) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../interfaces/ICurveAddressProvider.sol";
import "../../../../interfaces/ICurveLiquidityGaugeV2.sol";
import "../../../../interfaces/ICurveLiquidityPool.sol";
import "../../../../interfaces/ICurveRegistry.sol";
import "../../../../interfaces/ICurveStableSwapSteth.sol";
import "../../../../interfaces/IWETH.sol";
import "../utils/AdapterBase2.sol";
/// @title CurveLiquidityStethAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for liquidity provision in Curve's steth pool (https://www.curve.fi/steth)
contract CurveLiquidityStethAdapter is AdapterBase2 {
int128 private constant POOL_INDEX_ETH = 0;
int128 private constant POOL_INDEX_STETH = 1;
address private immutable LIQUIDITY_GAUGE_TOKEN;
address private immutable LP_TOKEN;
address private immutable POOL;
address private immutable STETH_TOKEN;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _liquidityGaugeToken,
address _lpToken,
address _pool,
address _stethToken,
address _wethToken
) public AdapterBase2(_integrationManager) {
LIQUIDITY_GAUGE_TOKEN = _liquidityGaugeToken;
LP_TOKEN = _lpToken;
POOL = _pool;
STETH_TOKEN = _stethToken;
WETH_TOKEN = _wethToken;
// Max approve contracts to spend relevant tokens
ERC20(_lpToken).safeApprove(_liquidityGaugeToken, type(uint256).max);
ERC20(_stethToken).safeApprove(_pool, type(uint256).max);
}
/// @dev Needed to receive ETH from redemption and to unwrap WETH
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "CURVE_LIQUIDITY_STETH";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == LEND_SELECTOR || _selector == LEND_AND_STAKE_SELECTOR) {
(
uint256 outgoingWethAmount,
uint256 outgoingStethAmount,
uint256 minIncomingAssetAmount
) = __decodeLendCallArgs(_encodedCallArgs);
if (outgoingWethAmount > 0 && outgoingStethAmount > 0) {
spendAssets_ = new address[](2);
spendAssets_[0] = WETH_TOKEN;
spendAssets_[1] = STETH_TOKEN;
spendAssetAmounts_ = new uint256[](2);
spendAssetAmounts_[0] = outgoingWethAmount;
spendAssetAmounts_[1] = outgoingStethAmount;
} else if (outgoingWethAmount > 0) {
spendAssets_ = new address[](1);
spendAssets_[0] = WETH_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingWethAmount;
} else {
spendAssets_ = new address[](1);
spendAssets_[0] = STETH_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingStethAmount;
}
incomingAssets_ = new address[](1);
if (_selector == LEND_SELECTOR) {
incomingAssets_[0] = LP_TOKEN;
} else {
incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
}
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
} else if (_selector == REDEEM_SELECTOR || _selector == UNSTAKE_AND_REDEEM_SELECTOR) {
(
uint256 outgoingAssetAmount,
uint256 minIncomingWethAmount,
uint256 minIncomingStethAmount,
bool receiveSingleAsset
) = __decodeRedeemCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
if (_selector == REDEEM_SELECTOR) {
spendAssets_[0] = LP_TOKEN;
} else {
spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
}
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
if (receiveSingleAsset) {
incomingAssets_ = new address[](1);
minIncomingAssetAmounts_ = new uint256[](1);
if (minIncomingWethAmount == 0) {
require(
minIncomingStethAmount > 0,
"parseAssetsForMethod: No min asset amount specified for receiveSingleAsset"
);
incomingAssets_[0] = STETH_TOKEN;
minIncomingAssetAmounts_[0] = minIncomingStethAmount;
} else {
require(
minIncomingStethAmount == 0,
"parseAssetsForMethod: Too many min asset amounts specified for receiveSingleAsset"
);
incomingAssets_[0] = WETH_TOKEN;
minIncomingAssetAmounts_[0] = minIncomingWethAmount;
}
} else {
incomingAssets_ = new address[](2);
incomingAssets_[0] = WETH_TOKEN;
incomingAssets_[1] = STETH_TOKEN;
minIncomingAssetAmounts_ = new uint256[](2);
minIncomingAssetAmounts_[0] = minIncomingWethAmount;
minIncomingAssetAmounts_[1] = minIncomingStethAmount;
}
} else if (_selector == STAKE_SELECTOR) {
uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = LP_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingLPTokenAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = outgoingLPTokenAmount;
} else if (_selector == UNSTAKE_SELECTOR) {
uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = LP_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount;
} else {
revert("parseAssetsForMethod: _selector invalid");
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Lends assets for steth LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
uint256 outgoingWethAmount,
uint256 outgoingStethAmount,
uint256 minIncomingLiquidityGaugeTokenAmount
) = __decodeLendCallArgs(_encodedCallArgs);
__lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount);
}
/// @notice Lends assets for steth LP tokens, then stakes the received LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lendAndStake(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
uint256 outgoingWethAmount,
uint256 outgoingStethAmount,
uint256 minIncomingLiquidityGaugeTokenAmount
) = __decodeLendCallArgs(_encodedCallArgs);
__lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount);
__stake(ERC20(LP_TOKEN).balanceOf(address(this)));
}
/// @notice Redeems steth LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
uint256 outgoingLPTokenAmount,
uint256 minIncomingWethAmount,
uint256 minIncomingStethAmount,
bool redeemSingleAsset
) = __decodeRedeemCallArgs(_encodedCallArgs);
__redeem(
outgoingLPTokenAmount,
minIncomingWethAmount,
minIncomingStethAmount,
redeemSingleAsset
);
}
/// @notice Stakes steth LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function stake(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs);
__stake(outgoingLPTokenAmount);
}
/// @notice Unstakes steth LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function unstake(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs);
__unstake(outgoingLiquidityGaugeTokenAmount);
}
/// @notice Unstakes steth LP tokens, then redeems them
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function unstakeAndRedeem(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
uint256 outgoingLiquidityGaugeTokenAmount,
uint256 minIncomingWethAmount,
uint256 minIncomingStethAmount,
bool redeemSingleAsset
) = __decodeRedeemCallArgs(_encodedCallArgs);
__unstake(outgoingLiquidityGaugeTokenAmount);
__redeem(
outgoingLiquidityGaugeTokenAmount,
minIncomingWethAmount,
minIncomingStethAmount,
redeemSingleAsset
);
}
// PRIVATE FUNCTIONS
/// @dev Helper to execute lend
function __lend(
uint256 _outgoingWethAmount,
uint256 _outgoingStethAmount,
uint256 _minIncomingLPTokenAmount
) private {
if (_outgoingWethAmount > 0) {
IWETH((WETH_TOKEN)).withdraw(_outgoingWethAmount);
}
ICurveStableSwapSteth(POOL).add_liquidity{value: _outgoingWethAmount}(
[_outgoingWethAmount, _outgoingStethAmount],
_minIncomingLPTokenAmount
);
}
/// @dev Helper to execute redeem
function __redeem(
uint256 _outgoingLPTokenAmount,
uint256 _minIncomingWethAmount,
uint256 _minIncomingStethAmount,
bool _redeemSingleAsset
) private {
if (_redeemSingleAsset) {
// "_minIncomingWethAmount > 0 XOR _minIncomingStethAmount > 0" has already been
// validated in parseAssetsForMethod()
if (_minIncomingWethAmount > 0) {
ICurveStableSwapSteth(POOL).remove_liquidity_one_coin(
_outgoingLPTokenAmount,
POOL_INDEX_ETH,
_minIncomingWethAmount
);
IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}();
} else {
ICurveStableSwapSteth(POOL).remove_liquidity_one_coin(
_outgoingLPTokenAmount,
POOL_INDEX_STETH,
_minIncomingStethAmount
);
}
} else {
ICurveStableSwapSteth(POOL).remove_liquidity(
_outgoingLPTokenAmount,
[_minIncomingWethAmount, _minIncomingStethAmount]
);
IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}();
}
}
/// @dev Helper to execute stake
function __stake(uint256 _lpTokenAmount) private {
ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).deposit(_lpTokenAmount, address(this));
}
/// @dev Helper to execute unstake
function __unstake(uint256 _liquidityGaugeTokenAmount) private {
ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).withdraw(_liquidityGaugeTokenAmount);
}
///////////////////////
// ENCODED CALL ARGS //
///////////////////////
/// @dev Helper to decode the encoded call arguments for lending
function __decodeLendCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
uint256 outgoingWethAmount_,
uint256 outgoingStethAmount_,
uint256 minIncomingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (uint256, uint256, uint256));
}
/// @dev Helper to decode the encoded call arguments for redeeming.
/// If `receiveSingleAsset_` is `true`, then one (and only one) of
/// `minIncomingWethAmount_` and `minIncomingStethAmount_` must be >0
/// to indicate which asset is to be received.
function __decodeRedeemCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
uint256 outgoingAssetAmount_,
uint256 minIncomingWethAmount_,
uint256 minIncomingStethAmount_,
bool receiveSingleAsset_
)
{
return abi.decode(_encodedCallArgs, (uint256, uint256, uint256, bool));
}
/// @dev Helper to decode the encoded call arguments for staking
function __decodeStakeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (uint256 outgoingLPTokenAmount_)
{
return abi.decode(_encodedCallArgs, (uint256));
}
/// @dev Helper to decode the encoded call arguments for unstaking
function __decodeUnstakeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (uint256 outgoingLiquidityGaugeTokenAmount_)
{
return abi.decode(_encodedCallArgs, (uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `LIQUIDITY_GAUGE_TOKEN` variable
/// @return liquidityGaugeToken_ The `LIQUIDITY_GAUGE_TOKEN` variable value
function getLiquidityGaugeToken() external view returns (address liquidityGaugeToken_) {
return LIQUIDITY_GAUGE_TOKEN;
}
/// @notice Gets the `LP_TOKEN` variable
/// @return lpToken_ The `LP_TOKEN` variable value
function getLPToken() external view returns (address lpToken_) {
return LP_TOKEN;
}
/// @notice Gets the `POOL` variable
/// @return pool_ The `POOL` variable value
function getPool() external view returns (address pool_) {
return POOL;
}
/// @notice Gets the `STETH_TOKEN` variable
/// @return stethToken_ The `STETH_TOKEN` variable value
function getStethToken() external view returns (address stethToken_) {
return STETH_TOKEN;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveLiquidityGaugeV2 interface
/// @author Enzyme Council <[email protected]>
interface ICurveLiquidityGaugeV2 {
function deposit(uint256, address) external;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveStableSwapSteth interface
/// @author Enzyme Council <[email protected]>
interface ICurveStableSwapSteth {
function add_liquidity(uint256[2] calldata, uint256) external payable returns (uint256);
function remove_liquidity(uint256, uint256[2] calldata) external returns (uint256[2] memory);
function remove_liquidity_one_coin(
uint256,
int128,
uint256
) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./AdapterBase.sol";
/// @title AdapterBase2 Contract
/// @author Enzyme Council <[email protected]>
/// @notice A base contract for integration adapters that extends AdapterBase
/// @dev This is a temporary contract that will be merged into AdapterBase with the next release
abstract contract AdapterBase2 is AdapterBase {
/// @dev Provides a standard implementation for transferring incoming assets and
/// unspent spend assets from an adapter to a VaultProxy at the end of an adapter action
modifier postActionAssetsTransferHandler(
address _vaultProxy,
bytes memory _encodedAssetTransferArgs
) {
_;
(
,
address[] memory spendAssets,
,
address[] memory incomingAssets
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
__transferFullAssetBalances(_vaultProxy, incomingAssets);
__transferFullAssetBalances(_vaultProxy, spendAssets);
}
/// @dev Provides a standard implementation for transferring incoming assets
/// from an adapter to a VaultProxy at the end of an adapter action
modifier postActionIncomingAssetsTransferHandler(
address _vaultProxy,
bytes memory _encodedAssetTransferArgs
) {
_;
(, , , address[] memory incomingAssets) = __decodeEncodedAssetTransferArgs(
_encodedAssetTransferArgs
);
__transferFullAssetBalances(_vaultProxy, incomingAssets);
}
/// @dev Provides a standard implementation for transferring unspent spend assets
/// from an adapter to a VaultProxy at the end of an adapter action
modifier postActionSpendAssetsTransferHandler(
address _vaultProxy,
bytes memory _encodedAssetTransferArgs
) {
_;
(, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs(
_encodedAssetTransferArgs
);
__transferFullAssetBalances(_vaultProxy, spendAssets);
}
constructor(address _integrationManager) public AdapterBase(_integrationManager) {}
/// @dev Helper to transfer full asset balances of current contract to the specified target
function __transferFullAssetBalances(address _target, address[] memory _assets) internal {
for (uint256 i = 0; i < _assets.length; i++) {
uint256 balance = ERC20(_assets[i]).balanceOf(address(this));
if (balance > 0) {
ERC20(_assets[i]).safeTransfer(_target, balance);
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/IParaSwapAugustusSwapper.sol";
import "../../../../interfaces/IWETH.sol";
import "../utils/AdapterBase.sol";
/// @title ParaSwapAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for interacting with ParaSwap
contract ParaSwapAdapter is AdapterBase {
using SafeMath for uint256;
string private constant REFERRER = "enzyme";
address private immutable EXCHANGE;
address private immutable TOKEN_TRANSFER_PROXY;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _exchange,
address _tokenTransferProxy,
address _wethToken
) public AdapterBase(_integrationManager) {
EXCHANGE = _exchange;
TOKEN_TRANSFER_PROXY = _tokenTransferProxy;
WETH_TOKEN = _wethToken;
}
/// @dev Needed to receive ETH refund from sent network fees
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "PARASWAP";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid");
(
address incomingAsset,
uint256 minIncomingAssetAmount,
,
address outgoingAsset,
uint256 outgoingAssetAmount,
IParaSwapAugustusSwapper.Path[] memory paths
) = __decodeCallArgs(_encodedCallArgs);
// Format incoming assets
incomingAssets_ = new address[](1);
incomingAssets_[0] = incomingAsset;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
// Format outgoing assets depending on if there are network fees
uint256 totalNetworkFees = __calcTotalNetworkFees(paths);
if (totalNetworkFees > 0) {
// We are not performing special logic if the incomingAsset is the fee asset
if (outgoingAsset == WETH_TOKEN) {
spendAssets_ = new address[](1);
spendAssets_[0] = outgoingAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount.add(totalNetworkFees);
} else {
spendAssets_ = new address[](2);
spendAssets_[0] = outgoingAsset;
spendAssets_[1] = WETH_TOKEN;
spendAssetAmounts_ = new uint256[](2);
spendAssetAmounts_[0] = outgoingAssetAmount;
spendAssetAmounts_[1] = totalNetworkFees;
}
} else {
spendAssets_ = new address[](1);
spendAssets_[0] = outgoingAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Trades assets on ParaSwap
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function takeOrder(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
__takeOrder(_vaultProxy, _encodedCallArgs);
}
// PRIVATE FUNCTIONS
/// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call
function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths)
private
pure
returns (uint256 totalNetworkFees_)
{
for (uint256 i; i < _paths.length; i++) {
totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee);
}
return totalNetworkFees_;
}
/// @dev Helper to decode the encoded callOnIntegration call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address incomingAsset_,
uint256 minIncomingAssetAmount_,
uint256 expectedIncomingAssetAmount_, // Passed as a courtesy to ParaSwap for analytics
address outgoingAsset_,
uint256 outgoingAssetAmount_,
IParaSwapAugustusSwapper.Path[] memory paths_
)
{
return
abi.decode(
_encodedCallArgs,
(address, uint256, uint256, address, uint256, IParaSwapAugustusSwapper.Path[])
);
}
/// @dev Helper to encode the call to ParaSwap multiSwap() as low-level calldata.
/// Avoids the stack-too-deep error.
function __encodeMultiSwapCallData(
address _vaultProxy,
address _incomingAsset,
uint256 _minIncomingAssetAmount,
uint256 _expectedIncomingAssetAmount, // Passed as a courtesy to ParaSwap for analytics
address _outgoingAsset,
uint256 _outgoingAssetAmount,
IParaSwapAugustusSwapper.Path[] memory _paths
) private pure returns (bytes memory multiSwapCallData) {
return
abi.encodeWithSelector(
IParaSwapAugustusSwapper.multiSwap.selector,
_outgoingAsset, // fromToken
_incomingAsset, // toToken
_outgoingAssetAmount, // fromAmount
_minIncomingAssetAmount, // toAmount
_expectedIncomingAssetAmount, // expectedAmount
_paths, // path
0, // mintPrice
payable(_vaultProxy), // beneficiary
0, // donationPercentage
REFERRER // referrer
);
}
/// @dev Helper to execute ParaSwapAugustusSwapper.multiSwap() via a low-level call.
/// Avoids the stack-too-deep error.
function __executeMultiSwap(bytes memory _multiSwapCallData, uint256 _totalNetworkFees)
private
{
(bool success, bytes memory returnData) = EXCHANGE.call{value: _totalNetworkFees}(
_multiSwapCallData
);
require(success, string(returnData));
}
/// @dev Helper for the inner takeOrder() logic.
/// Avoids the stack-too-deep error.
function __takeOrder(address _vaultProxy, bytes memory _encodedCallArgs) private {
(
address incomingAsset,
uint256 minIncomingAssetAmount,
uint256 expectedIncomingAssetAmount,
address outgoingAsset,
uint256 outgoingAssetAmount,
IParaSwapAugustusSwapper.Path[] memory paths
) = __decodeCallArgs(_encodedCallArgs);
__approveMaxAsNeeded(outgoingAsset, TOKEN_TRANSFER_PROXY, outgoingAssetAmount);
// If there are network fees, unwrap enough WETH to cover the fees
uint256 totalNetworkFees = __calcTotalNetworkFees(paths);
if (totalNetworkFees > 0) {
__unwrapWeth(totalNetworkFees);
}
// Get the callData for the low-level multiSwap() call
bytes memory multiSwapCallData = __encodeMultiSwapCallData(
_vaultProxy,
incomingAsset,
minIncomingAssetAmount,
expectedIncomingAssetAmount,
outgoingAsset,
outgoingAssetAmount,
paths
);
// Execute the trade on ParaSwap
__executeMultiSwap(multiSwapCallData, totalNetworkFees);
// If fees were paid and ETH remains in the contract, wrap it as WETH so it can be returned
if (totalNetworkFees > 0) {
__wrapEth();
}
}
/// @dev Helper to unwrap specified amount of WETH into ETH.
/// Avoids the stack-too-deep error.
function __unwrapWeth(uint256 _amount) private {
IWETH(payable(WETH_TOKEN)).withdraw(_amount);
}
/// @dev Helper to wrap all ETH in contract as WETH.
/// Avoids the stack-too-deep error.
function __wrapEth() private {
uint256 ethBalance = payable(address(this)).balance;
if (ethBalance > 0) {
IWETH(payable(WETH_TOKEN)).deposit{value: ethBalance}();
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `EXCHANGE` variable
/// @return exchange_ The `EXCHANGE` variable value
function getExchange() external view returns (address exchange_) {
return EXCHANGE;
}
/// @notice Gets the `TOKEN_TRANSFER_PROXY` variable
/// @return tokenTransferProxy_ The `TOKEN_TRANSFER_PROXY` variable value
function getTokenTransferProxy() external view returns (address tokenTransferProxy_) {
return TOKEN_TRANSFER_PROXY;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title ParaSwap IAugustusSwapper interface
interface IParaSwapAugustusSwapper {
struct Route {
address payable exchange;
address targetExchange;
uint256 percent;
bytes payload;
uint256 networkFee;
}
struct Path {
address to;
uint256 totalNetworkFee;
Route[] routes;
}
function multiSwap(
address,
address,
uint256,
uint256,
uint256,
Path[] calldata,
uint256,
address payable,
uint256,
string calldata
) external payable returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../release/interfaces/IParaSwapAugustusSwapper.sol";
import "../prices/CentralizedRateProvider.sol";
import "../utils/SwapperBase.sol";
contract MockParaSwapIntegratee is SwapperBase {
using SafeMath for uint256;
address private immutable MOCK_CENTRALIZED_RATE_PROVIDER;
// Deviation set in % defines the MAX deviation per block from the mean rate
uint256 private blockNumberDeviation;
constructor(address _mockCentralizedRateProvider, uint256 _blockNumberDeviation) public {
MOCK_CENTRALIZED_RATE_PROVIDER = _mockCentralizedRateProvider;
blockNumberDeviation = _blockNumberDeviation;
}
/// @dev Must be `public` to avoid error
function multiSwap(
address _fromToken,
address _toToken,
uint256 _fromAmount,
uint256, // toAmount (min received amount)
uint256, // expectedAmount
IParaSwapAugustusSwapper.Path[] memory _paths,
uint256, // mintPrice
address, // beneficiary
uint256, // donationPercentage
string memory // referrer
) public payable returns (uint256) {
return __multiSwap(_fromToken, _toToken, _fromAmount, _paths);
}
/// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call
function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths)
private
pure
returns (uint256 totalNetworkFees_)
{
for (uint256 i; i < _paths.length; i++) {
totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee);
}
return totalNetworkFees_;
}
/// @dev Helper to avoid the stack-too-deep error
function __multiSwap(
address _fromToken,
address _toToken,
uint256 _fromAmount,
IParaSwapAugustusSwapper.Path[] memory _paths
) private returns (uint256) {
address[] memory assetsFromIntegratee = new address[](1);
assetsFromIntegratee[0] = _toToken;
uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1);
assetsFromIntegrateeAmounts[0] = CentralizedRateProvider(MOCK_CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomized(_fromToken, _fromAmount, _toToken, blockNumberDeviation);
uint256 totalNetworkFees = __calcTotalNetworkFees(_paths);
address[] memory assetsToIntegratee;
uint256[] memory assetsToIntegrateeAmounts;
if (totalNetworkFees > 0) {
assetsToIntegratee = new address[](2);
assetsToIntegratee[1] = ETH_ADDRESS;
assetsToIntegrateeAmounts = new uint256[](2);
assetsToIntegrateeAmounts[1] = totalNetworkFees;
} else {
assetsToIntegratee = new address[](1);
assetsToIntegrateeAmounts = new uint256[](1);
}
assetsToIntegratee[0] = _fromToken;
assetsToIntegrateeAmounts[0] = _fromAmount;
__swap(
msg.sender,
assetsToIntegratee,
assetsToIntegrateeAmounts,
assetsFromIntegratee,
assetsFromIntegrateeAmounts
);
return assetsFromIntegrateeAmounts[0];
}
///////////////////
// STATE GETTERS //
///////////////////
function getBlockNumberDeviation() external view returns (uint256 blockNumberDeviation_) {
return blockNumberDeviation;
}
function getCentralizedRateProvider()
external
view
returns (address centralizedRateProvider_)
{
return MOCK_CENTRALIZED_RATE_PROVIDER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./EthConstantMixin.sol";
abstract contract SwapperBase is EthConstantMixin {
receive() external payable {}
function __swapAssets(
address payable _trader,
address _srcToken,
uint256 _srcAmount,
address _destToken,
uint256 _actualRate
) internal returns (uint256 destAmount_) {
address[] memory assetsToIntegratee = new address[](1);
assetsToIntegratee[0] = _srcToken;
uint256[] memory assetsToIntegrateeAmounts = new uint256[](1);
assetsToIntegrateeAmounts[0] = _srcAmount;
address[] memory assetsFromIntegratee = new address[](1);
assetsFromIntegratee[0] = _destToken;
uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1);
assetsFromIntegrateeAmounts[0] = _actualRate;
__swap(
_trader,
assetsToIntegratee,
assetsToIntegrateeAmounts,
assetsFromIntegratee,
assetsFromIntegrateeAmounts
);
return assetsFromIntegrateeAmounts[0];
}
function __swap(
address payable _trader,
address[] memory _assetsToIntegratee,
uint256[] memory _assetsToIntegrateeAmounts,
address[] memory _assetsFromIntegratee,
uint256[] memory _assetsFromIntegrateeAmounts
) internal {
// Take custody of incoming assets
for (uint256 i = 0; i < _assetsToIntegratee.length; i++) {
address asset = _assetsToIntegratee[i];
uint256 amount = _assetsToIntegrateeAmounts[i];
require(asset != address(0), "__swap: empty value in _assetsToIntegratee");
require(amount > 0, "__swap: empty value in _assetsToIntegrateeAmounts");
// Incoming ETH amounts can be ignored
if (asset == ETH_ADDRESS) {
continue;
}
ERC20(asset).transferFrom(_trader, address(this), amount);
}
// Distribute outgoing assets
for (uint256 i = 0; i < _assetsFromIntegratee.length; i++) {
address asset = _assetsFromIntegratee[i];
uint256 amount = _assetsFromIntegrateeAmounts[i];
require(asset != address(0), "__swap: empty value in _assetsFromIntegratee");
require(amount > 0, "__swap: empty value in _assetsFromIntegrateeAmounts");
if (asset == ETH_ADDRESS) {
_trader.transfer(amount);
} else {
ERC20(asset).transfer(_trader, amount);
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
abstract contract EthConstantMixin {
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/NormalizedRateProviderBase.sol";
import "../../utils/SwapperBase.sol";
abstract contract MockIntegrateeBase is NormalizedRateProviderBase, SwapperBase {
constructor(
address[] memory _defaultRateAssets,
address[] memory _specialAssets,
uint8[] memory _specialAssetDecimals,
uint256 _ratePrecision
)
public
NormalizedRateProviderBase(
_defaultRateAssets,
_specialAssets,
_specialAssetDecimals,
_ratePrecision
)
{}
function __getRate(address _baseAsset, address _quoteAsset)
internal
view
override
returns (uint256)
{
// 1. Return constant if base asset is quote asset
if (_baseAsset == _quoteAsset) {
return 10**RATE_PRECISION;
}
// 2. Check for a direct rate
uint256 directRate = assetToAssetRate[_baseAsset][_quoteAsset];
if (directRate > 0) {
return directRate;
}
// 3. Check for inverse direct rate
uint256 iDirectRate = assetToAssetRate[_quoteAsset][_baseAsset];
if (iDirectRate > 0) {
return 10**(RATE_PRECISION.mul(2)).div(iDirectRate);
}
// 4. Else return 1
return 10**RATE_PRECISION;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./RateProviderBase.sol";
abstract contract NormalizedRateProviderBase is RateProviderBase {
using SafeMath for uint256;
uint256 public immutable RATE_PRECISION;
constructor(
address[] memory _defaultRateAssets,
address[] memory _specialAssets,
uint8[] memory _specialAssetDecimals,
uint256 _ratePrecision
) public RateProviderBase(_specialAssets, _specialAssetDecimals) {
RATE_PRECISION = _ratePrecision;
for (uint256 i = 0; i < _defaultRateAssets.length; i++) {
for (uint256 j = i + 1; j < _defaultRateAssets.length; j++) {
assetToAssetRate[_defaultRateAssets[i]][_defaultRateAssets[j]] =
10**_ratePrecision;
assetToAssetRate[_defaultRateAssets[j]][_defaultRateAssets[i]] =
10**_ratePrecision;
}
}
}
// TODO: move to main contracts' utils for use with prices
function __calcDenormalizedQuoteAssetAmount(
uint256 _baseAssetDecimals,
uint256 _baseAssetAmount,
uint256 _quoteAssetDecimals,
uint256 _rate
) internal view returns (uint256) {
return
_rate.mul(_baseAssetAmount).mul(10**_quoteAssetDecimals).div(
10**(RATE_PRECISION.add(_baseAssetDecimals))
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./EthConstantMixin.sol";
abstract contract RateProviderBase is EthConstantMixin {
mapping(address => mapping(address => uint256)) public assetToAssetRate;
// Handles non-ERC20 compliant assets like ETH and USD
mapping(address => uint8) public specialAssetToDecimals;
constructor(address[] memory _specialAssets, uint8[] memory _specialAssetDecimals) public {
require(
_specialAssets.length == _specialAssetDecimals.length,
"constructor: _specialAssets and _specialAssetDecimals are uneven lengths"
);
for (uint256 i = 0; i < _specialAssets.length; i++) {
specialAssetToDecimals[_specialAssets[i]] = _specialAssetDecimals[i];
}
specialAssetToDecimals[ETH_ADDRESS] = 18;
}
function __getDecimalsForAsset(address _asset) internal view returns (uint256) {
uint256 decimals = specialAssetToDecimals[_asset];
if (decimals == 0) {
decimals = uint256(ERC20(_asset).decimals());
}
return decimals;
}
function __getRate(address _baseAsset, address _quoteAsset)
internal
view
virtual
returns (uint256)
{
return assetToAssetRate[_baseAsset][_quoteAsset];
}
function setRates(
address[] calldata _baseAssets,
address[] calldata _quoteAssets,
uint256[] calldata _rates
) external {
require(
_baseAssets.length == _quoteAssets.length,
"setRates: _baseAssets and _quoteAssets are uneven lengths"
);
require(
_baseAssets.length == _rates.length,
"setRates: _baseAssets and _rates are uneven lengths"
);
for (uint256 i = 0; i < _baseAssets.length; i++) {
assetToAssetRate[_baseAssets[i]][_quoteAssets[i]] = _rates[i];
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/// @title AssetUnitCacheMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice Mixin to store a cache of asset units
abstract contract AssetUnitCacheMixin {
event AssetUnitCached(address indexed asset, uint256 prevUnit, uint256 nextUnit);
mapping(address => uint256) private assetToUnit;
/// @notice Caches the decimal-relative unit for a given asset
/// @param _asset The asset for which to cache the decimal-relative unit
/// @dev Callable by any account
function cacheAssetUnit(address _asset) public {
uint256 prevUnit = getCachedUnitForAsset(_asset);
uint256 nextUnit = 10**uint256(ERC20(_asset).decimals());
if (nextUnit != prevUnit) {
assetToUnit[_asset] = nextUnit;
emit AssetUnitCached(_asset, prevUnit, nextUnit);
}
}
/// @notice Caches the decimal-relative units for multiple given assets
/// @param _assets The assets for which to cache the decimal-relative units
/// @dev Callable by any account
function cacheAssetUnits(address[] memory _assets) public {
for (uint256 i; i < _assets.length; i++) {
cacheAssetUnit(_assets[i]);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the cached decimal-relative unit for a given asset
/// @param _asset The asset for which to get the cached decimal-relative unit
/// @return unit_ The cached decimal-relative unit
function getCachedUnitForAsset(address _asset) public view returns (uint256 unit_) {
return assetToUnit[_asset];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../IDerivativePriceFeed.sol";
/// @title SinglePeggedDerivativePriceFeedBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price feed base for any single derivative that is pegged 1:1 to its underlying
abstract contract SinglePeggedDerivativePriceFeedBase is IDerivativePriceFeed {
address private immutable DERIVATIVE;
address private immutable UNDERLYING;
constructor(address _derivative, address _underlying) public {
require(
ERC20(_derivative).decimals() == ERC20(_underlying).decimals(),
"constructor: Unequal decimals"
);
DERIVATIVE = _derivative;
UNDERLYING = _underlying;
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
require(isSupportedAsset(_derivative), "calcUnderlyingValues: Not a supported derivative");
underlyings_ = new address[](1);
underlyings_[0] = UNDERLYING;
underlyingAmounts_ = new uint256[](1);
underlyingAmounts_[0] = _derivativeAmount;
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return _asset == DERIVATIVE;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `DERIVATIVE` variable value
/// @return derivative_ The `DERIVATIVE` variable value
function getDerivative() external view returns (address derivative_) {
return DERIVATIVE;
}
/// @notice Gets the `UNDERLYING` variable value
/// @return underlying_ The `UNDERLYING` variable value
function getUnderlying() external view returns (address underlying_) {
return UNDERLYING;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SinglePeggedDerivativePriceFeedBase.sol";
/// @title TestSingleUnderlyingDerivativeRegistry Contract
/// @author Enzyme Council <[email protected]>
/// @notice A test implementation of SinglePeggedDerivativePriceFeedBase
contract TestSinglePeggedDerivativePriceFeed is SinglePeggedDerivativePriceFeedBase {
constructor(address _derivative, address _underlying)
public
SinglePeggedDerivativePriceFeedBase(_derivative, _underlying)
{}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./utils/SinglePeggedDerivativePriceFeedBase.sol";
/// @title StakehoundEthPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for Stakehound stETH, which maps 1:1 with ETH
contract StakehoundEthPriceFeed is SinglePeggedDerivativePriceFeedBase {
constructor(address _steth, address _weth)
public
SinglePeggedDerivativePriceFeedBase(_steth, _weth)
{}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]yme.finance>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./utils/SinglePeggedDerivativePriceFeedBase.sol";
/// @title LidoStethPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for Lido stETH, which maps 1:1 with ETH (https://lido.fi/)
contract LidoStethPriceFeed is SinglePeggedDerivativePriceFeedBase {
constructor(address _steth, address _weth)
public
SinglePeggedDerivativePriceFeedBase(_steth, _weth)
{}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../interfaces/IKyberNetworkProxy.sol";
import "../../../../interfaces/IWETH.sol";
import "../../../../utils/MathHelpers.sol";
import "../utils/AdapterBase.sol";
/// @title KyberAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for interacting with Kyber Network
contract KyberAdapter is AdapterBase, MathHelpers {
address private immutable EXCHANGE;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _exchange,
address _wethToken
) public AdapterBase(_integrationManager) {
EXCHANGE = _exchange;
WETH_TOKEN = _wethToken;
}
/// @dev Needed to receive ETH from swap
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "KYBER_NETWORK";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid");
(
address incomingAsset,
uint256 minIncomingAssetAmount,
address outgoingAsset,
uint256 outgoingAssetAmount
) = __decodeCallArgs(_encodedCallArgs);
require(
incomingAsset != outgoingAsset,
"parseAssetsForMethod: incomingAsset and outgoingAsset asset cannot be the same"
);
require(outgoingAssetAmount > 0, "parseAssetsForMethod: outgoingAssetAmount must be >0");
spendAssets_ = new address[](1);
spendAssets_[0] = outgoingAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = incomingAsset;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Trades assets on Kyber
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function takeOrder(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
address incomingAsset,
uint256 minIncomingAssetAmount,
address outgoingAsset,
uint256 outgoingAssetAmount
) = __decodeCallArgs(_encodedCallArgs);
uint256 minExpectedRate = __calcNormalizedRate(
ERC20(outgoingAsset).decimals(),
outgoingAssetAmount,
ERC20(incomingAsset).decimals(),
minIncomingAssetAmount
);
if (outgoingAsset == WETH_TOKEN) {
__swapNativeAssetToToken(incomingAsset, outgoingAssetAmount, minExpectedRate);
} else if (incomingAsset == WETH_TOKEN) {
__swapTokenToNativeAsset(outgoingAsset, outgoingAssetAmount, minExpectedRate);
} else {
__swapTokenToToken(incomingAsset, outgoingAsset, outgoingAssetAmount, minExpectedRate);
}
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the encoded call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address incomingAsset_,
uint256 minIncomingAssetAmount_,
address outgoingAsset_,
uint256 outgoingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (address, uint256, address, uint256));
}
/// @dev Executes a swap of ETH to ERC20
function __swapNativeAssetToToken(
address _incomingAsset,
uint256 _outgoingAssetAmount,
uint256 _minExpectedRate
) private {
IWETH(payable(WETH_TOKEN)).withdraw(_outgoingAssetAmount);
IKyberNetworkProxy(EXCHANGE).swapEtherToToken{value: _outgoingAssetAmount}(
_incomingAsset,
_minExpectedRate
);
}
/// @dev Executes a swap of ERC20 to ETH
function __swapTokenToNativeAsset(
address _outgoingAsset,
uint256 _outgoingAssetAmount,
uint256 _minExpectedRate
) private {
__approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount);
IKyberNetworkProxy(EXCHANGE).swapTokenToEther(
_outgoingAsset,
_outgoingAssetAmount,
_minExpectedRate
);
IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}();
}
/// @dev Executes a swap of ERC20 to ERC20
function __swapTokenToToken(
address _incomingAsset,
address _outgoingAsset,
uint256 _outgoingAssetAmount,
uint256 _minExpectedRate
) private {
__approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount);
IKyberNetworkProxy(EXCHANGE).swapTokenToToken(
_outgoingAsset,
_outgoingAssetAmount,
_incomingAsset,
_minExpectedRate
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `EXCHANGE` variable
/// @return exchange_ The `EXCHANGE` variable value
function getExchange() external view returns (address exchange_) {
return EXCHANGE;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title Kyber Network interface
interface IKyberNetworkProxy {
function swapEtherToToken(address, uint256) external payable returns (uint256);
function swapTokenToEther(
address,
uint256,
uint256
) external returns (uint256);
function swapTokenToToken(
address,
uint256,
address,
uint256
) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../release/utils/MathHelpers.sol";
import "../prices/CentralizedRateProvider.sol";
import "../utils/SwapperBase.sol";
contract MockKyberIntegratee is SwapperBase, Ownable, MathHelpers {
using SafeMath for uint256;
address private immutable CENTRALIZED_RATE_PROVIDER;
address private immutable WETH;
uint256 private constant PRECISION = 18;
// Deviation set in % defines the MAX deviation per block from the mean rate
uint256 private blockNumberDeviation;
constructor(
address _centralizedRateProvider,
address _weth,
uint256 _blockNumberDeviation
) public {
CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider;
WETH = _weth;
blockNumberDeviation = _blockNumberDeviation;
}
function swapEtherToToken(address _destToken, uint256) external payable returns (uint256) {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomized(WETH, msg.value, _destToken, blockNumberDeviation);
__swapAssets(msg.sender, ETH_ADDRESS, msg.value, _destToken, destAmount);
return msg.value;
}
function swapTokenToEther(
address _srcToken,
uint256 _srcAmount,
uint256
) external returns (uint256) {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomized(_srcToken, _srcAmount, WETH, blockNumberDeviation);
__swapAssets(msg.sender, _srcToken, _srcAmount, ETH_ADDRESS, destAmount);
return _srcAmount;
}
function swapTokenToToken(
address _srcToken,
uint256 _srcAmount,
address _destToken,
uint256
) external returns (uint256) {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomized(_srcToken, _srcAmount, _destToken, blockNumberDeviation);
__swapAssets(msg.sender, _srcToken, _srcAmount, _destToken, destAmount);
return _srcAmount;
}
function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner {
blockNumberDeviation = _deviationPct;
}
function getExpectedRate(
address _srcToken,
address _destToken,
uint256 _amount
) external returns (uint256 rate_, uint256 worstRate_) {
if (_srcToken == ETH_ADDRESS) {
_srcToken = WETH;
}
if (_destToken == ETH_ADDRESS) {
_destToken = WETH;
}
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomizedBySender(_srcToken, _amount, _destToken);
rate_ = __calcNormalizedRate(
ERC20(_srcToken).decimals(),
_amount,
ERC20(_destToken).decimals(),
destAmount
);
worstRate_ = rate_.mul(uint256(100).sub(blockNumberDeviation)).div(100);
}
///////////////////
// STATE GETTERS //
///////////////////
function getCentralizedRateProvider() public view returns (address) {
return CENTRALIZED_RATE_PROVIDER;
}
function getWeth() public view returns (address) {
return WETH;
}
function getBlockNumberDeviation() public view returns (uint256) {
return blockNumberDeviation;
}
function getPrecision() public pure returns (uint256) {
return PRECISION;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./../../release/interfaces/ISynthetixExchangeRates.sol";
import "../prices/MockChainlinkPriceSource.sol";
/// @dev This price source offers two different options getting prices
/// The first one is getting a fixed rate, which can be useful for tests
/// The second approach calculates dinamically the rate making use of a chainlink price source
/// Mocks the functionality of the folllowing Synthetix contracts: { Exchanger, ExchangeRates }
contract MockSynthetixPriceSource is Ownable, ISynthetixExchangeRates {
using SafeMath for uint256;
mapping(bytes32 => uint256) private fixedRate;
mapping(bytes32 => AggregatorInfo) private currencyKeyToAggregator;
enum RateAsset {ETH, USD}
struct AggregatorInfo {
address aggregator;
RateAsset rateAsset;
}
constructor(address _ethUsdAggregator) public {
currencyKeyToAggregator[bytes32("ETH")] = AggregatorInfo({
aggregator: _ethUsdAggregator,
rateAsset: RateAsset.USD
});
}
function setPriceSourcesForCurrencyKeys(
bytes32[] calldata _currencyKeys,
address[] calldata _aggregators,
RateAsset[] calldata _rateAssets
) external onlyOwner {
require(
_currencyKeys.length == _aggregators.length &&
_rateAssets.length == _aggregators.length
);
for (uint256 i = 0; i < _currencyKeys.length; i++) {
currencyKeyToAggregator[_currencyKeys[i]] = AggregatorInfo({
aggregator: _aggregators[i],
rateAsset: _rateAssets[i]
});
}
}
function setRate(bytes32 _currencyKey, uint256 _rate) external onlyOwner {
fixedRate[_currencyKey] = _rate;
}
/// @dev Calculates the rate from a currency key against USD
function rateAndInvalid(bytes32 _currencyKey)
external
view
override
returns (uint256 rate_, bool isInvalid_)
{
uint256 storedRate = getFixedRate(_currencyKey);
if (storedRate != 0) {
rate_ = storedRate;
} else {
AggregatorInfo memory aggregatorInfo = getAggregatorFromCurrencyKey(_currencyKey);
address aggregator = aggregatorInfo.aggregator;
if (aggregator == address(0)) {
rate_ = 0;
isInvalid_ = true;
return (rate_, isInvalid_);
}
uint256 decimals = MockChainlinkPriceSource(aggregator).decimals();
rate_ = uint256(MockChainlinkPriceSource(aggregator).latestAnswer()).mul(
10**(uint256(18).sub(decimals))
);
if (aggregatorInfo.rateAsset == RateAsset.ETH) {
uint256 ethToUsd = uint256(
MockChainlinkPriceSource(
getAggregatorFromCurrencyKey(bytes32("ETH"))
.aggregator
)
.latestAnswer()
);
rate_ = rate_.mul(ethToUsd).div(10**8);
}
}
isInvalid_ = (rate_ == 0);
return (rate_, isInvalid_);
}
///////////////////
// STATE GETTERS //
///////////////////
function getAggregatorFromCurrencyKey(bytes32 _currencyKey)
public
view
returns (AggregatorInfo memory _aggregator)
{
return currencyKeyToAggregator[_currencyKey];
}
function getFixedRate(bytes32 _currencyKey) public view returns (uint256) {
return fixedRate[_currencyKey];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
contract MockChainlinkPriceSource {
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp);
uint256 public DECIMALS;
int256 public latestAnswer;
uint256 public latestTimestamp;
uint256 public roundId;
address public aggregator;
constructor(uint256 _decimals) public {
DECIMALS = _decimals;
latestAnswer = int256(10**_decimals);
latestTimestamp = now;
roundId = 1;
aggregator = address(this);
}
function setLatestAnswer(int256 _nextAnswer, uint256 _nextTimestamp) external {
latestAnswer = _nextAnswer;
latestTimestamp = _nextTimestamp;
roundId = roundId + 1;
emit AnswerUpdated(latestAnswer, roundId, latestTimestamp);
}
function setAggregator(address _nextAggregator) external {
aggregator = _nextAggregator;
}
function decimals() public view returns (uint256) {
return DECIMALS;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./../../release/interfaces/ISynthetixExchangeRates.sol";
import "../prices/CentralizedRateProvider.sol";
import "../tokens/MockSynthetixToken.sol";
/// @dev Synthetix Integratee. Mocks functionalities from the folllowing synthetix contracts
/// Synthetix, SynthetixAddressResolver, SynthetixDelegateApprovals
/// Link to contracts: <https://github.com/Synthetixio/synthetix/tree/develop/contracts>
contract MockSynthetixIntegratee is Ownable, MockToken {
using SafeMath for uint256;
mapping(address => mapping(address => bool)) private authorizerToDelegateToApproval;
mapping(bytes32 => address) private currencyKeyToSynth;
address private immutable CENTRALIZED_RATE_PROVIDER;
address private immutable EXCHANGE_RATES;
uint256 private immutable FEE;
uint256 private constant UNIT_FEE = 1000;
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _centralizedRateProvider,
address _exchangeRates,
uint256 _fee
) public MockToken(_name, _symbol, _decimals) {
CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider;
EXCHANGE_RATES = address(_exchangeRates);
FEE = _fee;
}
receive() external payable {}
function exchangeOnBehalfWithTracking(
address _exchangeForAddress,
bytes32 _srcCurrencyKey,
uint256 _srcAmount,
bytes32 _destinationCurrencyKey,
address,
bytes32
) external returns (uint256 amountReceived_) {
require(
canExchangeFor(_exchangeForAddress, msg.sender),
"exchangeOnBehalfWithTracking: Not approved to act on behalf"
);
amountReceived_ = __calculateAndSwap(
_exchangeForAddress,
_srcAmount,
_srcCurrencyKey,
_destinationCurrencyKey
);
return amountReceived_;
}
function getAmountsForExchange(
uint256 _srcAmount,
bytes32 _srcCurrencyKey,
bytes32 _destCurrencyKey
)
public
returns (
uint256 amountReceived_,
uint256 fee_,
uint256 exchangeFeeRate_
)
{
address srcToken = currencyKeyToSynth[_srcCurrencyKey];
address destToken = currencyKeyToSynth[_destCurrencyKey];
require(
currencyKeyToSynth[_srcCurrencyKey] != address(0) &&
currencyKeyToSynth[_destCurrencyKey] != address(0),
"getAmountsForExchange: Currency key doesn't have an associated synth"
);
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomizedBySender(srcToken, _srcAmount, destToken);
exchangeFeeRate_ = FEE;
amountReceived_ = destAmount.mul(UNIT_FEE.sub(exchangeFeeRate_)).div(UNIT_FEE);
fee_ = destAmount.sub(amountReceived_);
return (amountReceived_, fee_, exchangeFeeRate_);
}
function setSynthFromCurrencyKeys(bytes32[] calldata _currencyKeys, address[] calldata _synths)
external
{
require(
_currencyKeys.length == _synths.length,
"setSynthFromCurrencyKey: Unequal _currencyKeys and _synths lengths"
);
for (uint256 i = 0; i < _currencyKeys.length; i++) {
currencyKeyToSynth[_currencyKeys[i]] = _synths[i];
}
}
function approveExchangeOnBehalf(address _delegate) external {
authorizerToDelegateToApproval[msg.sender][_delegate] = true;
}
function __calculateAndSwap(
address _exchangeForAddress,
uint256 _srcAmount,
bytes32 _srcCurrencyKey,
bytes32 _destCurrencyKey
) private returns (uint256 amountReceived_) {
MockSynthetixToken srcSynth = MockSynthetixToken(currencyKeyToSynth[_srcCurrencyKey]);
MockSynthetixToken destSynth = MockSynthetixToken(currencyKeyToSynth[_destCurrencyKey]);
require(address(srcSynth) != address(0), "__calculateAndSwap: Source synth is not listed");
require(
address(destSynth) != address(0),
"__calculateAndSwap: Destination synth is not listed"
);
require(
!srcSynth.isLocked(_exchangeForAddress),
"__calculateAndSwap: Cannot settle during waiting period"
);
(amountReceived_, , ) = getAmountsForExchange(
_srcAmount,
_srcCurrencyKey,
_destCurrencyKey
);
srcSynth.burnFrom(_exchangeForAddress, _srcAmount);
destSynth.mintFor(_exchangeForAddress, amountReceived_);
destSynth.lock(_exchangeForAddress);
return amountReceived_;
}
function requireAndGetAddress(bytes32 _name, string calldata)
external
view
returns (address resolvedAddress_)
{
if (_name == "ExchangeRates") {
return EXCHANGE_RATES;
}
return address(this);
}
function settle(address, bytes32)
external
returns (
uint256,
uint256,
uint256
)
{}
///////////////////
// STATE GETTERS //
///////////////////
function canExchangeFor(address _authorizer, address _delegate)
public
view
returns (bool canExchange_)
{
return authorizerToDelegateToApproval[_authorizer][_delegate];
}
function getExchangeRates() public view returns (address exchangeRates_) {
return EXCHANGE_RATES;
}
function getFee() public view returns (uint256 fee_) {
return FEE;
}
function getSynthFromCurrencyKey(bytes32 _currencyKey) public view returns (address synth_) {
return currencyKeyToSynth[_currencyKey];
}
function getUnitFee() public pure returns (uint256 fee_) {
return UNIT_FEE;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../prices/CentralizedRateProvider.sol";
import "./utils/SimpleMockIntegrateeBase.sol";
/// @dev Mocks the integration with `UniswapV2Router02` <https://uniswap.org/docs/v2/smart-contracts/router02/>
/// Additionally mocks the integration with `UniswapV2Factory` <https://uniswap.org/docs/v2/smart-contracts/factory/>
contract MockUniswapV2Integratee is SwapperBase, Ownable {
using SafeMath for uint256;
mapping(address => mapping(address => address)) private assetToAssetToPair;
address private immutable CENTRALIZED_RATE_PROVIDER;
uint256 private constant PRECISION = 18;
// Set in %, defines the MAX deviation per block from the mean rate
uint256 private blockNumberDeviation;
constructor(
address[] memory _listOfToken0,
address[] memory _listOfToken1,
address[] memory _listOfPair,
address _centralizedRateProvider,
uint256 _blockNumberDeviation
) public {
addPair(_listOfToken0, _listOfToken1, _listOfPair);
CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider;
blockNumberDeviation = _blockNumberDeviation;
}
/// @dev Adds the maximum possible value from {_amountADesired _amountBDesired}
/// Makes use of the value interpreter to perform those calculations
function addLiquidity(
address _tokenA,
address _tokenB,
uint256 _amountADesired,
uint256 _amountBDesired,
uint256,
uint256,
address,
uint256
)
external
returns (
uint256,
uint256,
uint256
)
{
__addLiquidity(_tokenA, _tokenB, _amountADesired, _amountBDesired);
}
/// @dev Removes the specified amount of liquidity
/// Returns 50% of the incoming liquidity value on each token.
function removeLiquidity(
address _tokenA,
address _tokenB,
uint256 _liquidity,
uint256,
uint256,
address,
uint256
) public returns (uint256, uint256) {
__removeLiquidity(_tokenA, _tokenB, _liquidity);
}
function swapExactTokensForTokens(
uint256 amountIn,
uint256,
address[] calldata path,
address,
uint256
) external returns (uint256[] memory) {
uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomized(path[0], amountIn, path[1], blockNumberDeviation);
__swapAssets(msg.sender, path[0], amountIn, path[path.length - 1], amountOut);
}
/// @dev We don't calculate any intermediate values here because they aren't actually used
/// Returns the randomized by sender value of the edge path assets
function getAmountsOut(uint256 _amountIn, address[] calldata _path)
external
returns (uint256[] memory amounts_)
{
require(_path.length >= 2, "getAmountsOut: path must be >= 2");
address assetIn = _path[0];
address assetOut = _path[_path.length - 1];
uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomizedBySender(assetIn, _amountIn, assetOut);
amounts_ = new uint256[](_path.length);
amounts_[0] = _amountIn;
amounts_[_path.length - 1] = amountOut;
return amounts_;
}
function addPair(
address[] memory _listOfToken0,
address[] memory _listOfToken1,
address[] memory _listOfPair
) public onlyOwner {
require(
_listOfPair.length == _listOfToken0.length,
"constructor: _listOfPair and _listOfToken0 have an unequal length"
);
require(
_listOfPair.length == _listOfToken1.length,
"constructor: _listOfPair and _listOfToken1 have an unequal length"
);
for (uint256 i; i < _listOfPair.length; i++) {
address token0 = _listOfToken0[i];
address token1 = _listOfToken1[i];
address pair = _listOfPair[i];
assetToAssetToPair[token0][token1] = pair;
assetToAssetToPair[token1][token0] = pair;
}
}
function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner {
blockNumberDeviation = _deviationPct;
}
// PRIVATE FUNCTIONS
/// Avoids stack-too-deep error.
function __addLiquidity(
address _tokenA,
address _tokenB,
uint256 _amountADesired,
uint256 _amountBDesired
) private {
address pair = getPair(_tokenA, _tokenB);
uint256 amountA;
uint256 amountB;
uint256 amountBFromA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(_tokenA, _amountADesired, _tokenB);
uint256 amountAFromB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(_tokenB, _amountBDesired, _tokenA);
if (amountBFromA >= _amountBDesired) {
amountA = amountAFromB;
amountB = _amountBDesired;
} else {
amountA = _amountADesired;
amountB = amountBFromA;
}
uint256 tokenPerLPToken = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(pair, 10**uint256(PRECISION), _tokenA);
// Calculate the inverse rate to know the amount of LPToken to return from a unit of token
uint256 inverseRate = uint256(10**PRECISION).mul(10**PRECISION).div(tokenPerLPToken);
// Total liquidity can be calculated as 2x liquidity from amount A
uint256 totalLiquidity = uint256(2).mul(
amountA.mul(inverseRate).div(uint256(10**PRECISION))
);
require(
ERC20(pair).balanceOf(address(this)) >= totalLiquidity,
"__addLiquidity: Integratee doesn't have enough pair balance to cover the expected amount"
);
address[] memory assetsToIntegratee = new address[](2);
uint256[] memory assetsToIntegrateeAmounts = new uint256[](2);
address[] memory assetsFromIntegratee = new address[](1);
uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1);
assetsToIntegratee[0] = _tokenA;
assetsToIntegrateeAmounts[0] = amountA;
assetsToIntegratee[1] = _tokenB;
assetsToIntegrateeAmounts[1] = amountB;
assetsFromIntegratee[0] = pair;
assetsFromIntegrateeAmounts[0] = totalLiquidity;
__swap(
msg.sender,
assetsToIntegratee,
assetsToIntegrateeAmounts,
assetsFromIntegratee,
assetsFromIntegrateeAmounts
);
}
/// Avoids stack-too-deep error.
function __removeLiquidity(
address _tokenA,
address _tokenB,
uint256 _liquidity
) private {
address pair = assetToAssetToPair[_tokenA][_tokenB];
require(pair != address(0), "__removeLiquidity: this pair doesn't exist");
uint256 amountA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(pair, _liquidity, _tokenA)
.div(uint256(2));
uint256 amountB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(pair, _liquidity, _tokenB)
.div(uint256(2));
address[] memory assetsToIntegratee = new address[](1);
uint256[] memory assetsToIntegrateeAmounts = new uint256[](1);
address[] memory assetsFromIntegratee = new address[](2);
uint256[] memory assetsFromIntegrateeAmounts = new uint256[](2);
assetsToIntegratee[0] = pair;
assetsToIntegrateeAmounts[0] = _liquidity;
assetsFromIntegratee[0] = _tokenA;
assetsFromIntegrateeAmounts[0] = amountA;
assetsFromIntegratee[1] = _tokenB;
assetsFromIntegrateeAmounts[1] = amountB;
require(
ERC20(_tokenA).balanceOf(address(this)) >= amountA,
"__removeLiquidity: Integratee doesn't have enough tokenA balance to cover the expected amount"
);
require(
ERC20(_tokenB).balanceOf(address(this)) >= amountA,
"__removeLiquidity: Integratee doesn't have enough tokenB balance to cover the expected amount"
);
__swap(
msg.sender,
assetsToIntegratee,
assetsToIntegrateeAmounts,
assetsFromIntegratee,
assetsFromIntegrateeAmounts
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @dev By default set to address(0). It is read by UniswapV2PoolTokenValueCalculator: __calcPoolTokenValue
function feeTo() external pure returns (address) {
return address(0);
}
function getCentralizedRateProvider() public view returns (address) {
return CENTRALIZED_RATE_PROVIDER;
}
function getBlockNumberDeviation() public view returns (uint256) {
return blockNumberDeviation;
}
function getPrecision() public pure returns (uint256) {
return PRECISION;
}
function getPair(address _token0, address _token1) public view returns (address) {
return assetToAssetToPair[_token0][_token1];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./MockIntegrateeBase.sol";
abstract contract SimpleMockIntegrateeBase is MockIntegrateeBase {
constructor(
address[] memory _defaultRateAssets,
address[] memory _specialAssets,
uint8[] memory _specialAssetDecimals,
uint256 _ratePrecision
)
public
MockIntegrateeBase(
_defaultRateAssets,
_specialAssets,
_specialAssetDecimals,
_ratePrecision
)
{}
function __getRateAndSwapAssets(
address payable _trader,
address _srcToken,
uint256 _srcAmount,
address _destToken
) internal returns (uint256 destAmount_) {
uint256 actualRate = __getRate(_srcToken, _destToken);
__swapAssets(_trader, _srcToken, _srcAmount, _destToken, actualRate);
return actualRate;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "../../prices/CentralizedRateProvider.sol";
import "../../utils/SwapperBase.sol";
contract MockCTokenBase is ERC20, SwapperBase, Ownable {
address internal immutable TOKEN;
address internal immutable CENTRALIZED_RATE_PROVIDER;
uint256 internal rate;
mapping(address => mapping(address => uint256)) internal _allowances;
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _token,
address _centralizedRateProvider,
uint256 _initialRate
) public ERC20(_name, _symbol) {
_setupDecimals(_decimals);
TOKEN = _token;
CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider;
rate = _initialRate;
}
function approve(address _spender, uint256 _amount) public virtual override returns (bool) {
_allowances[msg.sender][_spender] = _amount;
return true;
}
/// @dev Overriden `allowance` function, give the integratee infinite approval by default
function allowance(address _owner, address _spender) public view override returns (uint256) {
if (_spender == address(this) || _owner == _spender) {
return 2**256 - 1;
} else {
return _allowances[_owner][_spender];
}
}
/// @dev Necessary as this contract doesn't directly inherit from MockToken
function mintFor(address _who, uint256 _amount) external onlyOwner {
_mint(_who, _amount);
}
/// @dev Necessary to allow updates on persistent deployments (e.g Kovan)
function setRate(uint256 _rate) public onlyOwner {
rate = _rate;
}
function transferFrom(
address _sender,
address _recipient,
uint256 _amount
) public virtual override returns (bool) {
_transfer(_sender, _recipient, _amount);
return true;
}
// INTERNAL FUNCTIONS
/// @dev Calculates the cTokenAmount given a tokenAmount
/// Makes use of a inverse rate with the CentralizedRateProvider as a derivative can't be used as quoteAsset
function __calcCTokenAmount(uint256 _tokenAmount) internal returns (uint256 cTokenAmount_) {
uint256 tokenDecimals = ERC20(TOKEN).decimals();
uint256 cTokenDecimals = decimals();
// Result in Token Decimals
uint256 tokenPerCTokenUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(address(this), 10**uint256(cTokenDecimals), TOKEN);
// Result in cToken decimals
uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(cTokenDecimals)).div(
tokenPerCTokenUnit
);
// Amount in token decimals, result in cToken decimals
cTokenAmount_ = _tokenAmount.mul(inverseRate).div(10**tokenDecimals);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @dev Part of ICERC20 token interface
function underlying() public view returns (address) {
return TOKEN;
}
/// @dev Part of ICERC20 token interface.
/// Called from CompoundPriceFeed, returns the actual Rate cToken/Token
function exchangeRateStored() public view returns (uint256) {
return rate;
}
function getCentralizedRateProvider() public view returns (address) {
return CENTRALIZED_RATE_PROVIDER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./MockCTokenBase.sol";
contract MockCTokenIntegratee is MockCTokenBase {
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _token,
address _centralizedRateProvider,
uint256 _initialRate
)
public
MockCTokenBase(_name, _symbol, _decimals, _token, _centralizedRateProvider, _initialRate)
{}
function mint(uint256 _amount) external returns (uint256) {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue(
TOKEN,
_amount,
address(this)
);
__swapAssets(msg.sender, TOKEN, _amount, address(this), destAmount);
return _amount;
}
function redeem(uint256 _amount) external returns (uint256) {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue(
address(this),
_amount,
TOKEN
);
__swapAssets(msg.sender, address(this), _amount, TOKEN, destAmount);
return _amount;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./MockCTokenBase.sol";
contract MockCEtherIntegratee is MockCTokenBase {
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _weth,
address _centralizedRateProvider,
uint256 _initialRate
)
public
MockCTokenBase(_name, _symbol, _decimals, _weth, _centralizedRateProvider, _initialRate)
{}
function mint() external payable {
uint256 amount = msg.value;
uint256 destAmount = __calcCTokenAmount(amount);
__swapAssets(msg.sender, ETH_ADDRESS, amount, address(this), destAmount);
}
function redeem(uint256 _amount) external returns (uint256) {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue(
address(this),
_amount,
TOKEN
);
__swapAssets(msg.sender, address(this), _amount, ETH_ADDRESS, destAmount);
return _amount;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../interfaces/ICurveAddressProvider.sol";
import "../../../../interfaces/ICurveSwapsERC20.sol";
import "../../../../interfaces/ICurveSwapsEther.sol";
import "../../../../interfaces/IWETH.sol";
import "../utils/AdapterBase.sol";
/// @title CurveExchangeAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for swapping assets on Curve <https://www.curve.fi/>
contract CurveExchangeAdapter is AdapterBase {
address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address private immutable ADDRESS_PROVIDER;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _addressProvider,
address _wethToken
) public AdapterBase(_integrationManager) {
ADDRESS_PROVIDER = _addressProvider;
WETH_TOKEN = _wethToken;
}
/// @dev Needed to receive ETH from swap and to unwrap WETH
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "CURVE_EXCHANGE";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid");
(
address pool,
address outgoingAsset,
uint256 outgoingAssetAmount,
address incomingAsset,
uint256 minIncomingAssetAmount
) = __decodeCallArgs(_encodedCallArgs);
require(pool != address(0), "parseAssetsForMethod: No pool address provided");
spendAssets_ = new address[](1);
spendAssets_[0] = outgoingAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = incomingAsset;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Trades assets on Curve
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
function takeOrder(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata
) external onlyIntegrationManager {
(
address pool,
address outgoingAsset,
uint256 outgoingAssetAmount,
address incomingAsset,
uint256 minIncomingAssetAmount
) = __decodeCallArgs(_encodedCallArgs);
address swaps = ICurveAddressProvider(ADDRESS_PROVIDER).get_address(2);
__takeOrder(
_vaultProxy,
swaps,
pool,
outgoingAsset,
outgoingAssetAmount,
incomingAsset,
minIncomingAssetAmount
);
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the take order encoded call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address pool_,
address outgoingAsset_,
uint256 outgoingAssetAmount_,
address incomingAsset_,
uint256 minIncomingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (address, address, uint256, address, uint256));
}
/// @dev Helper to execute takeOrder. Avoids stack-too-deep error.
function __takeOrder(
address _vaultProxy,
address _swaps,
address _pool,
address _outgoingAsset,
uint256 _outgoingAssetAmount,
address _incomingAsset,
uint256 _minIncomingAssetAmount
) private {
if (_outgoingAsset == WETH_TOKEN) {
IWETH(WETH_TOKEN).withdraw(_outgoingAssetAmount);
ICurveSwapsEther(_swaps).exchange{value: _outgoingAssetAmount}(
_pool,
ETH_ADDRESS,
_incomingAsset,
_outgoingAssetAmount,
_minIncomingAssetAmount,
_vaultProxy
);
} else if (_incomingAsset == WETH_TOKEN) {
__approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount);
ICurveSwapsERC20(_swaps).exchange(
_pool,
_outgoingAsset,
ETH_ADDRESS,
_outgoingAssetAmount,
_minIncomingAssetAmount,
address(this)
);
// wrap received ETH and send back to the vault
uint256 receivedAmount = payable(address(this)).balance;
IWETH(payable(WETH_TOKEN)).deposit{value: receivedAmount}();
ERC20(WETH_TOKEN).safeTransfer(_vaultProxy, receivedAmount);
} else {
__approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount);
ICurveSwapsERC20(_swaps).exchange(
_pool,
_outgoingAsset,
_incomingAsset,
_outgoingAssetAmount,
_minIncomingAssetAmount,
_vaultProxy
);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `ADDRESS_PROVIDER` variable
/// @return addressProvider_ The `ADDRESS_PROVIDER` variable value
function getAddressProvider() external view returns (address addressProvider_) {
return ADDRESS_PROVIDER;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveSwapsERC20 Interface
/// @author Enzyme Council <[email protected]>
interface ICurveSwapsERC20 {
function exchange(
address,
address,
address,
uint256,
uint256,
address
) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveSwapsEther Interface
/// @author Enzyme Council <[email protected]>
interface ICurveSwapsEther {
function exchange(
address,
address,
address,
uint256,
uint256,
address
) external payable returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../IDerivativePriceFeed.sol";
import "./SingleUnderlyingDerivativeRegistryMixin.sol";
/// @title PeggedDerivativesPriceFeedBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price feed base for multiple derivatives that are pegged 1:1 to their underlyings,
/// and have the same decimals as their underlying
abstract contract PeggedDerivativesPriceFeedBase is
IDerivativePriceFeed,
SingleUnderlyingDerivativeRegistryMixin
{
constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
address underlying = getUnderlyingForDerivative(_derivative);
require(underlying != address(0), "calcUnderlyingValues: Not a supported derivative");
underlyings_ = new address[](1);
underlyings_[0] = underlying;
underlyingAmounts_ = new uint256[](1);
underlyingAmounts_[0] = _derivativeAmount;
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) external view override returns (bool isSupported_) {
return getUnderlyingForDerivative(_asset) != address(0);
}
/// @dev Provides validation that the derivative and underlying have the same decimals.
/// Can be overrode by the inheriting price feed using super() to implement further validation.
function __validateDerivative(address _derivative, address _underlying)
internal
virtual
override
{
require(
ERC20(_derivative).decimals() == ERC20(_underlying).decimals(),
"__validateDerivative: Unequal decimals"
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../utils/DispatcherOwnerMixin.sol";
/// @title SingleUnderlyingDerivativeRegistryMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice Mixin for derivative price feeds that handle multiple derivatives
/// that each have a single underlying asset
abstract contract SingleUnderlyingDerivativeRegistryMixin is DispatcherOwnerMixin {
event DerivativeAdded(address indexed derivative, address indexed underlying);
event DerivativeRemoved(address indexed derivative);
mapping(address => address) private derivativeToUnderlying;
constructor(address _dispatcher) public DispatcherOwnerMixin(_dispatcher) {}
/// @notice Adds derivatives with corresponding underlyings to the price feed
/// @param _derivatives The derivatives to add
/// @param _underlyings The corresponding underlyings to add
function addDerivatives(address[] memory _derivatives, address[] memory _underlyings)
external
virtual
onlyDispatcherOwner
{
require(_derivatives.length > 0, "addDerivatives: Empty _derivatives");
require(_derivatives.length == _underlyings.length, "addDerivatives: Unequal arrays");
for (uint256 i; i < _derivatives.length; i++) {
require(_derivatives[i] != address(0), "addDerivatives: Empty derivative");
require(_underlyings[i] != address(0), "addDerivatives: Empty underlying");
require(
getUnderlyingForDerivative(_derivatives[i]) == address(0),
"addDerivatives: Value already set"
);
__validateDerivative(_derivatives[i], _underlyings[i]);
derivativeToUnderlying[_derivatives[i]] = _underlyings[i];
emit DerivativeAdded(_derivatives[i], _underlyings[i]);
}
}
/// @notice Removes derivatives from the price feed
/// @param _derivatives The derivatives to remove
function removeDerivatives(address[] memory _derivatives) external onlyDispatcherOwner {
require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives");
for (uint256 i; i < _derivatives.length; i++) {
require(
getUnderlyingForDerivative(_derivatives[i]) != address(0),
"removeDerivatives: Value not set"
);
delete derivativeToUnderlying[_derivatives[i]];
emit DerivativeRemoved(_derivatives[i]);
}
}
/// @dev Optionally allow the inheriting price feed to validate the derivative-underlying pair
function __validateDerivative(address, address) internal virtual {
// UNIMPLEMENTED
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the underlying asset for a given derivative
/// @param _derivative The derivative for which to get the underlying asset
/// @return underlying_ The underlying asset
function getUnderlyingForDerivative(address _derivative)
public
view
returns (address underlying_)
{
return derivativeToUnderlying[_derivative];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../release/infrastructure/price-feeds/derivatives/feeds/utils/PeggedDerivativesPriceFeedBase.sol";
/// @title TestSingleUnderlyingDerivativeRegistry Contract
/// @author Enzyme Council <[email protected]>
/// @notice A test implementation of PeggedDerivativesPriceFeedBase
contract TestPeggedDerivativesPriceFeed is PeggedDerivativesPriceFeedBase {
constructor(address _dispatcher) public PeggedDerivativesPriceFeedBase(_dispatcher) {}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SingleUnderlyingDerivativeRegistryMixin.sol";
/// @title TestSingleUnderlyingDerivativeRegistry Contract
/// @author Enzyme Council <[email protected]>
/// @notice A test implementation of SingleUnderlyingDerivativeRegistryMixin
contract TestSingleUnderlyingDerivativeRegistry is SingleUnderlyingDerivativeRegistryMixin {
constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../interfaces/IAaveProtocolDataProvider.sol";
import "./utils/PeggedDerivativesPriceFeedBase.sol";
/// @title AavePriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for Aave
contract AavePriceFeed is PeggedDerivativesPriceFeedBase {
address private immutable PROTOCOL_DATA_PROVIDER;
constructor(address _dispatcher, address _protocolDataProvider)
public
PeggedDerivativesPriceFeedBase(_dispatcher)
{
PROTOCOL_DATA_PROVIDER = _protocolDataProvider;
}
function __validateDerivative(address _derivative, address _underlying) internal override {
super.__validateDerivative(_derivative, _underlying);
(address aTokenAddress, , ) = IAaveProtocolDataProvider(PROTOCOL_DATA_PROVIDER)
.getReserveTokensAddresses(_underlying);
require(
aTokenAddress == _derivative,
"__validateDerivative: Invalid aToken or token provided"
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `PROTOCOL_DATA_PROVIDER` variable value
/// @return protocolDataProvider_ The `PROTOCOL_DATA_PROVIDER` variable value
function getProtocolDataProvider() external view returns (address protocolDataProvider_) {
return PROTOCOL_DATA_PROVIDER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IAaveProtocolDataProvider interface
/// @author Enzyme Council <[email protected]>
interface IAaveProtocolDataProvider {
function getReserveTokensAddresses(address)
external
view
returns (
address,
address,
address
);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../infrastructure/price-feeds/derivatives/feeds/AavePriceFeed.sol";
import "../../../../interfaces/IAaveLendingPool.sol";
import "../../../../interfaces/IAaveLendingPoolAddressProvider.sol";
import "../utils/AdapterBase.sol";
/// @title AaveAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for Aave Lending <https://aave.com/>
contract AaveAdapter is AdapterBase {
address private immutable AAVE_PRICE_FEED;
address private immutable LENDING_POOL_ADDRESS_PROVIDER;
uint16 private constant REFERRAL_CODE = 158;
constructor(
address _integrationManager,
address _lendingPoolAddressProvider,
address _aavePriceFeed
) public AdapterBase(_integrationManager) {
LENDING_POOL_ADDRESS_PROVIDER = _lendingPoolAddressProvider;
AAVE_PRICE_FEED = _aavePriceFeed;
}
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "AAVE";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == LEND_SELECTOR) {
(address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs);
// Prevent from invalid token/aToken combination
address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken);
require(token != address(0), "parseAssetsForMethod: Unsupported aToken");
spendAssets_ = new address[](1);
spendAssets_[0] = token;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = amount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = aToken;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = amount;
} else if (_selector == REDEEM_SELECTOR) {
(address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs);
// Prevent from invalid token/aToken combination
address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken);
require(token != address(0), "parseAssetsForMethod: Unsupported aToken");
spendAssets_ = new address[](1);
spendAssets_[0] = aToken;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = amount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = token;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = amount;
} else {
revert("parseAssetsForMethod: _selector invalid");
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Lends an amount of a token to AAVE
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata,
bytes calldata _encodedAssetTransferArgs
) external onlyIntegrationManager {
(
,
address[] memory spendAssets,
uint256[] memory spendAssetAmounts,
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER)
.getLendingPool();
__approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]);
IAaveLendingPool(lendingPoolAddress).deposit(
spendAssets[0],
spendAssetAmounts[0],
_vaultProxy,
REFERRAL_CODE
);
}
/// @notice Redeems an amount of aTokens from AAVE
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem(
address _vaultProxy,
bytes calldata,
bytes calldata _encodedAssetTransferArgs
) external onlyIntegrationManager {
(
,
address[] memory spendAssets,
uint256[] memory spendAssetAmounts,
address[] memory incomingAssets
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER)
.getLendingPool();
__approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]);
IAaveLendingPool(lendingPoolAddress).withdraw(
incomingAssets[0],
spendAssetAmounts[0],
_vaultProxy
);
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode callArgs for lend and redeem
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (address aToken, uint256 amount)
{
return abi.decode(_encodedCallArgs, (address, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `AAVE_PRICE_FEED` variable
/// @return aavePriceFeed_ The `AAVE_PRICE_FEED` variable value
function getAavePriceFeed() external view returns (address aavePriceFeed_) {
return AAVE_PRICE_FEED;
}
/// @notice Gets the `LENDING_POOL_ADDRESS_PROVIDER` variable
/// @return lendingPoolAddressProvider_ The `LENDING_POOL_ADDRESS_PROVIDER` variable value
function getLendingPoolAddressProvider()
external
view
returns (address lendingPoolAddressProvider_)
{
return LENDING_POOL_ADDRESS_PROVIDER;
}
/// @notice Gets the `REFERRAL_CODE` variable
/// @return referralCode_ The `REFERRAL_CODE` variable value
function getReferralCode() external pure returns (uint16 referralCode_) {
return REFERRAL_CODE;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IAaveLendingPool interface
/// @author Enzyme Council <[email protected]>
interface IAaveLendingPool {
function deposit(
address,
uint256,
address,
uint16
) external;
function withdraw(
address,
uint256,
address
) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IAaveLendingPoolAddressProvider interface
/// @author Enzyme Council <[email protected]>
interface IAaveLendingPoolAddressProvider {
function getLendingPool() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../core/fund/comptroller/ComptrollerLib.sol";
import "../../../../core/fund/vault/VaultLib.sol";
import "../../../../utils/AddressArrayLib.sol";
import "../utils/AddressListPolicyMixin.sol";
import "./utils/PostCallOnIntegrationValidatePolicyBase.sol";
/// @title AssetWhitelist Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that only allows a configurable whitelist of assets in a fund's holdings
contract AssetWhitelist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin {
using AddressArrayLib for address[];
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Validates and initializes a policy as necessary prior to fund activation
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _vaultProxy The fund's VaultProxy address
function activateForFund(address _comptrollerProxy, address _vaultProxy)
external
override
onlyPolicyManager
{
require(
passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()),
"activateForFund: Non-whitelisted asset detected"
);
}
/// @notice Add the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
address[] memory assets = abi.decode(_encodedSettings, (address[]));
require(
assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()),
"addFundSettings: Must whitelist denominationAsset"
);
__addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[])));
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "ASSET_WHITELIST";
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _assets The assets with which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address[] memory _assets)
public
view
returns (bool isValid_)
{
for (uint256 i; i < _assets.length; i++) {
if (!isInList(_comptrollerProxy, _assets[i])) {
return false;
}
}
return true;
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, incomingAssets);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
/// @title AddressListPolicyMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice An abstract mixin contract for policies that use an address list
abstract contract AddressListPolicyMixin {
using EnumerableSet for EnumerableSet.AddressSet;
event AddressesAdded(address indexed comptrollerProxy, address[] items);
event AddressesRemoved(address indexed comptrollerProxy, address[] items);
mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToList;
// EXTERNAL FUNCTIONS
/// @notice Get all addresses in a fund's list
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @return list_ The addresses in the fund's list
function getList(address _comptrollerProxy) external view returns (address[] memory list_) {
list_ = new address[](comptrollerProxyToList[_comptrollerProxy].length());
for (uint256 i = 0; i < list_.length; i++) {
list_[i] = comptrollerProxyToList[_comptrollerProxy].at(i);
}
return list_;
}
// PUBLIC FUNCTIONS
/// @notice Check if an address is in a fund's list
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _item The address to check against the list
/// @return isInList_ True if the address is in the list
function isInList(address _comptrollerProxy, address _item)
public
view
returns (bool isInList_)
{
return comptrollerProxyToList[_comptrollerProxy].contains(_item);
}
// INTERNAL FUNCTIONS
/// @dev Helper to add addresses to the calling fund's list
function __addToList(address _comptrollerProxy, address[] memory _items) internal {
require(_items.length > 0, "__addToList: No addresses provided");
for (uint256 i = 0; i < _items.length; i++) {
require(
comptrollerProxyToList[_comptrollerProxy].add(_items[i]),
"__addToList: Address already exists in list"
);
}
emit AddressesAdded(_comptrollerProxy, _items);
}
/// @dev Helper to remove addresses from the calling fund's list
function __removeFromList(address _comptrollerProxy, address[] memory _items) internal {
require(_items.length > 0, "__removeFromList: No addresses provided");
for (uint256 i = 0; i < _items.length; i++) {
require(
comptrollerProxyToList[_comptrollerProxy].remove(_items[i]),
"__removeFromList: Address does not exist in list"
);
}
emit AddressesRemoved(_comptrollerProxy, _items);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../core/fund/comptroller/ComptrollerLib.sol";
import "../../../../core/fund/vault/VaultLib.sol";
import "../../../../utils/AddressArrayLib.sol";
import "../utils/AddressListPolicyMixin.sol";
import "./utils/PostCallOnIntegrationValidatePolicyBase.sol";
/// @title AssetBlacklist Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that disallows a configurable blacklist of assets in a fund's holdings
contract AssetBlacklist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin {
using AddressArrayLib for address[];
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Validates and initializes a policy as necessary prior to fund activation
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _vaultProxy The fund's VaultProxy address
function activateForFund(address _comptrollerProxy, address _vaultProxy)
external
override
onlyPolicyManager
{
require(
passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()),
"activateForFund: Blacklisted asset detected"
);
}
/// @notice Add the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
address[] memory assets = abi.decode(_encodedSettings, (address[]));
require(
!assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()),
"addFundSettings: Cannot blacklist denominationAsset"
);
__addToList(_comptrollerProxy, assets);
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "ASSET_BLACKLIST";
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _assets The assets with which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address[] memory _assets)
public
view
returns (bool isValid_)
{
for (uint256 i; i < _assets.length; i++) {
if (isInList(_comptrollerProxy, _assets[i])) {
return false;
}
}
return true;
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, incomingAssets);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/AddressListPolicyMixin.sol";
import "./utils/PreCallOnIntegrationValidatePolicyBase.sol";
/// @title AdapterWhitelist Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that only allows a configurable whitelist of adapters for use by a fund
contract AdapterWhitelist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin {
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Add the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
__addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[])));
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "ADAPTER_WHITELIST";
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _adapter The adapter with which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address _adapter)
public
view
returns (bool isValid_)
{
return isInList(_comptrollerProxy, _adapter);
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(address adapter, ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, adapter);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/PolicyBase.sol";
/// @title CallOnIntegrationPreValidatePolicyMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract for policies that only implement the PreCallOnIntegration policy hook
abstract contract PreCallOnIntegrationValidatePolicyBase is PolicyBase {
/// @notice Gets the implemented PolicyHooks for a policy
/// @return implementedHooks_ The implemented PolicyHooks
function implementedHooks()
external
view
override
returns (IPolicyManager.PolicyHook[] memory implementedHooks_)
{
implementedHooks_ = new IPolicyManager.PolicyHook[](1);
implementedHooks_[0] = IPolicyManager.PolicyHook.PreCallOnIntegration;
return implementedHooks_;
}
/// @notice Helper to decode rule arguments
function __decodeRuleArgs(bytes memory _encodedRuleArgs)
internal
pure
returns (address adapter_, bytes4 selector_)
{
return abi.decode(_encodedRuleArgs, (address, bytes4));
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../utils/FundDeployerOwnerMixin.sol";
import "./utils/PreCallOnIntegrationValidatePolicyBase.sol";
/// @title GuaranteedRedemption Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that guarantees that shares will either be continuously redeemable or
/// redeemable within a predictable daily window by preventing trading during a configurable daily period
contract GuaranteedRedemption is PreCallOnIntegrationValidatePolicyBase, FundDeployerOwnerMixin {
using SafeMath for uint256;
event AdapterAdded(address adapter);
event AdapterRemoved(address adapter);
event FundSettingsSet(
address indexed comptrollerProxy,
uint256 startTimestamp,
uint256 duration
);
event RedemptionWindowBufferSet(uint256 prevBuffer, uint256 nextBuffer);
struct RedemptionWindow {
uint256 startTimestamp;
uint256 duration;
}
uint256 private constant ONE_DAY = 24 * 60 * 60;
mapping(address => bool) private adapterToCanBlockRedemption;
mapping(address => RedemptionWindow) private comptrollerProxyToRedemptionWindow;
uint256 private redemptionWindowBuffer;
constructor(
address _policyManager,
address _fundDeployer,
uint256 _redemptionWindowBuffer,
address[] memory _redemptionBlockingAdapters
) public PolicyBase(_policyManager) FundDeployerOwnerMixin(_fundDeployer) {
redemptionWindowBuffer = _redemptionWindowBuffer;
__addRedemptionBlockingAdapters(_redemptionBlockingAdapters);
}
// EXTERNAL FUNCTIONS
/// @notice Add the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
(uint256 startTimestamp, uint256 duration) = abi.decode(
_encodedSettings,
(uint256, uint256)
);
if (startTimestamp == 0) {
require(duration == 0, "addFundSettings: duration must be 0 if startTimestamp is 0");
return;
}
// Use 23 hours instead of 1 day to allow up to 1 hr of redemptionWindowBuffer
require(
duration > 0 && duration <= 23 hours,
"addFundSettings: duration must be between 1 second and 23 hours"
);
comptrollerProxyToRedemptionWindow[_comptrollerProxy].startTimestamp = startTimestamp;
comptrollerProxyToRedemptionWindow[_comptrollerProxy].duration = duration;
emit FundSettingsSet(_comptrollerProxy, startTimestamp, duration);
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "GUARANTEED_REDEMPTION";
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _adapter The adapter for which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address _adapter)
public
view
returns (bool isValid_)
{
if (!adapterCanBlockRedemption(_adapter)) {
return true;
}
RedemptionWindow memory redemptionWindow
= comptrollerProxyToRedemptionWindow[_comptrollerProxy];
// If no RedemptionWindow is set, the fund can never use redemption-blocking adapters
if (redemptionWindow.startTimestamp == 0) {
return false;
}
uint256 latestRedemptionWindowStart = calcLatestRedemptionWindowStart(
redemptionWindow.startTimestamp
);
// A fund can't trade during its redemption window, nor in the buffer beforehand.
// The lower bound is only relevant when the startTimestamp is in the future,
// so we check it last.
if (
block.timestamp >= latestRedemptionWindowStart.add(redemptionWindow.duration) ||
block.timestamp <= latestRedemptionWindowStart.sub(redemptionWindowBuffer)
) {
return true;
}
return false;
}
/// @notice Sets a new value for the redemptionWindowBuffer variable
/// @param _nextRedemptionWindowBuffer The number of seconds for the redemptionWindowBuffer
/// @dev The redemptionWindowBuffer is added to the beginning of the redemption window,
/// and should always be >= the longest potential block on redemption amongst all adapters.
/// (e.g., Synthetix blocks token transfers during a timelock after trading synths)
function setRedemptionWindowBuffer(uint256 _nextRedemptionWindowBuffer)
external
onlyFundDeployerOwner
{
uint256 prevRedemptionWindowBuffer = redemptionWindowBuffer;
require(
_nextRedemptionWindowBuffer != prevRedemptionWindowBuffer,
"setRedemptionWindowBuffer: Value already set"
);
redemptionWindowBuffer = _nextRedemptionWindowBuffer;
emit RedemptionWindowBufferSet(prevRedemptionWindowBuffer, _nextRedemptionWindowBuffer);
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(address adapter, ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, adapter);
}
// PUBLIC FUNCTIONS
/// @notice Calculates the start of the most recent redemption window
/// @param _startTimestamp The initial startTimestamp for the redemption window
/// @return latestRedemptionWindowStart_ The starting timestamp of the most recent redemption window
function calcLatestRedemptionWindowStart(uint256 _startTimestamp)
public
view
returns (uint256 latestRedemptionWindowStart_)
{
if (block.timestamp <= _startTimestamp) {
return _startTimestamp;
}
uint256 timeSinceStartTimestamp = block.timestamp.sub(_startTimestamp);
uint256 timeSincePeriodStart = timeSinceStartTimestamp.mod(ONE_DAY);
return block.timestamp.sub(timeSincePeriodStart);
}
///////////////////////////////////////////
// REDEMPTION-BLOCKING ADAPTERS REGISTRY //
///////////////////////////////////////////
/// @notice Add adapters which can block shares redemption
/// @param _adapters The addresses of adapters to be added
function addRedemptionBlockingAdapters(address[] calldata _adapters)
external
onlyFundDeployerOwner
{
require(
_adapters.length > 0,
"__addRedemptionBlockingAdapters: _adapters cannot be empty"
);
__addRedemptionBlockingAdapters(_adapters);
}
/// @notice Remove adapters which can block shares redemption
/// @param _adapters The addresses of adapters to be removed
function removeRedemptionBlockingAdapters(address[] calldata _adapters)
external
onlyFundDeployerOwner
{
require(
_adapters.length > 0,
"removeRedemptionBlockingAdapters: _adapters cannot be empty"
);
for (uint256 i; i < _adapters.length; i++) {
require(
adapterCanBlockRedemption(_adapters[i]),
"removeRedemptionBlockingAdapters: adapter is not added"
);
adapterToCanBlockRedemption[_adapters[i]] = false;
emit AdapterRemoved(_adapters[i]);
}
}
/// @dev Helper to mark adapters that can block shares redemption
function __addRedemptionBlockingAdapters(address[] memory _adapters) private {
for (uint256 i; i < _adapters.length; i++) {
require(
_adapters[i] != address(0),
"__addRedemptionBlockingAdapters: adapter cannot be empty"
);
require(
!adapterCanBlockRedemption(_adapters[i]),
"__addRedemptionBlockingAdapters: adapter already added"
);
adapterToCanBlockRedemption[_adapters[i]] = true;
emit AdapterAdded(_adapters[i]);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `redemptionWindowBuffer` variable
/// @return redemptionWindowBuffer_ The `redemptionWindowBuffer` variable value
function getRedemptionWindowBuffer() external view returns (uint256 redemptionWindowBuffer_) {
return redemptionWindowBuffer;
}
/// @notice Gets the RedemptionWindow settings for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return redemptionWindow_ The RedemptionWindow settings
function getRedemptionWindowForFund(address _comptrollerProxy)
external
view
returns (RedemptionWindow memory redemptionWindow_)
{
return comptrollerProxyToRedemptionWindow[_comptrollerProxy];
}
/// @notice Checks whether an adapter can block shares redemption
/// @param _adapter The address of the adapter to check
/// @return canBlockRedemption_ True if the adapter can block shares redemption
function adapterCanBlockRedemption(address _adapter)
public
view
returns (bool canBlockRedemption_)
{
return adapterToCanBlockRedemption[_adapter];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/AddressListPolicyMixin.sol";
import "./utils/PreCallOnIntegrationValidatePolicyBase.sol";
/// @title AdapterBlacklist Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that disallows a configurable blacklist of adapters from use by a fund
contract AdapterBlacklist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin {
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Add the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
__addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[])));
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "ADAPTER_BLACKLIST";
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _adapter The adapter with which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address _adapter)
public
view
returns (bool isValid_)
{
return !isInList(_comptrollerProxy, _adapter);
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(address adapter, ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, adapter);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/AddressListPolicyMixin.sol";
import "./utils/PreBuySharesValidatePolicyBase.sol";
/// @title InvestorWhitelist Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that only allows a configurable whitelist of investors to buy shares in a fund
contract InvestorWhitelist is PreBuySharesValidatePolicyBase, AddressListPolicyMixin {
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Adds the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
__updateList(_comptrollerProxy, _encodedSettings);
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "INVESTOR_WHITELIST";
}
/// @notice Updates the policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function updateFundSettings(
address _comptrollerProxy,
address,
bytes calldata _encodedSettings
) external override onlyPolicyManager {
__updateList(_comptrollerProxy, _encodedSettings);
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _investor The investor for which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address _investor)
public
view
returns (bool isValid_)
{
return isInList(_comptrollerProxy, _investor);
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(address buyer, , , ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, buyer);
}
/// @dev Helper to update the investor whitelist by adding and/or removing addresses
function __updateList(address _comptrollerProxy, bytes memory _settingsData) private {
(address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode(
_settingsData,
(address[], address[])
);
// If an address is in both add and remove arrays, they will not be in the final list.
// We do not check for uniqueness between the two arrays for efficiency.
if (itemsToAdd.length > 0) {
__addToList(_comptrollerProxy, itemsToAdd);
}
if (itemsToRemove.length > 0) {
__removeFromList(_comptrollerProxy, itemsToRemove);
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/PolicyBase.sol";
/// @title BuySharesPolicyMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract for policies that only implement the PreBuyShares policy hook
abstract contract PreBuySharesValidatePolicyBase is PolicyBase {
/// @notice Gets the implemented PolicyHooks for a policy
/// @return implementedHooks_ The implemented PolicyHooks
function implementedHooks()
external
view
override
returns (IPolicyManager.PolicyHook[] memory implementedHooks_)
{
implementedHooks_ = new IPolicyManager.PolicyHook[](1);
implementedHooks_[0] = IPolicyManager.PolicyHook.PreBuyShares;
return implementedHooks_;
}
/// @notice Helper to decode rule arguments
function __decodeRuleArgs(bytes memory _encodedArgs)
internal
pure
returns (
address buyer_,
uint256 investmentAmount_,
uint256 minSharesQuantity_,
uint256 gav_
)
{
return abi.decode(_encodedArgs, (address, uint256, uint256, uint256));
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./utils/PreBuySharesValidatePolicyBase.sol";
/// @title MinMaxInvestment Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that restricts the amount of the fund's denomination asset that a user can
/// send in a single call to buy shares in a fund
contract MinMaxInvestment is PreBuySharesValidatePolicyBase {
event FundSettingsSet(
address indexed comptrollerProxy,
uint256 minInvestmentAmount,
uint256 maxInvestmentAmount
);
struct FundSettings {
uint256 minInvestmentAmount;
uint256 maxInvestmentAmount;
}
mapping(address => FundSettings) private comptrollerProxyToFundSettings;
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Adds the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
__setFundSettings(_comptrollerProxy, _encodedSettings);
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "MIN_MAX_INVESTMENT";
}
/// @notice Updates the policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function updateFundSettings(
address _comptrollerProxy,
address,
bytes calldata _encodedSettings
) external override onlyPolicyManager {
__setFundSettings(_comptrollerProxy, _encodedSettings);
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _investmentAmount The investment amount for which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, uint256 _investmentAmount)
public
view
returns (bool isValid_)
{
uint256 minInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy]
.minInvestmentAmount;
uint256 maxInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy]
.maxInvestmentAmount;
// Both minInvestmentAmount and maxInvestmentAmount can be 0 in order to close the fund
// temporarily
if (minInvestmentAmount == 0) {
return _investmentAmount <= maxInvestmentAmount;
} else if (maxInvestmentAmount == 0) {
return _investmentAmount >= minInvestmentAmount;
}
return
_investmentAmount >= minInvestmentAmount && _investmentAmount <= maxInvestmentAmount;
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(, uint256 investmentAmount, , ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, investmentAmount);
}
/// @dev Helper to set the policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function __setFundSettings(address _comptrollerProxy, bytes memory _encodedSettings) private {
(uint256 minInvestmentAmount, uint256 maxInvestmentAmount) = abi.decode(
_encodedSettings,
(uint256, uint256)
);
require(
maxInvestmentAmount == 0 || minInvestmentAmount < maxInvestmentAmount,
"__setFundSettings: minInvestmentAmount must be less than maxInvestmentAmount"
);
comptrollerProxyToFundSettings[_comptrollerProxy]
.minInvestmentAmount = minInvestmentAmount;
comptrollerProxyToFundSettings[_comptrollerProxy]
.maxInvestmentAmount = maxInvestmentAmount;
emit FundSettingsSet(_comptrollerProxy, minInvestmentAmount, maxInvestmentAmount);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the min and max investment amount for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return fundSettings_ The fund settings
function getFundSettings(address _comptrollerProxy)
external
view
returns (FundSettings memory fundSettings_)
{
return comptrollerProxyToFundSettings[_comptrollerProxy];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/AddressListPolicyMixin.sol";
import "./utils/BuySharesSetupPolicyBase.sol";
/// @title BuySharesCallerWhitelist Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that only allows a configurable whitelist of buyShares callers for a fund
contract BuySharesCallerWhitelist is BuySharesSetupPolicyBase, AddressListPolicyMixin {
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Adds the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
__updateList(_comptrollerProxy, _encodedSettings);
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "BUY_SHARES_CALLER_WHITELIST";
}
/// @notice Updates the policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function updateFundSettings(
address _comptrollerProxy,
address,
bytes calldata _encodedSettings
) external override onlyPolicyManager {
__updateList(_comptrollerProxy, _encodedSettings);
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _buySharesCaller The buyShares caller for which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address _buySharesCaller)
public
view
returns (bool isValid_)
{
return isInList(_comptrollerProxy, _buySharesCaller);
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(address caller, , ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, caller);
}
/// @dev Helper to update the whitelist by adding and/or removing addresses
function __updateList(address _comptrollerProxy, bytes memory _settingsData) private {
(address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode(
_settingsData,
(address[], address[])
);
// If an address is in both add and remove arrays, they will not be in the final list.
// We do not check for uniqueness between the two arrays for efficiency.
if (itemsToAdd.length > 0) {
__addToList(_comptrollerProxy, itemsToAdd);
}
if (itemsToRemove.length > 0) {
__removeFromList(_comptrollerProxy, itemsToRemove);
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/PolicyBase.sol";
/// @title BuySharesSetupPolicyBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract for policies that only implement the BuySharesSetup policy hook
abstract contract BuySharesSetupPolicyBase is PolicyBase {
/// @notice Gets the implemented PolicyHooks for a policy
/// @return implementedHooks_ The implemented PolicyHooks
function implementedHooks()
external
view
override
returns (IPolicyManager.PolicyHook[] memory implementedHooks_)
{
implementedHooks_ = new IPolicyManager.PolicyHook[](1);
implementedHooks_[0] = IPolicyManager.PolicyHook.BuySharesSetup;
return implementedHooks_;
}
/// @notice Helper to decode rule arguments
function __decodeRuleArgs(bytes memory _encodedArgs)
internal
pure
returns (
address caller_,
uint256[] memory investmentAmounts_,
uint256 gav_
)
{
return abi.decode(_encodedArgs, (address, uint256[], uint256));
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../core/fund/vault/VaultLib.sol";
import "../utils/AdapterBase.sol";
/// @title TrackedAssetsAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter to add tracked assets to a fund (useful e.g. to handle token airdrops)
contract TrackedAssetsAdapter is AdapterBase {
constructor(address _integrationManager) public AdapterBase(_integrationManager) {}
/// @notice Add multiple assets to the Vault's list of tracked assets
/// @dev No need to perform any validation or implement any logic
function addTrackedAssets(
address,
bytes calldata,
bytes calldata
) external view {}
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "TRACKED_ASSETS";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
require(
_selector == ADD_TRACKED_ASSETS_SELECTOR,
"parseAssetsForMethod: _selector invalid"
);
incomingAssets_ = __decodeCallArgs(_encodedCallArgs);
minIncomingAssetAmounts_ = new uint256[](incomingAssets_.length);
for (uint256 i; i < minIncomingAssetAmounts_.length; i++) {
minIncomingAssetAmounts_[i] = 1;
}
return (
spendAssetsHandleType_,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the encoded call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (address[] memory incomingAssets_)
{
return abi.decode(_encodedCallArgs, (address[]));
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./utils/ProxiableVaultLib.sol";
/// @title VaultProxy Contract
/// @author Enzyme Council <[email protected]>
/// @notice A proxy contract for all VaultProxy instances, slightly modified from EIP-1822
/// @dev Adapted from the recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12,
/// and using the EIP-1967 storage slot for the proxiable implementation.
/// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is
/// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"
/// See: https://eips.ethereum.org/EIPS/eip-1822
contract VaultProxy {
constructor(bytes memory _constructData, address _vaultLib) public {
// "0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5" corresponds to
// `bytes32(keccak256('mln.proxiable.vaultlib'))`
require(
bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) ==
ProxiableVaultLib(_vaultLib).proxiableUUID(),
"constructor: _vaultLib not compatible"
);
assembly {
// solium-disable-line
sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _vaultLib)
}
(bool success, bytes memory returnData) = _vaultLib.delegatecall(_constructData); // solium-disable-line
require(success, string(returnData));
}
fallback() external payable {
assembly {
// solium-disable-line
let contractLogic := sload(
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc
)
calldatacopy(0x0, 0x0, calldatasize())
let success := delegatecall(
sub(gas(), 10000),
contractLogic,
0x0,
calldatasize(),
0,
0
)
let retSz := returndatasize()
returndatacopy(0, 0, retSz)
switch success
case 0 {
revert(0, retSz)
}
default {
return(0, retSz)
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/IMigrationHookHandler.sol";
import "../utils/IMigratableVault.sol";
import "../vault/VaultProxy.sol";
import "./IDispatcher.sol";
/// @title Dispatcher Contract
/// @author Enzyme Council <[email protected]>
/// @notice The top-level contract linking multiple releases.
/// It handles the deployment of new VaultProxy instances,
/// and the regulation of fund migration from a previous release to the current one.
/// It can also be referred to for access-control based on this contract's owner.
/// @dev DO NOT EDIT CONTRACT
contract Dispatcher is IDispatcher {
event CurrentFundDeployerSet(address prevFundDeployer, address nextFundDeployer);
event MigrationCancelled(
address indexed vaultProxy,
address indexed prevFundDeployer,
address indexed nextFundDeployer,
address nextVaultAccessor,
address nextVaultLib,
uint256 executableTimestamp
);
event MigrationExecuted(
address indexed vaultProxy,
address indexed prevFundDeployer,
address indexed nextFundDeployer,
address nextVaultAccessor,
address nextVaultLib,
uint256 executableTimestamp
);
event MigrationSignaled(
address indexed vaultProxy,
address indexed prevFundDeployer,
address indexed nextFundDeployer,
address nextVaultAccessor,
address nextVaultLib,
uint256 executableTimestamp
);
event MigrationTimelockSet(uint256 prevTimelock, uint256 nextTimelock);
event NominatedOwnerSet(address indexed nominatedOwner);
event NominatedOwnerRemoved(address indexed nominatedOwner);
event OwnershipTransferred(address indexed prevOwner, address indexed nextOwner);
event MigrationInCancelHookFailed(
bytes failureReturnData,
address indexed vaultProxy,
address indexed prevFundDeployer,
address indexed nextFundDeployer,
address nextVaultAccessor,
address nextVaultLib
);
event MigrationOutHookFailed(
bytes failureReturnData,
IMigrationHookHandler.MigrationOutHook hook,
address indexed vaultProxy,
address indexed prevFundDeployer,
address indexed nextFundDeployer,
address nextVaultAccessor,
address nextVaultLib
);
event SharesTokenSymbolSet(string _nextSymbol);
event VaultProxyDeployed(
address indexed fundDeployer,
address indexed owner,
address vaultProxy,
address indexed vaultLib,
address vaultAccessor,
string fundName
);
struct MigrationRequest {
address nextFundDeployer;
address nextVaultAccessor;
address nextVaultLib;
uint256 executableTimestamp;
}
address private currentFundDeployer;
address private nominatedOwner;
address private owner;
uint256 private migrationTimelock;
string private sharesTokenSymbol;
mapping(address => address) private vaultProxyToFundDeployer;
mapping(address => MigrationRequest) private vaultProxyToMigrationRequest;
modifier onlyCurrentFundDeployer() {
require(
msg.sender == currentFundDeployer,
"Only the current FundDeployer can call this function"
);
_;
}
modifier onlyOwner() {
require(msg.sender == owner, "Only the contract owner can call this function");
_;
}
constructor() public {
migrationTimelock = 2 days;
owner = msg.sender;
sharesTokenSymbol = "ENZF";
}
/////////////
// GENERAL //
/////////////
/// @notice Sets a new `symbol` value for VaultProxy instances
/// @param _nextSymbol The symbol value to set
function setSharesTokenSymbol(string calldata _nextSymbol) external override onlyOwner {
sharesTokenSymbol = _nextSymbol;
emit SharesTokenSymbolSet(_nextSymbol);
}
////////////////////
// ACCESS CONTROL //
////////////////////
/// @notice Claim ownership of the contract
function claimOwnership() external override {
address nextOwner = nominatedOwner;
require(
msg.sender == nextOwner,
"claimOwnership: Only the nominatedOwner can call this function"
);
delete nominatedOwner;
address prevOwner = owner;
owner = nextOwner;
emit OwnershipTransferred(prevOwner, nextOwner);
}
/// @notice Revoke the nomination of a new contract owner
function removeNominatedOwner() external override onlyOwner {
address removedNominatedOwner = nominatedOwner;
require(
removedNominatedOwner != address(0),
"removeNominatedOwner: There is no nominated owner"
);
delete nominatedOwner;
emit NominatedOwnerRemoved(removedNominatedOwner);
}
/// @notice Set a new FundDeployer for use within the contract
/// @param _nextFundDeployer The address of the FundDeployer contract
function setCurrentFundDeployer(address _nextFundDeployer) external override onlyOwner {
require(
_nextFundDeployer != address(0),
"setCurrentFundDeployer: _nextFundDeployer cannot be empty"
);
require(
__isContract(_nextFundDeployer),
"setCurrentFundDeployer: Non-contract _nextFundDeployer"
);
address prevFundDeployer = currentFundDeployer;
require(
_nextFundDeployer != prevFundDeployer,
"setCurrentFundDeployer: _nextFundDeployer is already currentFundDeployer"
);
currentFundDeployer = _nextFundDeployer;
emit CurrentFundDeployerSet(prevFundDeployer, _nextFundDeployer);
}
/// @notice Nominate a new contract owner
/// @param _nextNominatedOwner The account to nominate
/// @dev Does not prohibit overwriting the current nominatedOwner
function setNominatedOwner(address _nextNominatedOwner) external override onlyOwner {
require(
_nextNominatedOwner != address(0),
"setNominatedOwner: _nextNominatedOwner cannot be empty"
);
require(
_nextNominatedOwner != owner,
"setNominatedOwner: _nextNominatedOwner is already the owner"
);
require(
_nextNominatedOwner != nominatedOwner,
"setNominatedOwner: _nextNominatedOwner is already nominated"
);
nominatedOwner = _nextNominatedOwner;
emit NominatedOwnerSet(_nextNominatedOwner);
}
/// @dev Helper to check whether an address is a deployed contract
function __isContract(address _who) private view returns (bool isContract_) {
uint256 size;
assembly {
size := extcodesize(_who)
}
return size > 0;
}
////////////////
// DEPLOYMENT //
////////////////
/// @notice Deploys a VaultProxy
/// @param _vaultLib The VaultLib library with which to instantiate the VaultProxy
/// @param _owner The account to set as the VaultProxy's owner
/// @param _vaultAccessor The account to set as the VaultProxy's permissioned accessor
/// @param _fundName The name of the fund
/// @dev Input validation should be handled by the VaultProxy during deployment
function deployVaultProxy(
address _vaultLib,
address _owner,
address _vaultAccessor,
string calldata _fundName
) external override onlyCurrentFundDeployer returns (address vaultProxy_) {
require(__isContract(_vaultAccessor), "deployVaultProxy: Non-contract _vaultAccessor");
bytes memory constructData = abi.encodeWithSelector(
IMigratableVault.init.selector,
_owner,
_vaultAccessor,
_fundName
);
vaultProxy_ = address(new VaultProxy(constructData, _vaultLib));
address fundDeployer = msg.sender;
vaultProxyToFundDeployer[vaultProxy_] = fundDeployer;
emit VaultProxyDeployed(
fundDeployer,
_owner,
vaultProxy_,
_vaultLib,
_vaultAccessor,
_fundName
);
return vaultProxy_;
}
////////////////
// MIGRATIONS //
////////////////
/// @notice Cancels a pending migration request
/// @param _vaultProxy The VaultProxy contract for which to cancel the migration request
/// @param _bypassFailure True if a failure in either migration hook should be ignored
/// @dev Because this function must also be callable by a permissioned migrator, it has an
/// extra migration hook to the nextFundDeployer for the case where cancelMigration()
/// is called directly (rather than via the nextFundDeployer).
function cancelMigration(address _vaultProxy, bool _bypassFailure) external override {
MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy];
address nextFundDeployer = request.nextFundDeployer;
require(nextFundDeployer != address(0), "cancelMigration: No migration request exists");
// TODO: confirm that if canMigrate() does not exist but the caller is a valid FundDeployer, this still works.
require(
msg.sender == nextFundDeployer || IMigratableVault(_vaultProxy).canMigrate(msg.sender),
"cancelMigration: Not an allowed caller"
);
address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy];
address nextVaultAccessor = request.nextVaultAccessor;
address nextVaultLib = request.nextVaultLib;
uint256 executableTimestamp = request.executableTimestamp;
delete vaultProxyToMigrationRequest[_vaultProxy];
__invokeMigrationOutHook(
IMigrationHookHandler.MigrationOutHook.PostCancel,
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
nextVaultAccessor,
nextVaultLib,
_bypassFailure
);
__invokeMigrationInCancelHook(
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
nextVaultAccessor,
nextVaultLib,
_bypassFailure
);
emit MigrationCancelled(
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
nextVaultAccessor,
nextVaultLib,
executableTimestamp
);
}
/// @notice Executes a pending migration request
/// @param _vaultProxy The VaultProxy contract for which to execute the migration request
/// @param _bypassFailure True if a failure in either migration hook should be ignored
function executeMigration(address _vaultProxy, bool _bypassFailure) external override {
MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy];
address nextFundDeployer = request.nextFundDeployer;
require(
nextFundDeployer != address(0),
"executeMigration: No migration request exists for _vaultProxy"
);
require(
msg.sender == nextFundDeployer,
"executeMigration: Only the target FundDeployer can call this function"
);
require(
nextFundDeployer == currentFundDeployer,
"executeMigration: The target FundDeployer is no longer the current FundDeployer"
);
uint256 executableTimestamp = request.executableTimestamp;
require(
block.timestamp >= executableTimestamp,
"executeMigration: The migration timelock has not elapsed"
);
address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy];
address nextVaultAccessor = request.nextVaultAccessor;
address nextVaultLib = request.nextVaultLib;
__invokeMigrationOutHook(
IMigrationHookHandler.MigrationOutHook.PreMigrate,
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
nextVaultAccessor,
nextVaultLib,
_bypassFailure
);
// Upgrade the VaultProxy to a new VaultLib and update the accessor via the new VaultLib
IMigratableVault(_vaultProxy).setVaultLib(nextVaultLib);
IMigratableVault(_vaultProxy).setAccessor(nextVaultAccessor);
// Update the FundDeployer that migrated the VaultProxy
vaultProxyToFundDeployer[_vaultProxy] = nextFundDeployer;
// Remove the migration request
delete vaultProxyToMigrationRequest[_vaultProxy];
__invokeMigrationOutHook(
IMigrationHookHandler.MigrationOutHook.PostMigrate,
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
nextVaultAccessor,
nextVaultLib,
_bypassFailure
);
emit MigrationExecuted(
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
nextVaultAccessor,
nextVaultLib,
executableTimestamp
);
}
/// @notice Sets a new migration timelock
/// @param _nextTimelock The number of seconds for the new timelock
function setMigrationTimelock(uint256 _nextTimelock) external override onlyOwner {
uint256 prevTimelock = migrationTimelock;
require(
_nextTimelock != prevTimelock,
"setMigrationTimelock: _nextTimelock is the current timelock"
);
migrationTimelock = _nextTimelock;
emit MigrationTimelockSet(prevTimelock, _nextTimelock);
}
/// @notice Signals a migration by creating a migration request
/// @param _vaultProxy The VaultProxy contract for which to signal migration
/// @param _nextVaultAccessor The account that will be the next `accessor` on the VaultProxy
/// @param _nextVaultLib The next VaultLib library contract address to set on the VaultProxy
/// @param _bypassFailure True if a failure in either migration hook should be ignored
function signalMigration(
address _vaultProxy,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) external override onlyCurrentFundDeployer {
require(
__isContract(_nextVaultAccessor),
"signalMigration: Non-contract _nextVaultAccessor"
);
address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy];
require(prevFundDeployer != address(0), "signalMigration: _vaultProxy does not exist");
address nextFundDeployer = msg.sender;
require(
nextFundDeployer != prevFundDeployer,
"signalMigration: Can only migrate to a new FundDeployer"
);
__invokeMigrationOutHook(
IMigrationHookHandler.MigrationOutHook.PreSignal,
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
_nextVaultAccessor,
_nextVaultLib,
_bypassFailure
);
uint256 executableTimestamp = block.timestamp + migrationTimelock;
vaultProxyToMigrationRequest[_vaultProxy] = MigrationRequest({
nextFundDeployer: nextFundDeployer,
nextVaultAccessor: _nextVaultAccessor,
nextVaultLib: _nextVaultLib,
executableTimestamp: executableTimestamp
});
__invokeMigrationOutHook(
IMigrationHookHandler.MigrationOutHook.PostSignal,
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
_nextVaultAccessor,
_nextVaultLib,
_bypassFailure
);
emit MigrationSignaled(
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
_nextVaultAccessor,
_nextVaultLib,
executableTimestamp
);
}
/// @dev Helper to invoke a MigrationInCancelHook on the next FundDeployer being "migrated in" to,
/// which can optionally be implemented on the FundDeployer
function __invokeMigrationInCancelHook(
address _vaultProxy,
address _prevFundDeployer,
address _nextFundDeployer,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) private {
(bool success, bytes memory returnData) = _nextFundDeployer.call(
abi.encodeWithSelector(
IMigrationHookHandler.invokeMigrationInCancelHook.selector,
_vaultProxy,
_prevFundDeployer,
_nextVaultAccessor,
_nextVaultLib
)
);
if (!success) {
require(
_bypassFailure,
string(abi.encodePacked("MigrationOutCancelHook: ", returnData))
);
emit MigrationInCancelHookFailed(
returnData,
_vaultProxy,
_prevFundDeployer,
_nextFundDeployer,
_nextVaultAccessor,
_nextVaultLib
);
}
}
/// @dev Helper to invoke a IMigrationHookHandler.MigrationOutHook on the previous FundDeployer being "migrated out" of,
/// which can optionally be implemented on the FundDeployer
function __invokeMigrationOutHook(
IMigrationHookHandler.MigrationOutHook _hook,
address _vaultProxy,
address _prevFundDeployer,
address _nextFundDeployer,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) private {
(bool success, bytes memory returnData) = _prevFundDeployer.call(
abi.encodeWithSelector(
IMigrationHookHandler.invokeMigrationOutHook.selector,
_hook,
_vaultProxy,
_nextFundDeployer,
_nextVaultAccessor,
_nextVaultLib
)
);
if (!success) {
require(
_bypassFailure,
string(abi.encodePacked(__migrationOutHookFailureReasonPrefix(_hook), returnData))
);
emit MigrationOutHookFailed(
returnData,
_hook,
_vaultProxy,
_prevFundDeployer,
_nextFundDeployer,
_nextVaultAccessor,
_nextVaultLib
);
}
}
/// @dev Helper to return a revert reason string prefix for a given MigrationOutHook
function __migrationOutHookFailureReasonPrefix(IMigrationHookHandler.MigrationOutHook _hook)
private
pure
returns (string memory failureReasonPrefix_)
{
if (_hook == IMigrationHookHandler.MigrationOutHook.PreSignal) {
return "MigrationOutHook.PreSignal: ";
}
if (_hook == IMigrationHookHandler.MigrationOutHook.PostSignal) {
return "MigrationOutHook.PostSignal: ";
}
if (_hook == IMigrationHookHandler.MigrationOutHook.PreMigrate) {
return "MigrationOutHook.PreMigrate: ";
}
if (_hook == IMigrationHookHandler.MigrationOutHook.PostMigrate) {
return "MigrationOutHook.PostMigrate: ";
}
if (_hook == IMigrationHookHandler.MigrationOutHook.PostCancel) {
return "MigrationOutHook.PostCancel: ";
}
return "";
}
///////////////////
// STATE GETTERS //
///////////////////
// Provides several potentially helpful getters that are not strictly necessary
/// @notice Gets the current FundDeployer that is allowed to deploy and migrate funds
/// @return currentFundDeployer_ The current FundDeployer contract address
function getCurrentFundDeployer()
external
view
override
returns (address currentFundDeployer_)
{
return currentFundDeployer;
}
/// @notice Gets the FundDeployer with which a given VaultProxy is associated
/// @param _vaultProxy The VaultProxy instance
/// @return fundDeployer_ The FundDeployer contract address
function getFundDeployerForVaultProxy(address _vaultProxy)
external
view
override
returns (address fundDeployer_)
{
return vaultProxyToFundDeployer[_vaultProxy];
}
/// @notice Gets the details of a pending migration request for a given VaultProxy
/// @param _vaultProxy The VaultProxy instance
/// @return nextFundDeployer_ The FundDeployer contract address from which the migration
/// request was made
/// @return nextVaultAccessor_ The account that will be the next `accessor` on the VaultProxy
/// @return nextVaultLib_ The next VaultLib library contract address to set on the VaultProxy
/// @return executableTimestamp_ The timestamp at which the migration request can be executed
function getMigrationRequestDetailsForVaultProxy(address _vaultProxy)
external
view
override
returns (
address nextFundDeployer_,
address nextVaultAccessor_,
address nextVaultLib_,
uint256 executableTimestamp_
)
{
MigrationRequest memory r = vaultProxyToMigrationRequest[_vaultProxy];
if (r.executableTimestamp > 0) {
return (
r.nextFundDeployer,
r.nextVaultAccessor,
r.nextVaultLib,
r.executableTimestamp
);
}
}
/// @notice Gets the amount of time that must pass between signaling and executing a migration
/// @return migrationTimelock_ The timelock value (in seconds)
function getMigrationTimelock() external view override returns (uint256 migrationTimelock_) {
return migrationTimelock;
}
/// @notice Gets the account that is nominated to be the next owner of this contract
/// @return nominatedOwner_ The account that is nominated to be the owner
function getNominatedOwner() external view override returns (address nominatedOwner_) {
return nominatedOwner;
}
/// @notice Gets the owner of this contract
/// @return owner_ The account that is the owner
function getOwner() external view override returns (address owner_) {
return owner;
}
/// @notice Gets the shares token `symbol` value for use in VaultProxy instances
/// @return sharesTokenSymbol_ The `symbol` value
function getSharesTokenSymbol()
external
view
override
returns (string memory sharesTokenSymbol_)
{
return sharesTokenSymbol;
}
/// @notice Gets the time remaining until the migration request of a given VaultProxy can be executed
/// @param _vaultProxy The VaultProxy instance
/// @return secondsRemaining_ The number of seconds remaining on the timelock
function getTimelockRemainingForMigrationRequest(address _vaultProxy)
external
view
override
returns (uint256 secondsRemaining_)
{
uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy]
.executableTimestamp;
if (executableTimestamp == 0) {
return 0;
}
if (block.timestamp >= executableTimestamp) {
return 0;
}
return executableTimestamp - block.timestamp;
}
/// @notice Checks whether a migration request that is executable exists for a given VaultProxy
/// @param _vaultProxy The VaultProxy instance
/// @return hasExecutableRequest_ True if a migration request exists and is executable
function hasExecutableMigrationRequest(address _vaultProxy)
external
view
override
returns (bool hasExecutableRequest_)
{
uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy]
.executableTimestamp;
return executableTimestamp > 0 && block.timestamp >= executableTimestamp;
}
/// @notice Checks whether a migration request exists for a given VaultProxy
/// @param _vaultProxy The VaultProxy instance
/// @return hasMigrationRequest_ True if a migration request exists
function hasMigrationRequest(address _vaultProxy)
external
view
override
returns (bool hasMigrationRequest_)
{
return vaultProxyToMigrationRequest[_vaultProxy].executableTimestamp > 0;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../persistent/vault/VaultLibBaseCore.sol";
/// @title MockVaultLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mock VaultLib implementation that only extends VaultLibBaseCore
contract MockVaultLib is VaultLibBaseCore {
function getAccessor() external view returns (address) {
return accessor;
}
function getCreator() external view returns (address) {
return creator;
}
function getMigrator() external view returns (address) {
return migrator;
}
function getOwner() external view returns (address) {
return owner;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity ^0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title ICERC20 Interface
/// @author Enzyme Council <[email protected]>
/// @notice Minimal interface for interactions with Compound tokens (cTokens)
interface ICERC20 is IERC20 {
function decimals() external view returns (uint8);
function mint(uint256) external returns (uint256);
function redeem(uint256) external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function underlying() external returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/ICERC20.sol";
import "../../../utils/DispatcherOwnerMixin.sol";
import "../IDerivativePriceFeed.sol";
/// @title CompoundPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for Compound Tokens (cTokens)
contract CompoundPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin {
using SafeMath for uint256;
event CTokenAdded(address indexed cToken, address indexed token);
uint256 private constant CTOKEN_RATE_DIVISOR = 10**18;
mapping(address => address) private cTokenToToken;
constructor(
address _dispatcher,
address _weth,
address _ceth,
address[] memory cERC20Tokens
) public DispatcherOwnerMixin(_dispatcher) {
// Set cEth
cTokenToToken[_ceth] = _weth;
emit CTokenAdded(_ceth, _weth);
// Set any other cTokens
if (cERC20Tokens.length > 0) {
__addCERC20Tokens(cERC20Tokens);
}
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
underlyings_ = new address[](1);
underlyings_[0] = cTokenToToken[_derivative];
require(underlyings_[0] != address(0), "calcUnderlyingValues: Unsupported derivative");
underlyingAmounts_ = new uint256[](1);
// Returns a rate scaled to 10^18
underlyingAmounts_[0] = _derivativeAmount
.mul(ICERC20(_derivative).exchangeRateStored())
.div(CTOKEN_RATE_DIVISOR);
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) external view override returns (bool isSupported_) {
return cTokenToToken[_asset] != address(0);
}
//////////////////////
// CTOKENS REGISTRY //
//////////////////////
/// @notice Adds cTokens to the price feed
/// @param _cTokens cTokens to add
/// @dev Only allows CERC20 tokens. CEther is set in the constructor.
function addCTokens(address[] calldata _cTokens) external onlyDispatcherOwner {
__addCERC20Tokens(_cTokens);
}
/// @dev Helper to add cTokens
function __addCERC20Tokens(address[] memory _cTokens) private {
require(_cTokens.length > 0, "__addCTokens: Empty _cTokens");
for (uint256 i; i < _cTokens.length; i++) {
require(cTokenToToken[_cTokens[i]] == address(0), "__addCTokens: Value already set");
address token = ICERC20(_cTokens[i]).underlying();
cTokenToToken[_cTokens[i]] = token;
emit CTokenAdded(_cTokens[i], token);
}
}
////////////////////
// STATE GETTERS //
///////////////////
/// @notice Returns the underlying asset of a given cToken
/// @param _cToken The cToken for which to get the underlying asset
/// @return token_ The underlying token
function getTokenFromCToken(address _cToken) public view returns (address token_) {
return cTokenToToken[_cToken];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../infrastructure/price-feeds/derivatives/feeds/CompoundPriceFeed.sol";
import "../../../../interfaces/ICERC20.sol";
import "../../../../interfaces/ICEther.sol";
import "../../../../interfaces/IWETH.sol";
import "../utils/AdapterBase.sol";
/// @title CompoundAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for Compound <https://compound.finance/>
contract CompoundAdapter is AdapterBase {
address private immutable COMPOUND_PRICE_FEED;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _compoundPriceFeed,
address _wethToken
) public AdapterBase(_integrationManager) {
COMPOUND_PRICE_FEED = _compoundPriceFeed;
WETH_TOKEN = _wethToken;
}
/// @dev Needed to receive ETH during cEther lend/redeem
receive() external payable {}
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "COMPOUND";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == LEND_SELECTOR) {
(address cToken, uint256 tokenAmount, uint256 minCTokenAmount) = __decodeCallArgs(
_encodedCallArgs
);
address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken);
require(token != address(0), "parseAssetsForMethod: Unsupported cToken");
spendAssets_ = new address[](1);
spendAssets_[0] = token;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = tokenAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = cToken;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minCTokenAmount;
} else if (_selector == REDEEM_SELECTOR) {
(address cToken, uint256 cTokenAmount, uint256 minTokenAmount) = __decodeCallArgs(
_encodedCallArgs
);
address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken);
require(token != address(0), "parseAssetsForMethod: Unsupported cToken");
spendAssets_ = new address[](1);
spendAssets_[0] = cToken;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = cTokenAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = token;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minTokenAmount;
} else {
revert("parseAssetsForMethod: _selector invalid");
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Lends an amount of a token to Compound
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
// More efficient to parse all from _encodedAssetTransferArgs
(
,
address[] memory spendAssets,
uint256[] memory spendAssetAmounts,
address[] memory incomingAssets
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
if (spendAssets[0] == WETH_TOKEN) {
IWETH(WETH_TOKEN).withdraw(spendAssetAmounts[0]);
ICEther(incomingAssets[0]).mint{value: spendAssetAmounts[0]}();
} else {
__approveMaxAsNeeded(spendAssets[0], incomingAssets[0], spendAssetAmounts[0]);
ICERC20(incomingAssets[0]).mint(spendAssetAmounts[0]);
}
}
/// @notice Redeems an amount of cTokens from Compound
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem(
address _vaultProxy,
bytes calldata,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
// More efficient to parse all from _encodedAssetTransferArgs
(
,
address[] memory spendAssets,
uint256[] memory spendAssetAmounts,
address[] memory incomingAssets
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
ICERC20(spendAssets[0]).redeem(spendAssetAmounts[0]);
if (incomingAssets[0] == WETH_TOKEN) {
IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}();
}
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode callArgs for lend and redeem
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address cToken_,
uint256 outgoingAssetAmount_,
uint256 minIncomingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (address, uint256, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `COMPOUND_PRICE_FEED` variable
/// @return compoundPriceFeed_ The `COMPOUND_PRICE_FEED` variable value
function getCompoundPriceFeed() external view returns (address compoundPriceFeed_) {
return COMPOUND_PRICE_FEED;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity ^0.6.12;
/// @title ICEther Interface
/// @author Enzyme Council <[email protected]>
/// @notice Minimal interface for interactions with Compound Ether
interface ICEther {
function mint() external payable;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title IChai Interface
/// @author Enzyme Council <[email protected]>
/// @notice Minimal interface for our interactions with the Chai contract
interface IChai is IERC20 {
function exit(address, uint256) external;
function join(address, uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../interfaces/IChai.sol";
import "../utils/AdapterBase.sol";
/// @title ChaiAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for Chai <https://github.com/dapphub/chai>
contract ChaiAdapter is AdapterBase {
address private immutable CHAI;
address private immutable DAI;
constructor(
address _integrationManager,
address _chai,
address _dai
) public AdapterBase(_integrationManager) {
CHAI = _chai;
DAI = _dai;
}
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "CHAI";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == LEND_SELECTOR) {
(uint256 daiAmount, uint256 minChaiAmount) = __decodeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = DAI;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = daiAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = CHAI;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minChaiAmount;
} else if (_selector == REDEEM_SELECTOR) {
(uint256 chaiAmount, uint256 minDaiAmount) = __decodeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = CHAI;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = chaiAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = DAI;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minDaiAmount;
} else {
revert("parseAssetsForMethod: _selector invalid");
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Lend Dai for Chai
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(uint256 daiAmount, ) = __decodeCallArgs(_encodedCallArgs);
__approveMaxAsNeeded(DAI, CHAI, daiAmount);
// Execute Lend on Chai
// Chai.join allows specifying the vaultProxy as the destination of Chai tokens
IChai(CHAI).join(_vaultProxy, daiAmount);
}
/// @notice Redeem Chai for Dai
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(uint256 chaiAmount, ) = __decodeCallArgs(_encodedCallArgs);
// Execute redeem on Chai
// Chai.exit sends Dai back to the adapter
IChai(CHAI).exit(address(this), chaiAmount);
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the encoded call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (uint256 outgoingAmount_, uint256 minIncomingAmount_)
{
return abi.decode(_encodedCallArgs, (uint256, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `CHAI` variable value
/// @return chai_ The `CHAI` variable value
function getChai() external view returns (address chai_) {
return CHAI;
}
/// @notice Gets the `DAI` variable value
/// @return dai_ The `DAI` variable value
function getDai() external view returns (address dai_) {
return DAI;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/SwapperBase.sol";
contract MockGenericIntegratee is SwapperBase {
function swap(
address[] calldata _assetsToIntegratee,
uint256[] calldata _assetsToIntegrateeAmounts,
address[] calldata _assetsFromIntegratee,
uint256[] calldata _assetsFromIntegrateeAmounts
) external payable {
__swap(
msg.sender,
_assetsToIntegratee,
_assetsToIntegrateeAmounts,
_assetsFromIntegratee,
_assetsFromIntegrateeAmounts
);
}
function swapOnBehalf(
address payable _trader,
address[] calldata _assetsToIntegratee,
uint256[] calldata _assetsToIntegrateeAmounts,
address[] calldata _assetsFromIntegratee,
uint256[] calldata _assetsFromIntegrateeAmounts
) external payable {
__swap(
_trader,
_assetsToIntegratee,
_assetsToIntegrateeAmounts,
_assetsFromIntegratee,
_assetsFromIntegrateeAmounts
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../prices/CentralizedRateProvider.sol";
import "../tokens/MockToken.sol";
import "../utils/SwapperBase.sol";
contract MockChaiIntegratee is MockToken, SwapperBase {
address private immutable CENTRALIZED_RATE_PROVIDER;
address public immutable DAI;
constructor(
address _dai,
address _centralizedRateProvider,
uint8 _decimals
) public MockToken("Chai", "CHAI", _decimals) {
_setupDecimals(_decimals);
CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider;
DAI = _dai;
}
function join(address, uint256 _daiAmount) external {
uint256 tokenDecimals = ERC20(DAI).decimals();
uint256 chaiDecimals = decimals();
// Calculate the amount of tokens per one unit of DAI
uint256 daiPerChaiUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(address(this), 10**uint256(chaiDecimals), DAI);
// Calculate the inverse rate to know the amount of CHAI to return from a unit of DAI
uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(chaiDecimals)).div(
daiPerChaiUnit
);
// Mint and send those CHAI to sender
uint256 destAmount = _daiAmount.mul(inverseRate).div(10**tokenDecimals);
_mint(address(this), destAmount);
__swapAssets(msg.sender, DAI, _daiAmount, address(this), destAmount);
}
function exit(address payable _trader, uint256 _chaiAmount) external {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue(
address(this),
_chaiAmount,
DAI
);
// Burn CHAI of the trader.
_burn(_trader, _chaiAmount);
// Release DAI to the trader.
ERC20(DAI).transfer(msg.sender, destAmount);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../interfaces/IAlphaHomoraV1Bank.sol";
import "../../../../interfaces/IWETH.sol";
import "../utils/AdapterBase.sol";
/// @title AlphaHomoraV1Adapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for Alpha Homora v1 <https://alphafinance.io/>
contract AlphaHomoraV1Adapter is AdapterBase {
address private immutable IBETH_TOKEN;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _ibethToken,
address _wethToken
) public AdapterBase(_integrationManager) {
IBETH_TOKEN = _ibethToken;
WETH_TOKEN = _wethToken;
}
/// @dev Needed to receive ETH during redemption
receive() external payable {}
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "ALPHA_HOMORA_V1";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == LEND_SELECTOR) {
(uint256 wethAmount, uint256 minIbethAmount) = __decodeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = WETH_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = wethAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = IBETH_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIbethAmount;
} else if (_selector == REDEEM_SELECTOR) {
(uint256 ibethAmount, uint256 minWethAmount) = __decodeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = IBETH_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = ibethAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = WETH_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minWethAmount;
} else {
revert("parseAssetsForMethod: _selector invalid");
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Lends WETH for ibETH
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(uint256 wethAmount, ) = __decodeCallArgs(_encodedCallArgs);
IWETH(payable(WETH_TOKEN)).withdraw(wethAmount);
IAlphaHomoraV1Bank(IBETH_TOKEN).deposit{value: payable(address(this)).balance}();
}
/// @notice Redeems ibETH for WETH
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(uint256 ibethAmount, ) = __decodeCallArgs(_encodedCallArgs);
IAlphaHomoraV1Bank(IBETH_TOKEN).withdraw(ibethAmount);
IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}();
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the encoded call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (uint256 outgoingAmount_, uint256 minIncomingAmount_)
{
return abi.decode(_encodedCallArgs, (uint256, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `IBETH_TOKEN` variable
/// @return ibethToken_ The `IBETH_TOKEN` variable value
function getIbethToken() external view returns (address ibethToken_) {
return IBETH_TOKEN;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IAlphaHomoraV1Bank interface
/// @author Enzyme Council <[email protected]>
interface IAlphaHomoraV1Bank {
function deposit() external payable;
function totalETH() external view returns (uint256);
function totalSupply() external view returns (uint256);
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/IAlphaHomoraV1Bank.sol";
import "../IDerivativePriceFeed.sol";
/// @title AlphaHomoraV1PriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for Alpha Homora v1 ibETH
contract AlphaHomoraV1PriceFeed is IDerivativePriceFeed {
using SafeMath for uint256;
address private immutable IBETH_TOKEN;
address private immutable WETH_TOKEN;
constructor(address _ibethToken, address _wethToken) public {
IBETH_TOKEN = _ibethToken;
WETH_TOKEN = _wethToken;
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only ibETH is supported");
underlyings_ = new address[](1);
underlyings_[0] = WETH_TOKEN;
underlyingAmounts_ = new uint256[](1);
IAlphaHomoraV1Bank alphaHomoraBankContract = IAlphaHomoraV1Bank(IBETH_TOKEN);
underlyingAmounts_[0] = _derivativeAmount.mul(alphaHomoraBankContract.totalETH()).div(
alphaHomoraBankContract.totalSupply()
);
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return _asset == IBETH_TOKEN;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `IBETH_TOKEN` variable
/// @return ibethToken_ The `IBETH_TOKEN` variable value
function getIbethToken() external view returns (address ibethToken_) {
return IBETH_TOKEN;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/IMakerDaoPot.sol";
import "../IDerivativePriceFeed.sol";
/// @title ChaiPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for Chai
contract ChaiPriceFeed is IDerivativePriceFeed {
using SafeMath for uint256;
uint256 private constant CHI_DIVISOR = 10**27;
address private immutable CHAI;
address private immutable DAI;
address private immutable DSR_POT;
constructor(
address _chai,
address _dai,
address _dsrPot
) public {
CHAI = _chai;
DAI = _dai;
DSR_POT = _dsrPot;
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
/// @dev Calculation based on Chai source: https://github.com/dapphub/chai/blob/master/src/chai.sol
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only Chai is supported");
underlyings_ = new address[](1);
underlyings_[0] = DAI;
underlyingAmounts_ = new uint256[](1);
underlyingAmounts_[0] = _derivativeAmount.mul(IMakerDaoPot(DSR_POT).chi()).div(
CHI_DIVISOR
);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return _asset == CHAI;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `CHAI` variable value
/// @return chai_ The `CHAI` variable value
function getChai() external view returns (address chai_) {
return CHAI;
}
/// @notice Gets the `DAI` variable value
/// @return dai_ The `DAI` variable value
function getDai() external view returns (address dai_) {
return DAI;
}
/// @notice Gets the `DSR_POT` variable value
/// @return dsrPot_ The `DSR_POT` variable value
function getDsrPot() external view returns (address dsrPot_) {
return DSR_POT;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @notice Limited interface for Maker DSR's Pot contract
/// @dev See DSR integration guide: https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr-integration-guide-01.md
interface IMakerDaoPot {
function chi() external view returns (uint256);
function rho() external view returns (uint256);
function drip() external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./FeeBase.sol";
/// @title EntranceRateFeeBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Calculates a fee based on a rate to be charged to an investor upon entering a fund
abstract contract EntranceRateFeeBase is FeeBase {
using SafeMath for uint256;
event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate);
event Settled(address indexed comptrollerProxy, address indexed payer, uint256 sharesQuantity);
uint256 private constant RATE_DIVISOR = 10**18;
IFeeManager.SettlementType private immutable SETTLEMENT_TYPE;
mapping(address => uint256) private comptrollerProxyToRate;
constructor(address _feeManager, IFeeManager.SettlementType _settlementType)
public
FeeBase(_feeManager)
{
require(
_settlementType == IFeeManager.SettlementType.Burn ||
_settlementType == IFeeManager.SettlementType.Direct,
"constructor: Invalid _settlementType"
);
SETTLEMENT_TYPE = _settlementType;
}
// EXTERNAL FUNCTIONS
/// @notice Add the fee settings for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _settingsData Encoded settings to apply to the policy for a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData)
external
override
onlyFeeManager
{
uint256 rate = abi.decode(_settingsData, (uint256));
require(rate > 0, "addFundSettings: Fee rate must be >0");
comptrollerProxyToRate[_comptrollerProxy] = rate;
emit FundSettingsAdded(_comptrollerProxy, rate);
}
/// @notice Gets the hooks that are implemented by the fee
/// @return implementedHooksForSettle_ The hooks during which settle() is implemented
/// @return implementedHooksForUpdate_ The hooks during which update() is implemented
/// @return usesGavOnSettle_ True if GAV is used during the settle() implementation
/// @return usesGavOnUpdate_ True if GAV is used during the update() implementation
/// @dev Used only during fee registration
function implementedHooks()
external
view
override
returns (
IFeeManager.FeeHook[] memory implementedHooksForSettle_,
IFeeManager.FeeHook[] memory implementedHooksForUpdate_,
bool usesGavOnSettle_,
bool usesGavOnUpdate_
)
{
implementedHooksForSettle_ = new IFeeManager.FeeHook[](1);
implementedHooksForSettle_[0] = IFeeManager.FeeHook.PostBuyShares;
return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false);
}
/// @notice Settles the fee
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _settlementData Encoded args to use in calculating the settlement
/// @return settlementType_ The type of settlement
/// @return payer_ The payer of shares due
/// @return sharesDue_ The amount of shares due
function settle(
address _comptrollerProxy,
address,
IFeeManager.FeeHook,
bytes calldata _settlementData,
uint256
)
external
override
onlyFeeManager
returns (
IFeeManager.SettlementType settlementType_,
address payer_,
uint256 sharesDue_
)
{
uint256 sharesBought;
(payer_, , sharesBought) = __decodePostBuySharesSettlementData(_settlementData);
uint256 rate = comptrollerProxyToRate[_comptrollerProxy];
sharesDue_ = sharesBought.mul(rate).div(RATE_DIVISOR.add(rate));
if (sharesDue_ == 0) {
return (IFeeManager.SettlementType.None, address(0), 0);
}
emit Settled(_comptrollerProxy, payer_, sharesDue_);
return (SETTLEMENT_TYPE, payer_, sharesDue_);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `rate` variable for a fund
/// @param _comptrollerProxy The ComptrollerProxy contract for the fund
/// @return rate_ The `rate` variable value
function getRateForFund(address _comptrollerProxy) external view returns (uint256 rate_) {
return comptrollerProxyToRate[_comptrollerProxy];
}
/// @notice Gets the `SETTLEMENT_TYPE` variable
/// @return settlementType_ The `SETTLEMENT_TYPE` variable value
function getSettlementType()
external
view
returns (IFeeManager.SettlementType settlementType_)
{
return SETTLEMENT_TYPE;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./utils/EntranceRateFeeBase.sol";
/// @title EntranceRateDirectFee Contract
/// @author Enzyme Council <[email protected]>
/// @notice An EntranceRateFee that transfers the fee shares to the fund manager
contract EntranceRateDirectFee is EntranceRateFeeBase {
constructor(address _feeManager)
public
EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Direct)
{}
/// @notice Provides a constant string identifier for a fee
/// @return identifier_ The identifier string
function identifier() external pure override returns (string memory identifier_) {
return "ENTRANCE_RATE_DIRECT";
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./utils/EntranceRateFeeBase.sol";
/// @title EntranceRateBurnFee Contract
/// @author Enzyme Council <[email protected]>
/// @notice An EntranceRateFee that burns the fee shares
contract EntranceRateBurnFee is EntranceRateFeeBase {
constructor(address _feeManager)
public
EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Burn)
{}
/// @notice Provides a constant string identifier for a fee
/// @return identifier_ The identifier string
function identifier() external pure override returns (string memory identifier_) {
return "ENTRANCE_RATE_BURN";
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
contract MockChaiPriceSource {
using SafeMath for uint256;
uint256 private chiStored = 10**27;
uint256 private rhoStored = now;
function drip() external returns (uint256) {
require(now >= rhoStored, "drip: invalid now");
rhoStored = now;
chiStored = chiStored.mul(99).div(100);
return chi();
}
////////////////////
// STATE GETTERS //
///////////////////
function chi() public view returns (uint256) {
return chiStored;
}
function rho() public view returns (uint256) {
return rhoStored;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/DispatcherOwnerMixin.sol";
import "./IAggregatedDerivativePriceFeed.sol";
/// @title AggregatedDerivativePriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Aggregates multiple derivative price feeds (e.g., Compound, Chai) and dispatches
/// rate requests to the appropriate feed
contract AggregatedDerivativePriceFeed is IAggregatedDerivativePriceFeed, DispatcherOwnerMixin {
event DerivativeAdded(address indexed derivative, address priceFeed);
event DerivativeRemoved(address indexed derivative);
event DerivativeUpdated(
address indexed derivative,
address prevPriceFeed,
address nextPriceFeed
);
mapping(address => address) private derivativeToPriceFeed;
constructor(
address _dispatcher,
address[] memory _derivatives,
address[] memory _priceFeeds
) public DispatcherOwnerMixin(_dispatcher) {
if (_derivatives.length > 0) {
__addDerivatives(_derivatives, _priceFeeds);
}
}
/// @notice Gets the rates for 1 unit of the derivative to its underlying assets
/// @param _derivative The derivative for which to get the rates
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The rates for the _derivative to the underlyings_
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
address derivativePriceFeed = derivativeToPriceFeed[_derivative];
require(
derivativePriceFeed != address(0),
"calcUnderlyingValues: _derivative is not supported"
);
return
IDerivativePriceFeed(derivativePriceFeed).calcUnderlyingValues(
_derivative,
_derivativeAmount
);
}
/// @notice Checks whether an asset is a supported derivative
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is a supported derivative
/// @dev This should be as low-cost and simple as possible
function isSupportedAsset(address _asset) external view override returns (bool isSupported_) {
return derivativeToPriceFeed[_asset] != address(0);
}
//////////////////////////
// DERIVATIVES REGISTRY //
//////////////////////////
/// @notice Adds a list of derivatives with the given price feed values
/// @param _derivatives The derivatives to add
/// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives
function addDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds)
external
onlyDispatcherOwner
{
require(_derivatives.length > 0, "addDerivatives: _derivatives cannot be empty");
__addDerivatives(_derivatives, _priceFeeds);
}
/// @notice Removes a list of derivatives
/// @param _derivatives The derivatives to remove
function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner {
require(_derivatives.length > 0, "removeDerivatives: _derivatives cannot be empty");
for (uint256 i = 0; i < _derivatives.length; i++) {
require(
derivativeToPriceFeed[_derivatives[i]] != address(0),
"removeDerivatives: Derivative not yet added"
);
delete derivativeToPriceFeed[_derivatives[i]];
emit DerivativeRemoved(_derivatives[i]);
}
}
/// @notice Updates a list of derivatives with the given price feed values
/// @param _derivatives The derivatives to update
/// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives
function updateDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds)
external
onlyDispatcherOwner
{
require(_derivatives.length > 0, "updateDerivatives: _derivatives cannot be empty");
require(
_derivatives.length == _priceFeeds.length,
"updateDerivatives: Unequal _derivatives and _priceFeeds array lengths"
);
for (uint256 i = 0; i < _derivatives.length; i++) {
address prevPriceFeed = derivativeToPriceFeed[_derivatives[i]];
require(prevPriceFeed != address(0), "updateDerivatives: Derivative not yet added");
require(_priceFeeds[i] != prevPriceFeed, "updateDerivatives: Value already set");
__validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]);
derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i];
emit DerivativeUpdated(_derivatives[i], prevPriceFeed, _priceFeeds[i]);
}
}
/// @dev Helper to add derivative-feed pairs
function __addDerivatives(address[] memory _derivatives, address[] memory _priceFeeds)
private
{
require(
_derivatives.length == _priceFeeds.length,
"__addDerivatives: Unequal _derivatives and _priceFeeds array lengths"
);
for (uint256 i = 0; i < _derivatives.length; i++) {
require(
derivativeToPriceFeed[_derivatives[i]] == address(0),
"__addDerivatives: Already added"
);
__validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]);
derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i];
emit DerivativeAdded(_derivatives[i], _priceFeeds[i]);
}
}
/// @dev Helper to validate a derivative price feed
function __validateDerivativePriceFeed(address _derivative, address _priceFeed) private view {
require(_derivative != address(0), "__validateDerivativePriceFeed: Empty _derivative");
require(_priceFeed != address(0), "__validateDerivativePriceFeed: Empty _priceFeed");
require(
IDerivativePriceFeed(_priceFeed).isSupportedAsset(_derivative),
"__validateDerivativePriceFeed: Unsupported derivative"
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the registered price feed for a given derivative
/// @return priceFeed_ The price feed contract address
function getPriceFeedForDerivative(address _derivative)
external
view
override
returns (address priceFeed_)
{
return derivativeToPriceFeed[_derivative];
}
}
| Check the shares quantity against the user's balance after settling fees | ERC20 sharesContract = ERC20(address(vaultProxyContract));
| 1,696,867 | [
1,
1564,
326,
24123,
10457,
5314,
326,
729,
1807,
11013,
1839,
26319,
2456,
1656,
281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
4232,
39,
3462,
24123,
8924,
273,
4232,
39,
3462,
12,
2867,
12,
26983,
3886,
8924,
10019,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xCbbd3E8633BBa5365fCae84C413c73D030EB6fb9/sources/contracts/SubnameMinterV1.sol | 48 is the ASCII code of '0'
| uint8 digit = uint8(b[i]) - 48; | 9,618,823 | [
1,
8875,
353,
326,
11768,
981,
434,
296,
20,
11,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5411,
2254,
28,
8035,
273,
2254,
28,
12,
70,
63,
77,
5717,
300,
9934,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.13;
contract Token {
/* Public variables of the token */
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
function Token() {
totalSupply = 1*(10**8)*(10**18);
balanceOf[msg.sender] = 1*(10**8)*(10**18); // Give the creator all initial tokens
name = "jeason"; // Set the name for display purposes
symbol = "jeason"; // Set the symbol for display purposes
decimals = 18; // Amount of decimals for display purposes
}
function transfer(address _to, uint256 _value) {
/* Check if sender has balance and for overflows */
if (balanceOf[msg.sender] < _value || balanceOf[_to] + _value < balanceOf[_to])
revert();
/* Add and subtract new balances */
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
/* Notifiy anyone listening that this transfer took place */
Transfer(msg.sender, _to, _value);
}
/* This unnamed function is called whenever someone tries to send ether to it */
function () {
revert(); // Prevents accidental sending of ether
}
} | Public variables of the token */ This creates an array with all balances */ This generates a public event on the blockchain that will notify clients */ | function Token() {
totalSupply = 1*(10**8)*(10**18);
}
| 12,027,546 | [
1,
4782,
3152,
434,
326,
1147,
342,
1220,
3414,
392,
526,
598,
777,
324,
26488,
342,
1220,
6026,
279,
1071,
871,
603,
326,
16766,
716,
903,
5066,
7712,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
3155,
1435,
288,
203,
202,
565,
2078,
3088,
1283,
273,
404,
21556,
2163,
636,
28,
17653,
12,
2163,
636,
2643,
1769,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x14132D979fDdA62a56d9f552C9aa477b9c94851e/sources/@yield-protocol/yieldspace-tv/src/YieldMath.sol | Ethereum smart contract library implementing Yield Math model with yield bearing tokens. @dev see Mikhail Vladimirov (ABDK) explanations of the math: https://hackmd.io/gbnqA3gCTR6z-F0HHTxF-A#Yield-Math | library YieldMath {
using Math64x64 for int128;
using Math64x64 for uint128;
using Math64x64 for int256;
using Math64x64 for uint256;
using Exp64x64 for uint128;
using Exp64x64 for int128;
using Cast for uint256;
using Cast for uint128;
uint128 public constant WAD = 1e18;
┌───────────────────────────────┐ .-:::::::::::-.
┌──────────────┐ │ │ .:::::::::::::::::.
│$ $│ \│ │/ : _______ __ __ :
│ ┌────────────┴─┐ \│ │/ :: | || | | |::
│ │$ $│ │ fyTokenOutForSharesIn │ ::: | ___|| |_| |:::
│$│ ┌────────────┴─┐ ────────▶ │ │ ────────▶ ::: | |___ | |:::
└─┤ │$ $│ │ │ ::: | ___||_ _|:::
│$│ `sharesIn` │ /│ │\ ::: | | | | :::
└─┤ │ /│ │\ :: |___| |___| ::
│$ $│ │ \(^o^)/ │ : ???? :
└──────────────┘ │ YieldMath │ `:::::::::::::::::'
└───────────────────────────────┘ `-:::::::::::-'
function fyTokenOutForSharesIn(
uint128 timeTillMaturity,
int128 k,
int128 g,
int128 c,
int128 mu
pragma solidity >=0.8.15;
__ ___ _ _
import {Exp64x64} from "./Exp64x64.sol";
import {Math64x64} from "./Math64x64.sol";
import {Cast} from "@yield-protocol/utils-v2/src/utils/Cast.sol";
) public pure returns (uint128) {
unchecked {
require(c > 0 && mu > 0, "YieldMath: c and mu must be positive");
uint128 a = _computeA(timeTillMaturity, k, g);
uint256 sum;
{
y = fyToken reserves
z = shares reserves
x = Δz (sharesIn)
y - ( sum )^( invA )
y - (( Za ) + ( Ya ) - ( Zxa ) )^( invA )
Δy = y - ( c/μ * (μz)^(1-t) + y^(1-t) - c/μ * (μz + μx)^(1-t) )^(1 / (1 - t))
*/
uint256 normalizedSharesReserves;
require((normalizedSharesReserves = mu.mulu(sharesReserves)) <= MAX, "YieldMath: Rate overflow (nsr)");
uint256 za;
require(
(za = c.div(mu).mulu(uint128(normalizedSharesReserves).pow(a, ONE))) <= MAX,
"YieldMath: Rate overflow (za)"
);
uint256 ya = fyTokenReserves.pow(a, ONE);
uint256 normalizedSharesIn;
require((normalizedSharesIn = mu.mulu(sharesIn)) <= MAX, "YieldMath: Rate overflow (nsi)");
uint256 zx;
require((zx = normalizedSharesReserves + normalizedSharesIn) <= MAX, "YieldMath: Too many shares in");
uint256 zxa;
require((zxa = c.div(mu).mulu(uint128(zx).pow(a, ONE))) <= MAX, "YieldMath: Rate overflow (zxa)");
sum = za + ya - zxa;
require(sum <= (za + ya), "YieldMath: Sum underflow");
}
require(
(fyTokenOut = uint256(fyTokenReserves) - sum.u128().pow(ONE, a)) <= MAX,
"YieldMath: Rounding error"
);
require(fyTokenOut <= fyTokenReserves, "YieldMath: > fyToken reserves");
return uint128(fyTokenOut);
}
}
.:::::::::::::::::. │ │
: _______ __ __ : \│ │/ ┌──────────────┐
:: | || | | |:: \│ │/ │$ $│
::: | ___|| |_| |::: │ sharesOutForFYTokenIn │ │ ┌────────────┴─┐
::: | |___ | |::: ────────▶ │ │ ────────▶ │ │$ $│
::: | ___||_ _|::: │ │ │$│ ┌────────────┴─┐
::: | | | | ::: /│ │\ └─┤ │$ $│
:: |___| |___| :: /│ │\ │$│ SHARES │
: `fyTokenIn` : │ \(^o^)/ │ └─┤ ???? │
`:::::::::::::::::' │ YieldMath │ │$ $│
`-:::::::::::-' └───────────────────────────────┘ └──────────────┘
) public pure returns (uint128) {
unchecked {
require(c > 0 && mu > 0, "YieldMath: c and mu must be positive");
uint128 a = _computeA(timeTillMaturity, k, g);
uint256 sum;
{
y = fyToken reserves
z = shares reserves
x = Δz (sharesIn)
y - ( sum )^( invA )
y - (( Za ) + ( Ya ) - ( Zxa ) )^( invA )
Δy = y - ( c/μ * (μz)^(1-t) + y^(1-t) - c/μ * (μz + μx)^(1-t) )^(1 / (1 - t))
*/
uint256 normalizedSharesReserves;
require((normalizedSharesReserves = mu.mulu(sharesReserves)) <= MAX, "YieldMath: Rate overflow (nsr)");
uint256 za;
require(
(za = c.div(mu).mulu(uint128(normalizedSharesReserves).pow(a, ONE))) <= MAX,
"YieldMath: Rate overflow (za)"
);
uint256 ya = fyTokenReserves.pow(a, ONE);
uint256 normalizedSharesIn;
require((normalizedSharesIn = mu.mulu(sharesIn)) <= MAX, "YieldMath: Rate overflow (nsi)");
uint256 zx;
require((zx = normalizedSharesReserves + normalizedSharesIn) <= MAX, "YieldMath: Too many shares in");
uint256 zxa;
require((zxa = c.div(mu).mulu(uint128(zx).pow(a, ONE))) <= MAX, "YieldMath: Rate overflow (zxa)");
sum = za + ya - zxa;
require(sum <= (za + ya), "YieldMath: Sum underflow");
}
require(
(fyTokenOut = uint256(fyTokenReserves) - sum.u128().pow(ONE, a)) <= MAX,
"YieldMath: Rounding error"
);
require(fyTokenOut <= fyTokenReserves, "YieldMath: > fyToken reserves");
return uint128(fyTokenOut);
}
}
.:::::::::::::::::. │ │
: _______ __ __ : \│ │/ ┌──────────────┐
:: | || | | |:: \│ │/ │$ $│
::: | ___|| |_| |::: │ sharesOutForFYTokenIn │ │ ┌────────────┴─┐
::: | |___ | |::: ────────▶ │ │ ────────▶ │ │$ $│
::: | ___||_ _|::: │ │ │$│ ┌────────────┴─┐
::: | | | | ::: /│ │\ └─┤ │$ $│
:: |___| |___| :: /│ │\ │$│ SHARES │
: `fyTokenIn` : │ \(^o^)/ │ └─┤ ???? │
`:::::::::::::::::' │ YieldMath │ │$ $│
`-:::::::::::-' └───────────────────────────────┘ └──────────────┘
) public pure returns (uint128) {
unchecked {
require(c > 0 && mu > 0, "YieldMath: c and mu must be positive");
uint128 a = _computeA(timeTillMaturity, k, g);
uint256 sum;
{
y = fyToken reserves
z = shares reserves
x = Δz (sharesIn)
y - ( sum )^( invA )
y - (( Za ) + ( Ya ) - ( Zxa ) )^( invA )
Δy = y - ( c/μ * (μz)^(1-t) + y^(1-t) - c/μ * (μz + μx)^(1-t) )^(1 / (1 - t))
*/
uint256 normalizedSharesReserves;
require((normalizedSharesReserves = mu.mulu(sharesReserves)) <= MAX, "YieldMath: Rate overflow (nsr)");
uint256 za;
require(
(za = c.div(mu).mulu(uint128(normalizedSharesReserves).pow(a, ONE))) <= MAX,
"YieldMath: Rate overflow (za)"
);
uint256 ya = fyTokenReserves.pow(a, ONE);
uint256 normalizedSharesIn;
require((normalizedSharesIn = mu.mulu(sharesIn)) <= MAX, "YieldMath: Rate overflow (nsi)");
uint256 zx;
require((zx = normalizedSharesReserves + normalizedSharesIn) <= MAX, "YieldMath: Too many shares in");
uint256 zxa;
require((zxa = c.div(mu).mulu(uint128(zx).pow(a, ONE))) <= MAX, "YieldMath: Rate overflow (zxa)");
sum = za + ya - zxa;
require(sum <= (za + ya), "YieldMath: Sum underflow");
}
require(
(fyTokenOut = uint256(fyTokenReserves) - sum.u128().pow(ONE, a)) <= MAX,
"YieldMath: Rounding error"
);
require(fyTokenOut <= fyTokenReserves, "YieldMath: > fyToken reserves");
return uint128(fyTokenOut);
}
}
.:::::::::::::::::. │ │
: _______ __ __ : \│ │/ ┌──────────────┐
:: | || | | |:: \│ │/ │$ $│
::: | ___|| |_| |::: │ sharesOutForFYTokenIn │ │ ┌────────────┴─┐
::: | |___ | |::: ────────▶ │ │ ────────▶ │ │$ $│
::: | ___||_ _|::: │ │ │$│ ┌────────────┴─┐
::: | | | | ::: /│ │\ └─┤ │$ $│
:: |___| |___| :: /│ │\ │$│ SHARES │
: `fyTokenIn` : │ \(^o^)/ │ └─┤ ???? │
`:::::::::::::::::' │ YieldMath │ │$ $│
`-:::::::::::-' └───────────────────────────────┘ └──────────────┘
uint256 fyTokenOut;
.-:::::::::::-. ┌───────────────────────────────┐
function sharesOutForFYTokenIn(
uint128 sharesReserves,
uint128 fyTokenReserves,
uint128 fyTokenIn,
uint128 timeTillMaturity,
int128 k,
int128 g,
int128 c,
int128 mu
) public pure returns (uint128) {
unchecked {
require(c > 0 && mu > 0, "YieldMath: c and mu must be positive");
return
_sharesOutForFYTokenIn(
sharesReserves,
fyTokenReserves,
fyTokenIn,
_computeA(timeTillMaturity, k, g),
c,
mu
);
}
}
function sharesOutForFYTokenIn(
uint128 sharesReserves,
uint128 fyTokenReserves,
uint128 fyTokenIn,
uint128 timeTillMaturity,
int128 k,
int128 g,
int128 c,
int128 mu
) public pure returns (uint128) {
unchecked {
require(c > 0 && mu > 0, "YieldMath: c and mu must be positive");
return
_sharesOutForFYTokenIn(
sharesReserves,
fyTokenReserves,
fyTokenIn,
_computeA(timeTillMaturity, k, g),
c,
mu
);
}
}
function _sharesOutForFYTokenIn(
uint128 sharesReserves,
uint128 fyTokenReserves,
uint128 fyTokenIn,
uint128 a,
int128 c,
int128 mu
) private pure returns (uint128) {
y = fyToken reserves
z = shares reserves
x = Δy (fyTokenIn)
z - ( rightTerm )
z - (invMu) * ( Za ) + ( Ya ) - ( Yxa ) / (c / μ) )^( invA )
Δz = z - 1/μ * ( ( (c / μ) * (μz)^(1-t) + y^(1-t) - (y + x)^(1-t) ) / (c / μ) )^(1 / (1 - t))
*/
unchecked {
uint256 normalizedSharesReserves;
require((normalizedSharesReserves = mu.mulu(sharesReserves)) <= MAX, "YieldMath: Rate overflow (nsr)");
uint128 rightTerm;
{
uint256 zaYaYxa;
{
uint256 za;
require(
(za = c.div(mu).mulu(uint128(normalizedSharesReserves).pow(a, ONE))) <= MAX,
"YieldMath: Rate overflow (za)"
);
uint256 ya = fyTokenReserves.pow(a, ONE);
uint256 yxa = (fyTokenReserves + fyTokenIn).pow(a, ONE);
require((zaYaYxa = (za + ya - yxa)) <= MAX, "YieldMath: Rate overflow (yxa)");
}
).div(mu)
);
}
require(rightTerm <= sharesReserves, "YieldMath: Rate underflow");
return sharesReserves - rightTerm;
}
}
.:::::::::::::::::. │ │ ┌──────────────┐
: _______ __ __ : \│ │/ │$ $│
:: | || | | |:: \│ │/ │ ┌────────────┴─┐
::: | ___|| |_| |::: │ fyTokenInForSharesOut │ │ │$ $│
::: | |___ | |::: ────────▶ │ │ ────────▶ │$│ ┌────────────┴─┐
::: | ___||_ _|::: │ │ └─┤ │$ $│
::: | | | | ::: /│ │\ │$│ │
:: |___| |___| :: /│ │\ └─┤ `sharesOut` │
: ???? : │ \(^o^)/ │ │$ $│
`:::::::::::::::::' │ YieldMath │ └──────────────┘
`-:::::::::::-' └───────────────────────────────┘
function _sharesOutForFYTokenIn(
uint128 sharesReserves,
uint128 fyTokenReserves,
uint128 fyTokenIn,
uint128 a,
int128 c,
int128 mu
) private pure returns (uint128) {
y = fyToken reserves
z = shares reserves
x = Δy (fyTokenIn)
z - ( rightTerm )
z - (invMu) * ( Za ) + ( Ya ) - ( Yxa ) / (c / μ) )^( invA )
Δz = z - 1/μ * ( ( (c / μ) * (μz)^(1-t) + y^(1-t) - (y + x)^(1-t) ) / (c / μ) )^(1 / (1 - t))
*/
unchecked {
uint256 normalizedSharesReserves;
require((normalizedSharesReserves = mu.mulu(sharesReserves)) <= MAX, "YieldMath: Rate overflow (nsr)");
uint128 rightTerm;
{
uint256 zaYaYxa;
{
uint256 za;
require(
(za = c.div(mu).mulu(uint128(normalizedSharesReserves).pow(a, ONE))) <= MAX,
"YieldMath: Rate overflow (za)"
);
uint256 ya = fyTokenReserves.pow(a, ONE);
uint256 yxa = (fyTokenReserves + fyTokenIn).pow(a, ONE);
require((zaYaYxa = (za + ya - yxa)) <= MAX, "YieldMath: Rate overflow (yxa)");
}
).div(mu)
);
}
require(rightTerm <= sharesReserves, "YieldMath: Rate underflow");
return sharesReserves - rightTerm;
}
}
.:::::::::::::::::. │ │ ┌──────────────┐
: _______ __ __ : \│ │/ │$ $│
:: | || | | |:: \│ │/ │ ┌────────────┴─┐
::: | ___|| |_| |::: │ fyTokenInForSharesOut │ │ │$ $│
::: | |___ | |::: ────────▶ │ │ ────────▶ │$│ ┌────────────┴─┐
::: | ___||_ _|::: │ │ └─┤ │$ $│
::: | | | | ::: /│ │\ │$│ │
:: |___| |___| :: /│ │\ └─┤ `sharesOut` │
: ???? : │ \(^o^)/ │ │$ $│
`:::::::::::::::::' │ YieldMath │ └──────────────┘
`-:::::::::::-' └───────────────────────────────┘
function _sharesOutForFYTokenIn(
uint128 sharesReserves,
uint128 fyTokenReserves,
uint128 fyTokenIn,
uint128 a,
int128 c,
int128 mu
) private pure returns (uint128) {
y = fyToken reserves
z = shares reserves
x = Δy (fyTokenIn)
z - ( rightTerm )
z - (invMu) * ( Za ) + ( Ya ) - ( Yxa ) / (c / μ) )^( invA )
Δz = z - 1/μ * ( ( (c / μ) * (μz)^(1-t) + y^(1-t) - (y + x)^(1-t) ) / (c / μ) )^(1 / (1 - t))
*/
unchecked {
uint256 normalizedSharesReserves;
require((normalizedSharesReserves = mu.mulu(sharesReserves)) <= MAX, "YieldMath: Rate overflow (nsr)");
uint128 rightTerm;
{
uint256 zaYaYxa;
{
uint256 za;
require(
(za = c.div(mu).mulu(uint128(normalizedSharesReserves).pow(a, ONE))) <= MAX,
"YieldMath: Rate overflow (za)"
);
uint256 ya = fyTokenReserves.pow(a, ONE);
uint256 yxa = (fyTokenReserves + fyTokenIn).pow(a, ONE);
require((zaYaYxa = (za + ya - yxa)) <= MAX, "YieldMath: Rate overflow (yxa)");
}
).div(mu)
);
}
require(rightTerm <= sharesReserves, "YieldMath: Rate underflow");
return sharesReserves - rightTerm;
}
}
.:::::::::::::::::. │ │ ┌──────────────┐
: _______ __ __ : \│ │/ │$ $│
:: | || | | |:: \│ │/ │ ┌────────────┴─┐
::: | ___|| |_| |::: │ fyTokenInForSharesOut │ │ │$ $│
::: | |___ | |::: ────────▶ │ │ ────────▶ │$│ ┌────────────┴─┐
::: | ___||_ _|::: │ │ └─┤ │$ $│
::: | | | | ::: /│ │\ │$│ │
:: |___| |___| :: /│ │\ └─┤ `sharesOut` │
: ???? : │ \(^o^)/ │ │$ $│
`:::::::::::::::::' │ YieldMath │ └──────────────┘
`-:::::::::::-' └───────────────────────────────┘
function _sharesOutForFYTokenIn(
uint128 sharesReserves,
uint128 fyTokenReserves,
uint128 fyTokenIn,
uint128 a,
int128 c,
int128 mu
) private pure returns (uint128) {
y = fyToken reserves
z = shares reserves
x = Δy (fyTokenIn)
z - ( rightTerm )
z - (invMu) * ( Za ) + ( Ya ) - ( Yxa ) / (c / μ) )^( invA )
Δz = z - 1/μ * ( ( (c / μ) * (μz)^(1-t) + y^(1-t) - (y + x)^(1-t) ) / (c / μ) )^(1 / (1 - t))
*/
unchecked {
uint256 normalizedSharesReserves;
require((normalizedSharesReserves = mu.mulu(sharesReserves)) <= MAX, "YieldMath: Rate overflow (nsr)");
uint128 rightTerm;
{
uint256 zaYaYxa;
{
uint256 za;
require(
(za = c.div(mu).mulu(uint128(normalizedSharesReserves).pow(a, ONE))) <= MAX,
"YieldMath: Rate overflow (za)"
);
uint256 ya = fyTokenReserves.pow(a, ONE);
uint256 yxa = (fyTokenReserves + fyTokenIn).pow(a, ONE);
require((zaYaYxa = (za + ya - yxa)) <= MAX, "YieldMath: Rate overflow (yxa)");
}
).div(mu)
);
}
require(rightTerm <= sharesReserves, "YieldMath: Rate underflow");
return sharesReserves - rightTerm;
}
}
.:::::::::::::::::. │ │ ┌──────────────┐
: _______ __ __ : \│ │/ │$ $│
:: | || | | |:: \│ │/ │ ┌────────────┴─┐
::: | ___|| |_| |::: │ fyTokenInForSharesOut │ │ │$ $│
::: | |___ | |::: ────────▶ │ │ ────────▶ │$│ ┌────────────┴─┐
::: | ___||_ _|::: │ │ └─┤ │$ $│
::: | | | | ::: /│ │\ │$│ │
:: |___| |___| :: /│ │\ └─┤ `sharesOut` │
: ???? : │ \(^o^)/ │ │$ $│
`:::::::::::::::::' │ YieldMath │ └──────────────┘
`-:::::::::::-' └───────────────────────────────┘
.-:::::::::::-. ┌───────────────────────────────┐
function fyTokenInForSharesOut(
uint128 sharesReserves,
uint128 fyTokenReserves,
uint128 sharesOut,
uint128 timeTillMaturity,
int128 k,
int128 g,
int128 c,
int128 mu
) public pure returns (uint128) {
y = fyToken reserves
z = shares reserves
x = Δz (sharesOut)
( sum )^( invA ) - y
( Za ) + ( Ya ) - ( Zxa )^( invA ) - y
Δy = ( c/μ * (μz)^(1-t) + y^(1-t) - c/μ * (μz - μx)^(1-t) )^(1 / (1 - t)) - y
*/
unchecked {
require(c > 0 && mu > 0, "YieldMath: c and mu must be positive");
uint128 a = _computeA(timeTillMaturity, k, g);
uint256 sum;
{
uint256 normalizedSharesReserves;
require((normalizedSharesReserves = mu.mulu(sharesReserves)) <= MAX, "YieldMath: Rate overflow (nsr)");
uint256 za;
require(
(za = c.div(mu).mulu(uint128(normalizedSharesReserves).pow(a, ONE))) <= MAX,
"YieldMath: Rate overflow (za)"
);
uint256 ya = fyTokenReserves.pow(a, ONE);
uint256 normalizedSharesOut;
require((normalizedSharesOut = mu.mulu(sharesOut)) <= MAX, "YieldMath: Rate overflow (nso)");
require(normalizedSharesReserves >= normalizedSharesOut, "YieldMath: Too many shares in");
uint256 zx = normalizedSharesReserves - normalizedSharesOut;
uint256 zxa = c.div(mu).mulu(uint128(zx).pow(a, ONE));
require((sum = za + ya - zxa) <= MAX, "YieldMath: > fyToken reserves");
}
require(
(result = uint256(uint128(sum).pow(ONE, a)) - uint256(fyTokenReserves)) <= MAX,
"YieldMath: Rounding error"
);
return uint128(result);
}
}
┌──────────────┐ │ │ .:::::::::::::::::.
│$ $│ \│ │/ : _______ __ __ :
│ ┌────────────┴─┐ \│ │/ :: | || | | |::
│ │$ $│ │ sharesInForFYTokenOut │ ::: | ___|| |_| |:::
│$│ ┌────────────┴─┐ ────────▶ │ │ ────────▶ ::: | |___ | |:::
└─┤ │$ $│ │ │ ::: | ___||_ _|:::
│$│ SHARES │ /│ │\ ::: | | | | :::
└─┤ ???? │ /│ │\ :: |___| |___| ::
│$ $│ │ \(^o^)/ │ : `fyTokenOut` :
└──────────────┘ │ YieldMath │ `:::::::::::::::::'
└───────────────────────────────┘ `-:::::::::::-'
function fyTokenInForSharesOut(
uint128 sharesReserves,
uint128 fyTokenReserves,
uint128 sharesOut,
uint128 timeTillMaturity,
int128 k,
int128 g,
int128 c,
int128 mu
) public pure returns (uint128) {
y = fyToken reserves
z = shares reserves
x = Δz (sharesOut)
( sum )^( invA ) - y
( Za ) + ( Ya ) - ( Zxa )^( invA ) - y
Δy = ( c/μ * (μz)^(1-t) + y^(1-t) - c/μ * (μz - μx)^(1-t) )^(1 / (1 - t)) - y
*/
unchecked {
require(c > 0 && mu > 0, "YieldMath: c and mu must be positive");
uint128 a = _computeA(timeTillMaturity, k, g);
uint256 sum;
{
uint256 normalizedSharesReserves;
require((normalizedSharesReserves = mu.mulu(sharesReserves)) <= MAX, "YieldMath: Rate overflow (nsr)");
uint256 za;
require(
(za = c.div(mu).mulu(uint128(normalizedSharesReserves).pow(a, ONE))) <= MAX,
"YieldMath: Rate overflow (za)"
);
uint256 ya = fyTokenReserves.pow(a, ONE);
uint256 normalizedSharesOut;
require((normalizedSharesOut = mu.mulu(sharesOut)) <= MAX, "YieldMath: Rate overflow (nso)");
require(normalizedSharesReserves >= normalizedSharesOut, "YieldMath: Too many shares in");
uint256 zx = normalizedSharesReserves - normalizedSharesOut;
uint256 zxa = c.div(mu).mulu(uint128(zx).pow(a, ONE));
require((sum = za + ya - zxa) <= MAX, "YieldMath: > fyToken reserves");
}
require(
(result = uint256(uint128(sum).pow(ONE, a)) - uint256(fyTokenReserves)) <= MAX,
"YieldMath: Rounding error"
);
return uint128(result);
}
}
┌──────────────┐ │ │ .:::::::::::::::::.
│$ $│ \│ │/ : _______ __ __ :
│ ┌────────────┴─┐ \│ │/ :: | || | | |::
│ │$ $│ │ sharesInForFYTokenOut │ ::: | ___|| |_| |:::
│$│ ┌────────────┴─┐ ────────▶ │ │ ────────▶ ::: | |___ | |:::
└─┤ │$ $│ │ │ ::: | ___||_ _|:::
│$│ SHARES │ /│ │\ ::: | | | | :::
└─┤ ???? │ /│ │\ :: |___| |___| ::
│$ $│ │ \(^o^)/ │ : `fyTokenOut` :
└──────────────┘ │ YieldMath │ `:::::::::::::::::'
└───────────────────────────────┘ `-:::::::::::-'
function fyTokenInForSharesOut(
uint128 sharesReserves,
uint128 fyTokenReserves,
uint128 sharesOut,
uint128 timeTillMaturity,
int128 k,
int128 g,
int128 c,
int128 mu
) public pure returns (uint128) {
y = fyToken reserves
z = shares reserves
x = Δz (sharesOut)
( sum )^( invA ) - y
( Za ) + ( Ya ) - ( Zxa )^( invA ) - y
Δy = ( c/μ * (μz)^(1-t) + y^(1-t) - c/μ * (μz - μx)^(1-t) )^(1 / (1 - t)) - y
*/
unchecked {
require(c > 0 && mu > 0, "YieldMath: c and mu must be positive");
uint128 a = _computeA(timeTillMaturity, k, g);
uint256 sum;
{
uint256 normalizedSharesReserves;
require((normalizedSharesReserves = mu.mulu(sharesReserves)) <= MAX, "YieldMath: Rate overflow (nsr)");
uint256 za;
require(
(za = c.div(mu).mulu(uint128(normalizedSharesReserves).pow(a, ONE))) <= MAX,
"YieldMath: Rate overflow (za)"
);
uint256 ya = fyTokenReserves.pow(a, ONE);
uint256 normalizedSharesOut;
require((normalizedSharesOut = mu.mulu(sharesOut)) <= MAX, "YieldMath: Rate overflow (nso)");
require(normalizedSharesReserves >= normalizedSharesOut, "YieldMath: Too many shares in");
uint256 zx = normalizedSharesReserves - normalizedSharesOut;
uint256 zxa = c.div(mu).mulu(uint128(zx).pow(a, ONE));
require((sum = za + ya - zxa) <= MAX, "YieldMath: > fyToken reserves");
}
require(
(result = uint256(uint128(sum).pow(ONE, a)) - uint256(fyTokenReserves)) <= MAX,
"YieldMath: Rounding error"
);
return uint128(result);
}
}
┌──────────────┐ │ │ .:::::::::::::::::.
│$ $│ \│ │/ : _______ __ __ :
│ ┌────────────┴─┐ \│ │/ :: | || | | |::
│ │$ $│ │ sharesInForFYTokenOut │ ::: | ___|| |_| |:::
│$│ ┌────────────┴─┐ ────────▶ │ │ ────────▶ ::: | |___ | |:::
└─┤ │$ $│ │ │ ::: | ___||_ _|:::
│$│ SHARES │ /│ │\ ::: | | | | :::
└─┤ ???? │ /│ │\ :: |___| |___| ::
│$ $│ │ \(^o^)/ │ : `fyTokenOut` :
└──────────────┘ │ YieldMath │ `:::::::::::::::::'
└───────────────────────────────┘ `-:::::::::::-'
uint256 result;
┌───────────────────────────────┐ .-:::::::::::-.
function sharesInForFYTokenOut(
uint128 sharesReserves,
uint128 fyTokenReserves,
uint128 fyTokenOut,
uint128 timeTillMaturity,
int128 k,
int128 g,
int128 c,
int128 mu
) public pure returns (uint128) {
unchecked {
require(c > 0 && mu > 0, "YieldMath: c and mu must be positive");
return
_sharesInForFYTokenOut(
sharesReserves,
fyTokenReserves,
fyTokenOut,
_computeA(timeTillMaturity, k, g),
c,
mu
);
}
}
function sharesInForFYTokenOut(
uint128 sharesReserves,
uint128 fyTokenReserves,
uint128 fyTokenOut,
uint128 timeTillMaturity,
int128 k,
int128 g,
int128 c,
int128 mu
) public pure returns (uint128) {
unchecked {
require(c > 0 && mu > 0, "YieldMath: c and mu must be positive");
return
_sharesInForFYTokenOut(
sharesReserves,
fyTokenReserves,
fyTokenOut,
_computeA(timeTillMaturity, k, g),
c,
mu
);
}
}
function _sharesInForFYTokenOut(
uint128 sharesReserves,
uint128 fyTokenReserves,
uint128 fyTokenOut,
uint128 a,
int128 c,
int128 mu
) private pure returns (uint128) {
y = fyToken reserves
z = shares reserves
x = Δy (fyTokenOut)
1/μ * ( subtotal )^( invA ) - z
1/μ * (( Za ) + ( Ya ) - ( Yxa )) / (c/μ) )^( invA ) - z
Δz = 1/μ * (( c/μ * μz^(1-t) + y^(1-t) - (y - x)^(1-t)) / (c/μ) )^(1 / (1 - t)) - z
*/
unchecked {
require(mu.mulu(sharesReserves) <= MAX, "YieldMath: Rate overflow (nsr)");
uint256 za = c.div(mu).mulu(uint128(mu.mulu(sharesReserves)).pow(a, ONE));
require(za <= MAX, "YieldMath: Rate overflow (za)");
uint256 ya = fyTokenReserves.pow(a, ONE);
uint256 yxa = (fyTokenReserves - fyTokenOut).pow(a, ONE);
require(fyTokenOut <= fyTokenReserves, "YieldMath: Underflow (yxa)");
uint256 zaYaYxa;
require((zaYaYxa = (za + ya - yxa)) <= MAX, "YieldMath: Rate overflow (zyy)");
int128 subtotal = int128(ONE).div(mu).mul(
(uint128(zaYaYxa.divu(uint128(c.div(mu)))).pow(uint128(ONE), uint128(a))).i128()
);
uint128 sharesOut = uint128(subtotal) - sharesReserves;
require(sharesOut <= uint128(subtotal), "YieldMath: Underflow error");
return sharesOut;
}
}
function _sharesInForFYTokenOut(
uint128 sharesReserves,
uint128 fyTokenReserves,
uint128 fyTokenOut,
uint128 a,
int128 c,
int128 mu
) private pure returns (uint128) {
y = fyToken reserves
z = shares reserves
x = Δy (fyTokenOut)
1/μ * ( subtotal )^( invA ) - z
1/μ * (( Za ) + ( Ya ) - ( Yxa )) / (c/μ) )^( invA ) - z
Δz = 1/μ * (( c/μ * μz^(1-t) + y^(1-t) - (y - x)^(1-t)) / (c/μ) )^(1 / (1 - t)) - z
*/
unchecked {
require(mu.mulu(sharesReserves) <= MAX, "YieldMath: Rate overflow (nsr)");
uint256 za = c.div(mu).mulu(uint128(mu.mulu(sharesReserves)).pow(a, ONE));
require(za <= MAX, "YieldMath: Rate overflow (za)");
uint256 ya = fyTokenReserves.pow(a, ONE);
uint256 yxa = (fyTokenReserves - fyTokenOut).pow(a, ONE);
require(fyTokenOut <= fyTokenReserves, "YieldMath: Underflow (yxa)");
uint256 zaYaYxa;
require((zaYaYxa = (za + ya - yxa)) <= MAX, "YieldMath: Rate overflow (zyy)");
int128 subtotal = int128(ONE).div(mu).mul(
(uint128(zaYaYxa.divu(uint128(c.div(mu)))).pow(uint128(ONE), uint128(a))).i128()
);
uint128 sharesOut = uint128(subtotal) - sharesReserves;
require(sharesOut <= uint128(subtotal), "YieldMath: Underflow error");
return sharesOut;
}
}
function maxFYTokenIn(
uint128 sharesReserves,
uint128 fyTokenReserves,
uint128 timeTillMaturity,
int128 k,
int128 g,
int128 c,
int128 mu
) public pure returns (uint128 fyTokenIn) {
Y = fyToken reserves
Z = shares reserves
y = maxFYTokenIn
( sum )^( invA ) - Y
( Za ) + ( Ya ) )^( invA ) - Y
Δy = ( c/μ * (μz)^(1-t) + Y^(1-t) )^(1 / (1 - t)) - Y
*/
unchecked {
require(c > 0 && mu > 0, "YieldMath: c and mu must be positive");
uint128 a = _computeA(timeTillMaturity, k, g);
uint256 sum;
{
uint256 normalizedSharesReserves;
require((normalizedSharesReserves = mu.mulu(sharesReserves)) <= MAX, "YieldMath: Rate overflow (nsr)");
uint256 za;
require(
(za = c.div(mu).mulu(uint128(normalizedSharesReserves).pow(a, ONE))) <= MAX,
"YieldMath: Rate overflow (za)"
);
uint256 ya = fyTokenReserves.pow(a, ONE);
require((sum = za + ya) <= MAX, "YieldMath: > fyToken reserves");
}
require(
(result = uint256(uint128(sum).pow(ONE, a)) - uint256(fyTokenReserves)) <= MAX,
"YieldMath: Rounding error"
);
fyTokenIn = uint128(result);
}
}
function maxFYTokenIn(
uint128 sharesReserves,
uint128 fyTokenReserves,
uint128 timeTillMaturity,
int128 k,
int128 g,
int128 c,
int128 mu
) public pure returns (uint128 fyTokenIn) {
Y = fyToken reserves
Z = shares reserves
y = maxFYTokenIn
( sum )^( invA ) - Y
( Za ) + ( Ya ) )^( invA ) - Y
Δy = ( c/μ * (μz)^(1-t) + Y^(1-t) )^(1 / (1 - t)) - Y
*/
unchecked {
require(c > 0 && mu > 0, "YieldMath: c and mu must be positive");
uint128 a = _computeA(timeTillMaturity, k, g);
uint256 sum;
{
uint256 normalizedSharesReserves;
require((normalizedSharesReserves = mu.mulu(sharesReserves)) <= MAX, "YieldMath: Rate overflow (nsr)");
uint256 za;
require(
(za = c.div(mu).mulu(uint128(normalizedSharesReserves).pow(a, ONE))) <= MAX,
"YieldMath: Rate overflow (za)"
);
uint256 ya = fyTokenReserves.pow(a, ONE);
require((sum = za + ya) <= MAX, "YieldMath: > fyToken reserves");
}
require(
(result = uint256(uint128(sum).pow(ONE, a)) - uint256(fyTokenReserves)) <= MAX,
"YieldMath: Rounding error"
);
fyTokenIn = uint128(result);
}
}
function maxFYTokenIn(
uint128 sharesReserves,
uint128 fyTokenReserves,
uint128 timeTillMaturity,
int128 k,
int128 g,
int128 c,
int128 mu
) public pure returns (uint128 fyTokenIn) {
Y = fyToken reserves
Z = shares reserves
y = maxFYTokenIn
( sum )^( invA ) - Y
( Za ) + ( Ya ) )^( invA ) - Y
Δy = ( c/μ * (μz)^(1-t) + Y^(1-t) )^(1 / (1 - t)) - Y
*/
unchecked {
require(c > 0 && mu > 0, "YieldMath: c and mu must be positive");
uint128 a = _computeA(timeTillMaturity, k, g);
uint256 sum;
{
uint256 normalizedSharesReserves;
require((normalizedSharesReserves = mu.mulu(sharesReserves)) <= MAX, "YieldMath: Rate overflow (nsr)");
uint256 za;
require(
(za = c.div(mu).mulu(uint128(normalizedSharesReserves).pow(a, ONE))) <= MAX,
"YieldMath: Rate overflow (za)"
);
uint256 ya = fyTokenReserves.pow(a, ONE);
require((sum = za + ya) <= MAX, "YieldMath: > fyToken reserves");
}
require(
(result = uint256(uint128(sum).pow(ONE, a)) - uint256(fyTokenReserves)) <= MAX,
"YieldMath: Rounding error"
);
fyTokenIn = uint128(result);
}
}
uint256 result;
function maxFYTokenOut(
uint128 sharesReserves,
uint128 fyTokenReserves,
uint128 timeTillMaturity,
int128 k,
int128 g,
int128 c,
int128 mu
) public pure returns (uint128 fyTokenOut) {
unchecked {
require(c > 0 && mu > 0, "YieldMath: c and mu must be positive");
int128 a = int128(_computeA(timeTillMaturity, k, g));
y = maxFyTokenOut
Y = fyTokenReserves (virtual)
Z = sharesReserves
Y - ( ( numerator ) / ( denominator ) )^invA
Y - ( ( ( Za ) + ( Ya ) ) / ( denominator ) )^invA
y = Y - ( ( c/μ * (μZ)^a + Y^a ) / ( c/μ + 1 ) )^(1/a)
int128 za = c.div(mu).mul(mu.mul(sharesReserves.divu(WAD)).pow(a));
int128 ya = fyTokenReserves.divu(WAD).pow(a);
int128 numerator = za.add(ya);
int128 denominator = c.div(mu).add(int128(ONE));
int128 rightTerm = numerator.div(denominator).pow(int128(ONE).div(a));
require((fyTokenOut = fyTokenReserves - uint128(rightTerm.mulu(WAD))) <= MAX, "YieldMath: Underflow error");
require(fyTokenOut <= fyTokenReserves, "YieldMath: Underflow error");
}
}
function maxFYTokenOut(
uint128 sharesReserves,
uint128 fyTokenReserves,
uint128 timeTillMaturity,
int128 k,
int128 g,
int128 c,
int128 mu
) public pure returns (uint128 fyTokenOut) {
unchecked {
require(c > 0 && mu > 0, "YieldMath: c and mu must be positive");
int128 a = int128(_computeA(timeTillMaturity, k, g));
y = maxFyTokenOut
Y = fyTokenReserves (virtual)
Z = sharesReserves
Y - ( ( numerator ) / ( denominator ) )^invA
Y - ( ( ( Za ) + ( Ya ) ) / ( denominator ) )^invA
y = Y - ( ( c/μ * (μZ)^a + Y^a ) / ( c/μ + 1 ) )^(1/a)
int128 za = c.div(mu).mul(mu.mul(sharesReserves.divu(WAD)).pow(a));
int128 ya = fyTokenReserves.divu(WAD).pow(a);
int128 numerator = za.add(ya);
int128 denominator = c.div(mu).add(int128(ONE));
int128 rightTerm = numerator.div(denominator).pow(int128(ONE).div(a));
require((fyTokenOut = fyTokenReserves - uint128(rightTerm.mulu(WAD))) <= MAX, "YieldMath: Underflow error");
require(fyTokenOut <= fyTokenReserves, "YieldMath: Underflow error");
}
}
function maxSharesIn(
uint128 timeTillMaturity,
int128 k,
int128 g,
int128 c,
int128 mu
) public pure returns (uint128 sharesIn) {
unchecked {
require(c > 0 && mu > 0, "YieldMath: c and mu must be positive");
int128 a = int128(_computeA(timeTillMaturity, k, g));
y = maxSharesIn_
Y = fyTokenReserves (virtual)
Z = sharesReserves
1/μ ( ( numerator ) / ( denominator ) )^invA - Z
1/μ ( ( ( Za ) + ( Ya ) ) / ( denominator ) )^invA - Z
y = 1/μ ( ( c/μ * (μZ)^a + Y^a ) / ( c/u + 1 ) )^(1/a) - Z
int128 za = c.div(mu).mul(mu.mul(sharesReserves.divu(WAD)).pow(a));
int128 ya = fyTokenReserves.divu(WAD).pow(a);
int128 numerator = za.add(ya);
int128 denominator = c.div(mu).add(int128(ONE));
int128 leftTerm = int128(ONE).div(mu).mul(numerator.div(denominator).pow(int128(ONE).div(a)));
require((sharesIn = uint128(leftTerm.mulu(WAD)) - sharesReserves) <= MAX, "YieldMath: Underflow error");
require(sharesIn <= uint128(leftTerm.mulu(WAD)), "YieldMath: Underflow error");
}
}
function maxSharesIn(
uint128 timeTillMaturity,
int128 k,
int128 g,
int128 c,
int128 mu
) public pure returns (uint128 sharesIn) {
unchecked {
require(c > 0 && mu > 0, "YieldMath: c and mu must be positive");
int128 a = int128(_computeA(timeTillMaturity, k, g));
y = maxSharesIn_
Y = fyTokenReserves (virtual)
Z = sharesReserves
1/μ ( ( numerator ) / ( denominator ) )^invA - Z
1/μ ( ( ( Za ) + ( Ya ) ) / ( denominator ) )^invA - Z
y = 1/μ ( ( c/μ * (μZ)^a + Y^a ) / ( c/u + 1 ) )^(1/a) - Z
int128 za = c.div(mu).mul(mu.mul(sharesReserves.divu(WAD)).pow(a));
int128 ya = fyTokenReserves.divu(WAD).pow(a);
int128 numerator = za.add(ya);
int128 denominator = c.div(mu).add(int128(ONE));
int128 leftTerm = int128(ONE).div(mu).mul(numerator.div(denominator).pow(int128(ONE).div(a)));
require((sharesIn = uint128(leftTerm.mulu(WAD)) - sharesReserves) <= MAX, "YieldMath: Underflow error");
require(sharesIn <= uint128(leftTerm.mulu(WAD)), "YieldMath: Underflow error");
}
}
) public pure returns (uint128 maxSharesOut_) {} */
This function is not needed as it's return value is driven directly by the shares liquidity of the pool
function maxSharesOut(
uint128 timeTillMaturity,
int128 k,
int128 g,
int128 c,
int128 mu
function invariant(
uint128 timeTillMaturity,
int128 k,
int128 g,
int128 c,
int128 mu
) public pure returns (uint128 result) {
if (totalSupply == 0) return 0;
int128 a = int128(_computeA(timeTillMaturity, k, g));
result = _invariant(sharesReserves, fyTokenReserves, totalSupply, a, c, mu);
}
function _invariant(
int128 a,
int128 c,
int128 mu
) internal pure returns (uint128 result) {
unchecked {
require(c > 0 && mu > 0, "YieldMath: c and mu must be positive");
y = invariant
Y = fyTokenReserves (virtual)
Z = sharesReserves
s = total supply
c/μ ( ( numerator ) / ( denominator ) )^invA / s
c/μ ( ( ( Za ) + ( Ya ) ) / ( denominator ) )^invA / s
y = c/μ ( ( c/μ * (μZ)^a + Y^a ) / ( c/u + 1 ) )^(1/a) / s
int128 za = c.div(mu).mul(mu.mul(sharesReserves.divu(WAD)).pow(a));
int128 ya = fyTokenReserves.divu(WAD).pow(a);
int128 numerator = za.add(ya);
int128 denominator = c.div(mu).add(int128(ONE));
int128 topTerm = c.div(mu).mul((numerator.div(denominator)).pow(int128(ONE).div(a)));
result = uint128((topTerm.mulu(WAD) * WAD) / totalSupply);
}
}
function _invariant(
int128 a,
int128 c,
int128 mu
) internal pure returns (uint128 result) {
unchecked {
require(c > 0 && mu > 0, "YieldMath: c and mu must be positive");
y = invariant
Y = fyTokenReserves (virtual)
Z = sharesReserves
s = total supply
c/μ ( ( numerator ) / ( denominator ) )^invA / s
c/μ ( ( ( Za ) + ( Ya ) ) / ( denominator ) )^invA / s
y = c/μ ( ( c/μ * (μZ)^a + Y^a ) / ( c/u + 1 ) )^(1/a) / s
int128 za = c.div(mu).mul(mu.mul(sharesReserves.divu(WAD)).pow(a));
int128 ya = fyTokenReserves.divu(WAD).pow(a);
int128 numerator = za.add(ya);
int128 denominator = c.div(mu).add(int128(ONE));
int128 topTerm = c.div(mu).mul((numerator.div(denominator)).pow(int128(ONE).div(a)));
result = uint128((topTerm.mulu(WAD) * WAD) / totalSupply);
}
}
function _computeA(
uint128 timeTillMaturity,
int128 k,
int128 g
) private pure returns (uint128) {
int128 t = k.mul(timeTillMaturity.fromUInt());
int128 a = int128(ONE).sub(g.mul(t));
require(a > 0, "YieldMath: Too far from maturity");
require(a <= int128(ONE), "YieldMath: g must be positive");
return uint128(a);
}
}
| 15,663,259 | [
1,
41,
18664,
379,
13706,
6835,
5313,
19981,
31666,
2361,
938,
598,
2824,
30261,
2430,
18,
225,
2621,
490,
1766,
76,
671,
776,
80,
361,
381,
11373,
90,
261,
2090,
3398,
13,
431,
7088,
1012,
434,
326,
4233,
30,
2333,
2207,
76,
484,
1264,
18,
1594,
19,
4490,
82,
85,
37,
23,
75,
23876,
26,
94,
17,
42,
20,
17500,
4188,
42,
17,
5255,
491,
17,
10477,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
31666,
10477,
288,
203,
565,
1450,
2361,
1105,
92,
1105,
364,
509,
10392,
31,
203,
565,
1450,
2361,
1105,
92,
1105,
364,
2254,
10392,
31,
203,
565,
1450,
2361,
1105,
92,
1105,
364,
509,
5034,
31,
203,
565,
1450,
2361,
1105,
92,
1105,
364,
2254,
5034,
31,
203,
565,
1450,
7784,
1105,
92,
1105,
364,
2254,
10392,
31,
203,
565,
1450,
7784,
1105,
92,
1105,
364,
509,
10392,
31,
203,
565,
1450,
19782,
364,
2254,
5034,
31,
203,
565,
1450,
19782,
364,
2254,
10392,
31,
203,
203,
565,
2254,
10392,
1071,
5381,
678,
1880,
273,
404,
73,
2643,
31,
203,
203,
203,
4766,
2868,
225,
163,
247,
239,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
243,
10792,
263,
17,
2866,
2866,
2866,
2866,
2866,
30,
17,
18,
203,
1377,
225,
163,
247,
239,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
227,
163,
247,
2
] |
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/token/ERC721/ERC721Full.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./provableAPI_0.5.sol";
contract OwnableDelegateProxy { }
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
library Random
{
/**
* Initialize the pool with the entropy of the blockhashes of the blocks in the closed interval [earliestBlock, latestBlock]
* The argument "seed" is optional and can be left zero in most cases.
* This extra seed allows you to select a different sequence of random numbers for the same block range.
*/
function init(uint256 earliestBlock, uint256 latestBlock, uint256 seed) internal view returns (bytes32[] memory) {
//require(block.number-1 >= latestBlock && latestBlock >= earliestBlock && earliestBlock >= block.number-256, "Random.init: invalid block interval");
require(block.number-1 >= latestBlock && latestBlock >= earliestBlock, "Random.init: invalid block interval");
bytes32[] memory pool = new bytes32[](latestBlock-earliestBlock+2);
bytes32 salt = keccak256(abi.encodePacked(block.number,seed));
for(uint256 i=0; i<=latestBlock-earliestBlock; i++) {
// Add some salt to each blockhash so that we don't reuse those hash chains
// when this function gets called again in another block.
pool[i+1] = keccak256(abi.encodePacked(blockhash(earliestBlock+i),salt));
}
return pool;
}
/**
* Initialize the pool from the latest "num" blocks.
*/
function initLatest(uint256 num, uint256 seed) internal view returns (bytes32[] memory) {
return init(block.number-num, block.number-1, seed);
}
/**
* Advances to the next 256-bit random number in the pool of hash chains.
*/
function next(bytes32[] memory pool) internal pure returns (uint256) {
require(pool.length > 1, "Random.next: invalid pool");
uint256 roundRobinIdx = uint256(pool[0]) % (pool.length-1) + 1;
bytes32 hash = keccak256(abi.encodePacked(pool[roundRobinIdx]));
pool[0] = bytes32(uint256(pool[0])+1);
pool[roundRobinIdx] = hash;
return uint256(hash);
}
/**
* Produces random integer values, uniformly distributed on the closed interval [a, b]
*/
function uniform(bytes32[] memory pool, int256 a, int256 b) internal pure returns (int256) {
require(a <= b, "Random.uniform: invalid interval");
return int256(next(pool)%uint256(b-a+1))+a;
}
}
contract Cell is ERC721Full, usingProvable {
using Address for address payable;
using SafeMath for uint256;
uint public maxTokenId;
uint public massPool;
address payable public owner = address(0xA096b47EbF7727d01Ff4F09c34Fc6591f2c375F0);
address proxyRegistryAddress;
uint constant private NUM_RANDOM_BYTES_REQUESTED = 2; //The variable `ceiling` should never be greater than: `(256 ^ NUM_RANDOM_BYTES_REQUESTED) - 1`.
uint private _currentTokenId;
uint private gasPrice = 4010000000; //many set exactly 4gwei, so adding 0.01 gwei increases speed much more than expected.
uint private gasAmount = 250000;
struct Wall {
uint32 wave;
bool round;
uint24 color;
}
struct Nucleus {
bool hidden;
uint24 color;
}
struct Feature {
uint8 category;
uint8 family;
uint8 count;
uint24 color;
}
struct Metadata {
uint mass;
Wall wall;
Nucleus nucleus;
mapping(uint => Feature) features;
}
mapping(uint => Metadata) id_to_cell;
mapping(bytes32 => uint16) public provableQueryToSeed;
mapping(bytes32 => address) public provableQueryToAddress;
mapping(bytes32 => uint) public provableQueryToTokenId;
mapping(uint => uint) public nftSeed;
event LogMintQuery(address minter, bytes32 queryId, uint seed, uint tokenId);
constructor() ERC721Full("Cell", "(Y)") public {
massPool = 20000;
_mint(msg.sender, 1);
maxTokenId = 1;
provable_setProof(proofType_Ledger);
provable_setCustomGasPrice(gasPrice);
}
function __callback(bytes32 _queryId, string memory _result, bytes memory _proof) public {
require(msg.sender == provable_cbAddress());
uint16 seed = provableQueryToSeed[_queryId];
address minterAddr = provableQueryToAddress[_queryId];
uint tokenIdR = provableQueryToTokenId[_queryId];
uint rand = uint(
keccak256(abi.encodePacked(_result)) ^ blockhash(block.number-1) ^ bytes32(uint(seed))
);
nftSeed[tokenIdR] = rand.mod(65535);
_safeMint(minterAddr,tokenIdR);
delete provableQueryToSeed[_queryId];
delete provableQueryToAddress[_queryId];
delete provableQueryToTokenId[_queryId];
}
function _parseRandom(uint random, uint min, uint max, uint offset) internal pure returns (uint) {
uint diff = max.sub(min);
uint value = random;
for (uint i = 0; i < offset; i++) {
value /= diff;
}
return value % diff + min;
}
function getWall(uint256 seed) internal view returns (Wall memory cellWall){
bytes32[] memory pool = Random.initLatest(1, seed);
uint32 wallWaveRNG = uint32(Random.uniform(pool, 0, 33554431));
bool wallRoundRNG = Random.uniform(pool, 0, 1) == 1;
uint24 wallColorRNG = uint24(Random.uniform(pool, 0, 16777215));
return Wall(wallWaveRNG, wallRoundRNG, wallColorRNG);
}
function getNucleus(uint256 seed) internal view returns (Nucleus memory cellNucleus){
bytes32[] memory pool = Random.initLatest(2, seed);
bool nucleusHiddenRNG = Random.uniform(pool, 0, 1) == 1;
uint24 nucleusColorRNG = uint24(Random.uniform(pool, 0, 16777215));
return Nucleus(nucleusHiddenRNG, nucleusColorRNG);
}
function getFeatures(uint256 seed) internal view returns (Feature memory cellFeature){
bytes32[] memory pool = Random.initLatest(3, seed);
uint8 featureCategoryRNG = uint8(Random.uniform(pool, 0, 7));
uint8 featureFamilyRNG = uint8(Random.uniform(pool, 0, 7));
uint8 featureCountRNG = uint8(Random.uniform(pool, 0, 15));
uint24 featureColorRNG = uint24(Random.uniform(pool, 0, 16777215));
return Feature(featureCategoryRNG, featureFamilyRNG, featureCountRNG, featureColorRNG);
}
function getMassOffset(uint256 seed) internal view returns (int8 massOffsetRNG){
bytes32[] memory pool = Random.initLatest(4, seed);
massOffsetRNG = int8(Random.uniform(pool, -2, 2));
}
function getMerge(uint256 seed) internal view returns (uint8[12] memory combineCellsRNG){
bytes32[] memory pool = Random.initLatest(5, seed);
uint i;
for(i=0; i<12; i++) {
combineCellsRNG[i] = uint8(Random.uniform(pool, 1, 100));
}
}
function getDivide(uint256 seed) internal view returns (uint8 divideCellsRNG){
bytes32[] memory pool = Random.initLatest(6, seed);
divideCellsRNG = uint8(Random.uniform(pool, 30, 70));
}
function getRektBoost(uint256 seed, uint mass) internal view returns (uint256 rektBoostMass){
bytes32[] memory pool = Random.initLatest(6, seed);
uint8 rektBoostRNG = uint8(Random.uniform(pool, 1, 100));
uint x = mass;
uint8 level = 1;
while (x > 8) {
x /= 2;
level++;
}
if (rektBoostRNG <= 1) {
rektBoostMass = mass * 1 / 100;
} else if (rektBoostRNG <= 3) {
rektBoostMass = mass * 70 / 100;
} else if (rektBoostRNG <= 10) {
rektBoostMass = mass * 90 / 100;
} else if (rektBoostRNG <= 35) {
rektBoostMass = mass * 95 / 100;
} else if (rektBoostRNG <= 65) {
rektBoostMass = mass;
} else if (rektBoostRNG <= 90) {
rektBoostMass = mass + uint256(level*(massPool/1000));
} else if (rektBoostRNG <= 97) {
rektBoostMass = mass + uint256(level*(massPool/333));
} else {
rektBoostMass = mass + uint256(level*(massPool/100));
}
}
function mint(uint256 seed) public payable {
require(msg.value == 8 finney);
require(massPool >= 8);
maxTokenId++;
Metadata storage cell = id_to_cell[maxTokenId];
cell.mass = 8;
cell.wall = getWall(seed + maxTokenId);
cell.nucleus = getNucleus(seed + maxTokenId);
for (uint i = 0; i < 10; i++) {
cell.features[i] = getFeatures(seed + maxTokenId + i);
}
id_to_cell[maxTokenId] = cell;
massPool = massPool.sub(8);
_mint(msg.sender, maxTokenId);
owner.toPayable().sendValue(8 finney);
/*
bytes32 queryId = provable_newRandomDSQuery(
0, //Execution delay
NUM_RANDOM_BYTES_REQUESTED,
gasAmount
);
emit LogMintQuery(msg.sender, queryId, seed, _currentTokenId);
provableQueryToSeed[queryId] = seed;
provableQueryToAddress[queryId] = msg.sender;
provableQueryToTokenId[queryId] = maxTokenId;
*/
}
function merge(uint id1, uint id2) public payable {
require(msg.value == 2 finney);
require(massPool > 0);
require(ownerOf(id1) == msg.sender);
require(ownerOf(id2) == msg.sender);
maxTokenId++;
Metadata storage cellA = id_to_cell[id1];
Metadata storage cellB = id_to_cell[id2];
Metadata storage cell = id_to_cell[maxTokenId];
cell.mass = cellA.mass.add(cellB.mass);
uint256 rektBoostMass = getRektBoost(1234, cell.mass);
massPool = massPool + cell.mass - rektBoostMass;
cell.mass = rektBoostMass;
uint256 mergeRatio = (cellA.mass*100/cell.mass);
uint8[12] memory mergeSelectRNG = getMerge(123);
for (uint i = 0; i < 8; i++) {
if (mergeSelectRNG[i] >= mergeRatio) {
cell.features[i] = cellB.features[i];
} else {
cell.features[i] = cellA.features[i];
}
}
if (mergeSelectRNG[8] >= mergeRatio) {
cell.wall.wave = cellB.wall.wave;
} else {
cell.wall.wave = cellA.wall.wave;
}
if (mergeSelectRNG[9] >= mergeRatio) {
cell.wall.round = cellB.wall.round;
} else {
cell.wall.round = cellA.wall.round;
}
if (mergeSelectRNG[10] >= mergeRatio) {
cell.wall.color = cellB.wall.color;
} else {
cell.wall.color = cellA.wall.color;
}
if (mergeSelectRNG[11] >= mergeRatio) {
cell.nucleus = cellB.nucleus;
} else {
cell.nucleus = cellA.nucleus;
}
_mint(msg.sender, maxTokenId);
_burn(id1);
_burn(id2);
owner.toPayable().sendValue(2 finney);
}
function split(uint id) public payable {
require(msg.value == 2 finney);
require(massPool > 0);
require(ownerOf(id) == msg.sender);
maxTokenId++;
Metadata storage cell = id_to_cell[id];
uint8 divideRatio = getDivide(123);
Metadata storage cell1 = id_to_cell[maxTokenId];
cell1.mass = (divideRatio*cell.mass)/100;
cell1.wall = cell.wall;
cell1.nucleus = cell.nucleus;
for (uint i = 0; i < 8; i++) {
cell1.features[i] = cell.features[i];
}
id_to_cell[maxTokenId] = cell1;
_mint(msg.sender, maxTokenId);
maxTokenId++;
Metadata storage cell2 = id_to_cell[maxTokenId];
cell2.mass = cell.mass - cell1.mass;
cell2.wall = cell.wall;
cell2.nucleus = cell.nucleus;
for (uint i = 0; i < 8; i++) {
cell2.features[i] = cell.features[i];
}
id_to_cell[maxTokenId] = cell2;
_mint(msg.sender, maxTokenId);
_burn(id);
owner.toPayable().sendValue(2 finney);
}
function get(uint id) external view returns (uint mass,
uint32 wallWave, bool wallRound, uint24 wallColor,
bool nucleusHidden, uint24 nucleusColor,
uint8[8] memory featureCategories, uint8[8] memory featureFamilies,
uint8[8] memory featureCounts, uint24[8] memory featureColors
) {
Metadata storage cell = id_to_cell[id];
mass = cell.mass;
wallWave = cell.wall.wave;
wallRound = cell.wall.round;
wallColor = cell.wall.color;
nucleusHidden = cell.nucleus.hidden;
nucleusColor = cell.nucleus.color;
for (uint i = 0; i < 8; i++) {
Feature memory feature = cell.features[i];
featureCategories[i] = feature.category;
featureFamilies[i] = feature.family;
featureCounts[i] = feature.count;
featureColors[i] = feature.color;
}
}
} | The variable `ceiling` should never be greater than: `(256 ^ NUM_RANDOM_BYTES_REQUESTED) - 1`.
| uint constant private NUM_RANDOM_BYTES_REQUESTED = 2; | 12,677,706 | [
1,
1986,
2190,
1375,
311,
4973,
68,
1410,
5903,
506,
6802,
2353,
30,
1375,
12,
5034,
3602,
9443,
67,
54,
28159,
67,
13718,
67,
5519,
2056,
13,
300,
404,
8338,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5381,
3238,
9443,
67,
54,
28159,
67,
13718,
67,
5519,
2056,
273,
576,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0xD11F69C9F80503D3c504f296F1Ab1b7575ab7854/sources/contracts/ThdToken.sol | My Variables Keep track balances and allowances approved Events - fire events on state changes etc production: 0xdAC17F958D2ee523a2206206994597C13D831ec7 | contract Token {
string public name;
string public symbol;
uint256 public decimals;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
address public constant USDT_CONTRACT_ADDRESS = 0xD92E713d051C37EbB2561803a3b5FBAbc4962431;
IERC20 usdt = IERC20(address(USDT_CONTRACT_ADDRESS));
address public constant RESERVED_WALLET_ADDRESS = 0x1f5ac5d4C9CD21c804a2dF3bd28a0127343E561F;
constructor(string memory _name, string memory _symbol, uint _decimals, uint _totalSupply) {
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _totalSupply;
balanceOf[msg.sender] = totalSupply;
}
struct TradeOrder{
uint256 orderType;
uint256 amount;
uint256 limitedPrice;
address payable owner;
}
mapping(uint256 => TradeOrder) public buyOrders;
mapping(uint256 => TradeOrder) public sellOrders;
uint256 public totalBuys;
uint256 public totalSells;
function _insertBuyOrder(TradeOrder memory buyOrder) internal {
totalBuys = totalBuys + 1;
buyOrders[totalBuys-1] = buyOrder;
uint256 cursor = totalBuys - 1;
while (cursor > 0 && buyOrders[cursor-1].limitedPrice > buyOrders[cursor].limitedPrice) {
TradeOrder memory temp = buyOrders[cursor-1];
buyOrders[cursor-1] = buyOrders[cursor];
buyOrders[cursor] = temp;
cursor = cursor - 1;
}
}
function _insertBuyOrder(TradeOrder memory buyOrder) internal {
totalBuys = totalBuys + 1;
buyOrders[totalBuys-1] = buyOrder;
uint256 cursor = totalBuys - 1;
while (cursor > 0 && buyOrders[cursor-1].limitedPrice > buyOrders[cursor].limitedPrice) {
TradeOrder memory temp = buyOrders[cursor-1];
buyOrders[cursor-1] = buyOrders[cursor];
buyOrders[cursor] = temp;
cursor = cursor - 1;
}
}
function _insertSellOrder(TradeOrder memory sellOrder) internal {
totalSells = totalSells + 1;
sellOrders[totalSells-1] = sellOrder;
uint256 cursor = totalSells - 1;
while (cursor > 0 && sellOrders[cursor-1].limitedPrice < sellOrders[cursor].limitedPrice) {
TradeOrder memory temp = sellOrders[cursor-1];
sellOrders[cursor-1] = sellOrders[cursor];
sellOrders[cursor] = temp;
cursor = cursor - 1;
}
}
function _insertSellOrder(TradeOrder memory sellOrder) internal {
totalSells = totalSells + 1;
sellOrders[totalSells-1] = sellOrder;
uint256 cursor = totalSells - 1;
while (cursor > 0 && sellOrders[cursor-1].limitedPrice < sellOrders[cursor].limitedPrice) {
TradeOrder memory temp = sellOrders[cursor-1];
sellOrders[cursor-1] = sellOrders[cursor];
sellOrders[cursor] = temp;
cursor = cursor - 1;
}
}
function commitToMarket(uint256 orderType, uint256 amount, uint256 limitedPrice) external returns (bool success) {
require(amount > 0);
require(limitedPrice > 0);
require(orderType == 1 || orderType == 2);
uint256 usdtBalance = usdt.balanceOf(address(msg.sender));
require(usdtBalance >= limitedPrice * amount, "Not enough USDT in your wallet");
TradeOrder memory newOrder = TradeOrder(orderType, amount, limitedPrice, payable(msg.sender));
if (orderType == 1) {
if (usdt.transfer(RESERVED_WALLET_ADDRESS, amount * limitedPrice)) {
_insertBuyOrder(newOrder);
}
}
if (orderType == 2) {
_insertSellOrder(newOrder);
}
return true;
}
event FulfilledResult(uint256 amount);
function commitToMarket(uint256 orderType, uint256 amount, uint256 limitedPrice) external returns (bool success) {
require(amount > 0);
require(limitedPrice > 0);
require(orderType == 1 || orderType == 2);
uint256 usdtBalance = usdt.balanceOf(address(msg.sender));
require(usdtBalance >= limitedPrice * amount, "Not enough USDT in your wallet");
TradeOrder memory newOrder = TradeOrder(orderType, amount, limitedPrice, payable(msg.sender));
if (orderType == 1) {
if (usdt.transfer(RESERVED_WALLET_ADDRESS, amount * limitedPrice)) {
_insertBuyOrder(newOrder);
}
}
if (orderType == 2) {
_insertSellOrder(newOrder);
}
return true;
}
event FulfilledResult(uint256 amount);
function commitToMarket(uint256 orderType, uint256 amount, uint256 limitedPrice) external returns (bool success) {
require(amount > 0);
require(limitedPrice > 0);
require(orderType == 1 || orderType == 2);
uint256 usdtBalance = usdt.balanceOf(address(msg.sender));
require(usdtBalance >= limitedPrice * amount, "Not enough USDT in your wallet");
TradeOrder memory newOrder = TradeOrder(orderType, amount, limitedPrice, payable(msg.sender));
if (orderType == 1) {
if (usdt.transfer(RESERVED_WALLET_ADDRESS, amount * limitedPrice)) {
_insertBuyOrder(newOrder);
}
}
if (orderType == 2) {
_insertSellOrder(newOrder);
}
return true;
}
event FulfilledResult(uint256 amount);
function commitToMarket(uint256 orderType, uint256 amount, uint256 limitedPrice) external returns (bool success) {
require(amount > 0);
require(limitedPrice > 0);
require(orderType == 1 || orderType == 2);
uint256 usdtBalance = usdt.balanceOf(address(msg.sender));
require(usdtBalance >= limitedPrice * amount, "Not enough USDT in your wallet");
TradeOrder memory newOrder = TradeOrder(orderType, amount, limitedPrice, payable(msg.sender));
if (orderType == 1) {
if (usdt.transfer(RESERVED_WALLET_ADDRESS, amount * limitedPrice)) {
_insertBuyOrder(newOrder);
}
}
if (orderType == 2) {
_insertSellOrder(newOrder);
}
return true;
}
event FulfilledResult(uint256 amount);
function popBuyOrder() public {
require(totalBuys > 0);
totalBuys = totalBuys - 1;
emit FulfilledResult(buyOrders[totalBuys].amount);
}
function popSellOrder() public {
require(totalSells > 0);
totalSells = totalSells - 1;
emit FulfilledResult(sellOrders[totalSells].amount);
}
function transfer(address _to, uint256 _value) external returns (bool success) {
require(balanceOf[msg.sender] >= _value);
_transfer(msg.sender, _to, _value);
return true;
}
function _transfer(address _from, address _to, uint256 _value) internal {
require(_to != address(0));
balanceOf[_from] = balanceOf[_from] - (_value);
balanceOf[_to] = balanceOf[_to] + (_value);
emit Transfer(_from, _to, _value);
}
function approve(address _spender, uint256 _value) external returns (bool) {
require(_spender != address(0));
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) external returns (bool) {
require(_value <= balanceOf[_from]);
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] = allowance[_from][msg.sender] - (_value);
_transfer(_from, _to, _value);
return true;
}
}
| 13,344,261 | [
1,
12062,
23536,
10498,
3298,
324,
26488,
471,
1699,
6872,
20412,
9043,
300,
4452,
2641,
603,
919,
3478,
5527,
12449,
30,
374,
7669,
2226,
4033,
42,
29,
8204,
40,
22,
1340,
25,
4366,
69,
27246,
26,
3462,
26,
2733,
24,
6162,
27,
39,
3437,
40,
28,
6938,
557,
27,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
3155,
288,
203,
203,
565,
533,
1071,
508,
31,
203,
565,
533,
1071,
3273,
31,
203,
565,
2254,
5034,
1071,
15105,
31,
203,
565,
2254,
5034,
1071,
2078,
3088,
1283,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
11013,
951,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
1071,
1699,
1359,
31,
203,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
5034,
460,
1769,
203,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
3410,
16,
1758,
8808,
17571,
264,
16,
2254,
5034,
460,
1769,
203,
203,
565,
1758,
1071,
5381,
11836,
9081,
67,
6067,
2849,
1268,
67,
15140,
273,
374,
17593,
9975,
41,
27,
3437,
72,
6260,
21,
39,
6418,
41,
70,
38,
5034,
2643,
4630,
69,
23,
70,
25,
22201,
5895,
71,
7616,
26,
3247,
6938,
31,
203,
565,
467,
654,
39,
3462,
584,
7510,
273,
467,
654,
39,
3462,
12,
2867,
12,
3378,
9081,
67,
6067,
2849,
1268,
67,
15140,
10019,
203,
203,
565,
1758,
1071,
5381,
2438,
19501,
67,
59,
1013,
15146,
67,
15140,
273,
374,
92,
21,
74,
25,
1077,
25,
72,
24,
39,
29,
10160,
5340,
71,
28,
3028,
69,
22,
72,
42,
23,
16410,
6030,
69,
1611,
5324,
5026,
23,
41,
4313,
21,
42,
31,
203,
203,
565,
3885,
12,
1080,
3778,
389,
529,
16,
533,
3778,
389,
7175,
16,
2254,
389,
31734,
16,
2254,
389,
4963,
3088,
1283,
13,
288,
203,
3639,
508,
273,
389,
529,
31,
203,
3639,
3273,
2
] |
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./interfaces/IHabitat.sol";
import "./interfaces/IHouseTraits.sol";
import "./interfaces/ICHEDDAR.sol";
import "./interfaces/IHouse.sol";
import "./interfaces/IRandomizer.sol";
contract HouseGame is Ownable, ReentrancyGuard, Pausable {
event MintCommitted(address indexed owner, uint256 indexed amount);
event MintRevealed(address indexed owner, uint256 indexed amount);
struct MintCommit {
bool stake;
uint16 amount;
}
// address -> commit id -> commits
mapping(address => mapping(uint16 => MintCommit)) private _mintCommits;
// address -> commit num of commit need revealed for account
mapping(address => uint16) private _pendingCommitId;
// pending mint amount
uint16 private pendingMintAmt;
// flag for commits allowment
bool public allowCommits = true;
// address => can call addCommitRandom
mapping(address => bool) private admins;
// reference to the Habitat for choosing random Cat thieves
IHabitat public habitat;
// reference to $CHEDDAR for burning on mint
ICHEDDAR public cheddarToken;
// reference to House Traits
IHouseTraits public houseTraits;
// reference to House NFT collection
IHouse public houseNFT;
// reference to IRandomizer
IRandomizer public randomizer;
constructor() {
_pause();
}
/** CRITICAL TO SETUP */
modifier requireContractsSet() {
require(address(cheddarToken) != address(0) && address(houseTraits) != address(0)
&& address(habitat) != address(0) && address(houseNFT) != address(0) && address(randomizer) != address(0)
, "Contracts not set");
_;
}
function setContracts(address _cheddar,address _houseTraits, address _habitat, address _house, address _randomizer) external onlyOwner {
cheddarToken = ICHEDDAR(_cheddar);
habitat = IHabitat(_habitat);
houseNFT = IHouse(_house);
houseTraits = IHouseTraits(_houseTraits);
randomizer = IRandomizer(_randomizer);
}
/** EXTERNAL */
function getPendingMint(address addr) external view returns (MintCommit memory) {
require(_pendingCommitId[addr] != 0, "no pending commits");
return _mintCommits[addr][_pendingCommitId[addr]];
}
function hasMintPending(address addr) external view returns (bool) {
return _pendingCommitId[addr] != 0;
}
function canMint(address addr) external view returns (bool) {
return _pendingCommitId[addr] != 0 && randomizer.getCommitRandom(_pendingCommitId[addr]) > 0;
}
function deleteCommit(address addr) external {
require(owner() == _msgSender() || admins[_msgSender()], "Only admins can call this");
uint16 commitIdCur = _pendingCommitId[_msgSender()];
require(commitIdCur > 0, "No pending commit");
delete _mintCommits[addr][commitIdCur];
delete _pendingCommitId[addr];
}
function forceRevealCommit(address addr) external {
require(owner() == _msgSender() || admins[_msgSender()], "Only admins can call this");
reveal(addr);
}
/** Initiate the start of a mint. This action burns $CHEDDAR, as the intent of committing is that you cannot back out once you've started.
* This will add users into the pending queue, to be revealed after a random seed is generated and assigned to the commit id this
* commit was added to. */
function mintCommit(uint256 amount, bool stake) external whenNotPaused nonReentrant {
require(allowCommits, "adding commits disallowed");
require(tx.origin == _msgSender(), "Only EOA");
require(_pendingCommitId[_msgSender()] == 0, "Already have pending mints");
uint16 minted = houseNFT.minted();
uint256 maxTokens = houseNFT.getMaxTokens();
require(minted + pendingMintAmt + amount <= maxTokens, "All tokens minted");
require(amount > 0 && amount <= 10, "Invalid mint amount");
uint256 totalCheddarCost = 0;
// Loop through the amount of
for (uint i = 1; i <= amount; i++) {
totalCheddarCost += mintCost(minted + pendingMintAmt + i, maxTokens);
}
if (totalCheddarCost > 0) {
cheddarToken.burn(_msgSender(), totalCheddarCost);
cheddarToken.updateOriginAccess();
}
uint16 amt = uint16(amount);
_mintCommits[_msgSender()][randomizer.commitId()] = MintCommit(stake, amt);
_pendingCommitId[_msgSender()] = randomizer.commitId();
pendingMintAmt += amt;
emit MintCommitted(_msgSender(), amount);
}
/** Reveal the commits for this user. This will be when the user gets their NFT, and can only be done when the commit id that
* the user is pending for has been assigned a random seed. */
function mintReveal() external whenNotPaused nonReentrant {
require(tx.origin == _msgSender(), "Only EOA1");
reveal(_msgSender());
}
function reveal(address addr) internal {
uint16 commitIdCur = _pendingCommitId[addr];
uint256 seed = randomizer.getCommitRandom(commitIdCur);
require(commitIdCur > 0, "No pending commit");
require(seed > 0, "random seed not set");
uint16 minted = houseNFT.minted();
MintCommit memory commit = _mintCommits[addr][commitIdCur];
pendingMintAmt -= commit.amount;
uint16[] memory tokenIds = new uint16[](commit.amount);
uint16[] memory tokenIdsToStake = new uint16[](commit.amount);
for (uint k = 0; k < commit.amount; k++) {
minted++;
// scramble the random so the steal / treasure mechanic are different per mint
seed = uint256(keccak256(abi.encode(seed, addr)));
address recipient = selectRecipient(seed);
tokenIds[k] = minted;
if (!commit.stake || recipient != addr) {
houseNFT.mint(recipient, seed);
} else {
houseNFT.mint(address(habitat), seed);
tokenIdsToStake[k] = minted;
}
}
houseNFT.updateOriginAccess(tokenIds);
if(commit.stake) {
habitat.addManyHouseToStakingPool(addr, tokenIdsToStake);
}
delete _mintCommits[addr][commitIdCur];
delete _pendingCommitId[addr];
emit MintRevealed(addr, tokenIds.length);
}
/**
* the first 25% are 80000 $CHEDDAR
* the next 50% are 160000 $CHEDDAR
* the next 25% are 320000 $WOOL
* @param tokenId the ID to check the cost of to mint
* @return the cost of the given token ID
*/
function mintCost(uint256 tokenId, uint256 maxTokens) public pure returns (uint256) {
if (tokenId <= maxTokens / 4) return 80000 ether;
if (tokenId <= maxTokens * 3 / 4) return 160000 ether;
return 320000 ether;
}
/** INTERNAL */
/**
* @param seed a random value to select a recipient from
* @return the address of the recipient (either the minter or the Cat thief's owner)
*/
function selectRecipient(uint256 seed) internal view returns (address) {
if (((seed >> 245) % 8) != 0) return _msgSender(); // top 8 bits haven't been used
address thief = habitat.randomCrazyCatOwner(seed >> 144); // 144 bits reserved for trait selection
if (thief == address(0x0)) return _msgSender();
return thief;
}
/** ADMIN */
/**
* enables owner to pause / unpause contract
*/
function setPaused(bool _paused) external requireContractsSet onlyOwner {
if (_paused) _pause();
else _unpause();
}
function setAllowCommits(bool allowed) external onlyOwner {
allowCommits = allowed;
}
/** Allow the contract owner to set the pending mint amount.
* This allows any long-standing pending commits to be overwritten, say for instance if the max supply has been
* reached but there are many stale pending commits, it could be used to free up those spaces if needed/desired by the community.
* This function should not be called lightly, this will have negative consequences on the game. */
function setPendingMintAmt(uint256 pendingAmt) external onlyOwner {
pendingMintAmt = uint16(pendingAmt);
}
/**
* enables an address to mint / burn
* @param addr the address to enable
*/
function addAdmin(address addr) external onlyOwner {
admins[addr] = true;
}
/**
* disables an address from minting / burning
* @param addr the address to disbale
*/
function removeAdmin(address addr) external onlyOwner {
admins[addr] = false;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface IHabitat {
function addManyToStakingPool(address account, uint16[] calldata tokenIds) external;
function addManyHouseToStakingPool(address account, uint16[] calldata tokenIds) external;
function randomCatOwner(uint256 seed) external view returns (address);
function randomCrazyCatOwner(uint256 seed) external view returns (address);
function isOwner(uint256 tokenId, address owner) external view returns (bool);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface IHouseTraits {
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface ICHEDDAR {
function mint(address to, uint256 amount) external;
function burn(address from, uint256 amount) external;
function updateOriginAccess() external;
function transferFrom(address sender, address recipient, uint256 amount) external returns(bool);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
interface IHouse is IERC721Enumerable {
// House NFT struct
struct HouseStruct {
uint8 roll; //0 - Shack, 1 - Ranch, 2 - Mansion
uint8 body;
}
function getTokenWriteBlock(uint256 tokenId) external view returns(uint64);
function mint(address recipient, uint256 seed) external;
function burn(uint256 tokenId) external;
function updateOriginAccess(uint16[] memory tokenIds) external;
function isShack(uint256 tokenId) external view returns(bool);
function isRanch(uint256 tokenId) external view returns(bool);
function isMansion(uint256 tokenId) external view returns(bool);
function getMaxTokens() external view returns (uint256);
function getTokenTraits(uint256 tokenId) external view returns (HouseStruct memory);
function minted() external view returns (uint16);
function emitShackStakedEvent(address owner, uint256 tokenId) external;
function emitRanchStakedEvent(address owner, uint256 tokenId) external;
function emitMansionStakedEvent(address owner, uint256 tokenId) external;
function emitShackUnStakedEvent(address owner, uint256 tokenId) external;
function emitRanchUnStakedEvent(address owner, uint256 tokenId) external;
function emitMansionUnStakedEvent(address owner, uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface IRandomizer {
function commitId() external view returns (uint16);
function getCommitRandom(uint16 id) external view returns (uint256);
function random() external returns (uint256);
function sRandom(uint256 tokenId) external returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
| SPDX-License-Identifier: MIT LICENSE | interface IRandomizer {
function commitId() external view returns (uint16);
function getCommitRandom(uint16 id) external view returns (uint256);
function random() external returns (uint256);
function sRandom(uint256 tokenId) external returns (uint256);
}
| 12,755,992 | [
1,
3118,
28826,
17,
13211,
17,
3004,
30,
490,
1285,
511,
2871,
23396,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
8529,
1824,
288,
203,
565,
445,
3294,
548,
1435,
3903,
1476,
1135,
261,
11890,
2313,
1769,
203,
565,
445,
336,
5580,
8529,
12,
11890,
2313,
612,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
2744,
1435,
3903,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
272,
8529,
12,
11890,
5034,
1147,
548,
13,
3903,
1135,
261,
11890,
5034,
1769,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.