file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
./partial_match/83/0x1cF350DA842D4816c2978691D93e4670EEd7e10D/sources/VRFProvider.sol
|
Decodes the encoded data request response result encodedResult Encoded result data
|
function decodeResult(bytes memory encodedResult)
internal
pure
returns (bytes32 result)
{
Obi.Data memory decoder = Obi.from(encodedResult);
result = bytes32(decoder.decodeBytes());
require(decoder.finished(), "DATA_DECODE_NOT_FINISHED");
}
| 8,829,011 |
./full_match/137/0xe558726C468Ccc21cc09ca4B8B46131dC1002923/sources/project_/contracts/Exchange.sol
|
Load the quantity filled so far for a partially filled orders Invalidating an order nonce will not clear partial fill quantities for earlier orders because the gas cost would potentially be unbound orderHash The order hash as originally signed by placing wallet that uniquely identifies an order return For partially filled orders, the amount filled so far in pips. For orders in all other states, 0/
|
function loadPartiallyFilledOrderQuantityInPips(bytes32 orderHash)
external
view
returns (uint64)
{
return _partiallyFilledOrderQuantitiesInPips[orderHash];
}
| 4,761,966 |
//Address: 0x07307d0b136a79bac718f43388aed706389c4588
//Contract name: Alarm
//Balance: 0.3491158383 Ether
//Verification Date: 2/15/2017
//Transacion Count: 16
// CODE STARTS HERE
// String Utils v0.1
/// @title String Utils - String utility functions
/// @author Piper Merriam -
library StringLib {
/*
* Address: 0x443b53559d337277373171280ec57029718203fb
*/
/// @dev Converts an unsigned integert to its string representation.
/// @param v The number to be converted.
function uintToBytes(uint v) constant returns (bytes32 ret) {
if (v == 0) {
ret = '0';
}
else {
while (v > 0) {
ret = bytes32(uint(ret) / (2 ** 8));
ret |= bytes32(((v % 10) + 48) * 2 ** (8 * 31));
v /= 10;
}
}
return ret;
}
/// @dev Converts a numeric string to it's unsigned integer representation.
/// @param v The string to be converted.
function bytesToUInt(bytes32 v) constant returns (uint ret) {
if (v == 0x0) {
throw;
}
uint digit;
for (uint i = 0; i < 32; i++) {
digit = uint((uint(v) / (2 ** (8 * (31 - i)))) & 0xff);
if (digit == 0) {
break;
}
else if (digit < 48 || digit > 57) {
throw;
}
ret *= 10;
ret += (digit - 48);
}
return ret;
}
}
// Accounting v0.1 (not the same as the 0.1 release of this library)
/// @title Accounting Lib - Accounting utilities
/// @author Piper Merriam -
library AccountingLib {
/*
* Address: 0x7de615d8a51746a9f10f72a593fb5b3718dc3d52
*/
struct Bank {
mapping (address => uint) accountBalances;
}
/// @dev Low level method for adding funds to an account. Protects against overflow.
/// @param self The Bank instance to operate on.
/// @param accountAddress The address of the account the funds should be added to.
/// @param value The amount that should be added to the account.
function addFunds(Bank storage self, address accountAddress, uint value) public {
if (self.accountBalances[accountAddress] + value < self.accountBalances[accountAddress]) {
// Prevent Overflow.
throw;
}
self.accountBalances[accountAddress] += value;
}
event _Deposit(address indexed _from, address indexed accountAddress, uint value);
/// @dev Function wrapper around the _Deposit event so that it can be used by contracts. Can be used to log a deposit to an account.
/// @param _from The address that deposited the funds.
/// @param accountAddress The address of the account the funds were added to.
/// @param value The amount that was added to the account.
function Deposit(address _from, address accountAddress, uint value) public {
_Deposit(_from, accountAddress, value);
}
/// @dev Safe function for depositing funds. Returns boolean for whether the deposit was successful
/// @param self The Bank instance to operate on.
/// @param accountAddress The address of the account the funds should be added to.
/// @param value The amount that should be added to the account.
function deposit(Bank storage self, address accountAddress, uint value) public returns (bool) {
addFunds(self, accountAddress, value);
return true;
}
event _Withdrawal(address indexed accountAddress, uint value);
/// @dev Function wrapper around the _Withdrawal event so that it can be used by contracts. Can be used to log a withdrawl from an account.
/// @param accountAddress The address of the account the funds were withdrawn from.
/// @param value The amount that was withdrawn to the account.
function Withdrawal(address accountAddress, uint value) public {
_Withdrawal(accountAddress, value);
}
event _InsufficientFunds(address indexed accountAddress, uint value, uint balance);
/// @dev Function wrapper around the _InsufficientFunds event so that it can be used by contracts. Can be used to log a failed withdrawl from an account.
/// @param accountAddress The address of the account the funds were to be withdrawn from.
/// @param value The amount that was attempted to be withdrawn from the account.
/// @param balance The current balance of the account.
function InsufficientFunds(address accountAddress, uint value, uint balance) public {
_InsufficientFunds(accountAddress, value, balance);
}
/// @dev Low level method for removing funds from an account. Protects against underflow.
/// @param self The Bank instance to operate on.
/// @param accountAddress The address of the account the funds should be deducted from.
/// @param value The amount that should be deducted from the account.
function deductFunds(Bank storage self, address accountAddress, uint value) public {
/*
* Helper function that should be used for any reduction of
* account funds. It has error checking to prevent
* underflowing the account balance which would be REALLY bad.
*/
if (value > self.accountBalances[accountAddress]) {
// Prevent Underflow.
throw;
}
self.accountBalances[accountAddress] -= value;
}
/// @dev Safe function for withdrawing funds. Returns boolean for whether the deposit was successful as well as sending the amount in ether to the account address.
/// @param self The Bank instance to operate on.
/// @param accountAddress The address of the account the funds should be withdrawn from.
/// @param value The amount that should be withdrawn from the account.
function withdraw(Bank storage self, address accountAddress, uint value) public returns (bool) {
/*
* Public API for withdrawing funds.
*/
if (self.accountBalances[accountAddress] >= value) {
deductFunds(self, accountAddress, value);
if (!accountAddress.send(value)) {
// Potentially sending money to a contract that
// has a fallback function. So instead, try
// tranferring the funds with the call api.
if (!accountAddress.call.value(value)()) {
// Revert the entire transaction. No
// need to destroy the funds.
throw;
}
}
return true;
}
return false;
}
}
// Grove v0.3 (not the same as the 0.3 release of this library)
/// @title GroveLib - Library for queriable indexed ordered data.
/// @author PiperMerriam -
library GroveLib {
/*
* Indexes for ordered data
*
* Address: 0x920c890a90db8fba7604864b0cf38ee667331323
*/
struct Index {
bytes32 root;
mapping (bytes32 => Node) nodes;
}
struct Node {
bytes32 id;
int value;
bytes32 parent;
bytes32 left;
bytes32 right;
uint height;
}
function max(uint a, uint b) internal returns (uint) {
if (a >= b) {
return a;
}
return b;
}
/*
* Node getters
*/
/// @dev Retrieve the unique identifier for the node.
/// @param index The index that the node is part of.
/// @param id The id for the node to be looked up.
function getNodeId(Index storage index, bytes32 id) constant returns (bytes32) {
return index.nodes[id].id;
}
/// @dev Retrieve the value for the node.
/// @param index The index that the node is part of.
/// @param id The id for the node to be looked up.
function getNodeValue(Index storage index, bytes32 id) constant returns (int) {
return index.nodes[id].value;
}
/// @dev Retrieve the height of the node.
/// @param index The index that the node is part of.
/// @param id The id for the node to be looked up.
function getNodeHeight(Index storage index, bytes32 id) constant returns (uint) {
return index.nodes[id].height;
}
/// @dev Retrieve the parent id of the node.
/// @param index The index that the node is part of.
/// @param id The id for the node to be looked up.
function getNodeParent(Index storage index, bytes32 id) constant returns (bytes32) {
return index.nodes[id].parent;
}
/// @dev Retrieve the left child id of the node.
/// @param index The index that the node is part of.
/// @param id The id for the node to be looked up.
function getNodeLeftChild(Index storage index, bytes32 id) constant returns (bytes32) {
return index.nodes[id].left;
}
/// @dev Retrieve the right child id of the node.
/// @param index The index that the node is part of.
/// @param id The id for the node to be looked up.
function getNodeRightChild(Index storage index, bytes32 id) constant returns (bytes32) {
return index.nodes[id].right;
}
/// @dev Retrieve the node id of the next node in the tree.
/// @param index The index that the node is part of.
/// @param id The id for the node to be looked up.
function getPreviousNode(Index storage index, bytes32 id) constant returns (bytes32) {
Node storage currentNode = index.nodes[id];
if (currentNode.id == 0x0) {
// Unknown node, just return 0x0;
return 0x0;
}
Node memory child;
if (currentNode.left != 0x0) {
// Trace left to latest child in left tree.
child = index.nodes[currentNode.left];
while (child.right != 0) {
child = index.nodes[child.right];
}
return child.id;
}
if (currentNode.parent != 0x0) {
// Now we trace back up through parent relationships, looking
// for a link where the child is the right child of it's
// parent.
Node storage parent = index.nodes[currentNode.parent];
child = currentNode;
while (true) {
if (parent.right == child.id) {
return parent.id;
}
if (parent.parent == 0x0) {
break;
}
child = parent;
parent = index.nodes[parent.parent];
}
}
// This is the first node, and has no previous node.
return 0x0;
}
/// @dev Retrieve the node id of the previous node in the tree.
/// @param index The index that the node is part of.
/// @param id The id for the node to be looked up.
function getNextNode(Index storage index, bytes32 id) constant returns (bytes32) {
Node storage currentNode = index.nodes[id];
if (currentNode.id == 0x0) {
// Unknown node, just return 0x0;
return 0x0;
}
Node memory child;
if (currentNode.right != 0x0) {
// Trace right to earliest child in right tree.
child = index.nodes[currentNode.right];
while (child.left != 0) {
child = index.nodes[child.left];
}
return child.id;
}
if (currentNode.parent != 0x0) {
// if the node is the left child of it's parent, then the
// parent is the next one.
Node storage parent = index.nodes[currentNode.parent];
child = currentNode;
while (true) {
if (parent.left == child.id) {
return parent.id;
}
if (parent.parent == 0x0) {
break;
}
child = parent;
parent = index.nodes[parent.parent];
}
// Now we need to trace all the way up checking to see if any parent is the
}
// This is the final node.
return 0x0;
}
/// @dev Updates or Inserts the id into the index at its appropriate location based on the value provided.
/// @param index The index that the node is part of.
/// @param id The unique identifier of the data element the index node will represent.
/// @param value The value of the data element that represents it's total ordering with respect to other elementes.
function insert(Index storage index, bytes32 id, int value) public {
if (index.nodes[id].id == id) {
// A node with this id already exists. If the value is
// the same, then just return early, otherwise, remove it
// and reinsert it.
if (index.nodes[id].value == value) {
return;
}
remove(index, id);
}
uint leftHeight;
uint rightHeight;
bytes32 previousNodeId = 0x0;
if (index.root == 0x0) {
index.root = id;
}
Node storage currentNode = index.nodes[index.root];
// Do insertion
while (true) {
if (currentNode.id == 0x0) {
// This is a new unpopulated node.
currentNode.id = id;
currentNode.parent = previousNodeId;
currentNode.value = value;
break;
}
// Set the previous node id.
previousNodeId = currentNode.id;
// The new node belongs in the right subtree
if (value >= currentNode.value) {
if (currentNode.right == 0x0) {
currentNode.right = id;
}
currentNode = index.nodes[currentNode.right];
continue;
}
// The new node belongs in the left subtree.
if (currentNode.left == 0x0) {
currentNode.left = id;
}
currentNode = index.nodes[currentNode.left];
}
// Rebalance the tree
_rebalanceTree(index, currentNode.id);
}
/// @dev Checks whether a node for the given unique identifier exists within the given index.
/// @param index The index that should be searched
/// @param id The unique identifier of the data element to check for.
function exists(Index storage index, bytes32 id) constant returns (bool) {
return (index.nodes[id].id == id);
}
/// @dev Remove the node for the given unique identifier from the index.
/// @param index The index that should be removed
/// @param id The unique identifier of the data element to remove.
function remove(Index storage index, bytes32 id) public {
Node storage replacementNode;
Node storage parent;
Node storage child;
bytes32 rebalanceOrigin;
Node storage nodeToDelete = index.nodes[id];
if (nodeToDelete.id != id) {
// The id does not exist in the tree.
return;
}
if (nodeToDelete.left != 0x0 || nodeToDelete.right != 0x0) {
// This node is not a leaf node and thus must replace itself in
// it's tree by either the previous or next node.
if (nodeToDelete.left != 0x0) {
// This node is guaranteed to not have a right child.
replacementNode = index.nodes[getPreviousNode(index, nodeToDelete.id)];
}
else {
// This node is guaranteed to not have a left child.
replacementNode = index.nodes[getNextNode(index, nodeToDelete.id)];
}
// The replacementNode is guaranteed to have a parent.
parent = index.nodes[replacementNode.parent];
// Keep note of the location that our tree rebalancing should
// start at.
rebalanceOrigin = replacementNode.id;
// Join the parent of the replacement node with any subtree of
// the replacement node. We can guarantee that the replacement
// node has at most one subtree because of how getNextNode and
// getPreviousNode are used.
if (parent.left == replacementNode.id) {
parent.left = replacementNode.right;
if (replacementNode.right != 0x0) {
child = index.nodes[replacementNode.right];
child.parent = parent.id;
}
}
if (parent.right == replacementNode.id) {
parent.right = replacementNode.left;
if (replacementNode.left != 0x0) {
child = index.nodes[replacementNode.left];
child.parent = parent.id;
}
}
// Now we replace the nodeToDelete with the replacementNode.
// This includes parent/child relationships for all of the
// parent, the left child, and the right child.
replacementNode.parent = nodeToDelete.parent;
if (nodeToDelete.parent != 0x0) {
parent = index.nodes[nodeToDelete.parent];
if (parent.left == nodeToDelete.id) {
parent.left = replacementNode.id;
}
if (parent.right == nodeToDelete.id) {
parent.right = replacementNode.id;
}
}
else {
// If the node we are deleting is the root node update the
// index root node pointer.
index.root = replacementNode.id;
}
replacementNode.left = nodeToDelete.left;
if (nodeToDelete.left != 0x0) {
child = index.nodes[nodeToDelete.left];
child.parent = replacementNode.id;
}
replacementNode.right = nodeToDelete.right;
if (nodeToDelete.right != 0x0) {
child = index.nodes[nodeToDelete.right];
child.parent = replacementNode.id;
}
}
else if (nodeToDelete.parent != 0x0) {
// The node being deleted is a leaf node so we only erase it's
// parent linkage.
parent = index.nodes[nodeToDelete.parent];
if (parent.left == nodeToDelete.id) {
parent.left = 0x0;
}
if (parent.right == nodeToDelete.id) {
parent.right = 0x0;
}
// keep note of where the rebalancing should begin.
rebalanceOrigin = parent.id;
}
else {
// This is both a leaf node and the root node, so we need to
// unset the root node pointer.
index.root = 0x0;
}
// Now we zero out all of the fields on the nodeToDelete.
nodeToDelete.id = 0x0;
nodeToDelete.value = 0;
nodeToDelete.parent = 0x0;
nodeToDelete.left = 0x0;
nodeToDelete.right = 0x0;
// Walk back up the tree rebalancing
if (rebalanceOrigin != 0x0) {
_rebalanceTree(index, rebalanceOrigin);
}
}
bytes2 constant GT = ">";
bytes2 constant LT = "<";
bytes2 constant GTE = ">=";
bytes2 constant LTE = "<=";
bytes2 constant EQ = "==";
function _compare(int left, bytes2 operator, int right) internal returns (bool) {
if (operator == GT) {
return (left > right);
}
if (operator == LT) {
return (left < right);
}
if (operator == GTE) {
return (left >= right);
}
if (operator == LTE) {
return (left <= right);
}
if (operator == EQ) {
return (left == right);
}
// Invalid operator.
throw;
}
function _getMaximum(Index storage index, bytes32 id) internal returns (int) {
Node storage currentNode = index.nodes[id];
while (true) {
if (currentNode.right == 0x0) {
return currentNode.value;
}
currentNode = index.nodes[currentNode.right];
}
}
function _getMinimum(Index storage index, bytes32 id) internal returns (int) {
Node storage currentNode = index.nodes[id];
while (true) {
if (currentNode.left == 0x0) {
return currentNode.value;
}
currentNode = index.nodes[currentNode.left];
}
}
/** @dev Query the index for the edge-most node that satisfies the
* given query. For >, >=, and ==, this will be the left-most node
* that satisfies the comparison. For < and <= this will be the
* right-most node that satisfies the comparison.
*/
/// @param index The index that should be queried
/** @param operator One of '>', '>=', '<', '<=', '==' to specify what
* type of comparison operator should be used.
*/
function query(Index storage index, bytes2 operator, int value) public returns (bytes32) {
bytes32 rootNodeId = index.root;
if (rootNodeId == 0x0) {
// Empty tree.
return 0x0;
}
Node storage currentNode = index.nodes[rootNodeId];
while (true) {
if (_compare(currentNode.value, operator, value)) {
// We have found a match but it might not be the
// *correct* match.
if ((operator == LT) || (operator == LTE)) {
// Need to keep traversing right until this is no
// longer true.
if (currentNode.right == 0x0) {
return currentNode.id;
}
if (_compare(_getMinimum(index, currentNode.right), operator, value)) {
// There are still nodes to the right that
// match.
currentNode = index.nodes[currentNode.right];
continue;
}
return currentNode.id;
}
if ((operator == GT) || (operator == GTE) || (operator == EQ)) {
// Need to keep traversing left until this is no
// longer true.
if (currentNode.left == 0x0) {
return currentNode.id;
}
if (_compare(_getMaximum(index, currentNode.left), operator, value)) {
currentNode = index.nodes[currentNode.left];
continue;
}
return currentNode.id;
}
}
if ((operator == LT) || (operator == LTE)) {
if (currentNode.left == 0x0) {
// There are no nodes that are less than the value
// so return null.
return 0x0;
}
currentNode = index.nodes[currentNode.left];
continue;
}
if ((operator == GT) || (operator == GTE)) {
if (currentNode.right == 0x0) {
// There are no nodes that are greater than the value
// so return null.
return 0x0;
}
currentNode = index.nodes[currentNode.right];
continue;
}
if (operator == EQ) {
if (currentNode.value < value) {
if (currentNode.right == 0x0) {
return 0x0;
}
currentNode = index.nodes[currentNode.right];
continue;
}
if (currentNode.value > value) {
if (currentNode.left == 0x0) {
return 0x0;
}
currentNode = index.nodes[currentNode.left];
continue;
}
}
}
}
function _rebalanceTree(Index storage index, bytes32 id) internal {
// Trace back up rebalancing the tree and updating heights as
// needed..
Node storage currentNode = index.nodes[id];
while (true) {
int balanceFactor = _getBalanceFactor(index, currentNode.id);
if (balanceFactor == 2) {
// Right rotation (tree is heavy on the left)
if (_getBalanceFactor(index, currentNode.left) == -1) {
// The subtree is leaning right so it need to be
// rotated left before the current node is rotated
// right.
_rotateLeft(index, currentNode.left);
}
_rotateRight(index, currentNode.id);
}
if (balanceFactor == -2) {
// Left rotation (tree is heavy on the right)
if (_getBalanceFactor(index, currentNode.right) == 1) {
// The subtree is leaning left so it need to be
// rotated right before the current node is rotated
// left.
_rotateRight(index, currentNode.right);
}
_rotateLeft(index, currentNode.id);
}
if ((-1 <= balanceFactor) && (balanceFactor <= 1)) {
_updateNodeHeight(index, currentNode.id);
}
if (currentNode.parent == 0x0) {
// Reached the root which may be new due to tree
// rotation, so set it as the root and then break.
break;
}
currentNode = index.nodes[currentNode.parent];
}
}
function _getBalanceFactor(Index storage index, bytes32 id) internal returns (int) {
Node storage node = index.nodes[id];
return int(index.nodes[node.left].height) - int(index.nodes[node.right].height);
}
function _updateNodeHeight(Index storage index, bytes32 id) internal {
Node storage node = index.nodes[id];
node.height = max(index.nodes[node.left].height, index.nodes[node.right].height) + 1;
}
function _rotateLeft(Index storage index, bytes32 id) internal {
Node storage originalRoot = index.nodes[id];
if (originalRoot.right == 0x0) {
// Cannot rotate left if there is no right originalRoot to rotate into
// place.
throw;
}
// The right child is the new root, so it gets the original
// `originalRoot.parent` as it's parent.
Node storage newRoot = index.nodes[originalRoot.right];
newRoot.parent = originalRoot.parent;
// The original root needs to have it's right child nulled out.
originalRoot.right = 0x0;
if (originalRoot.parent != 0x0) {
// If there is a parent node, it needs to now point downward at
// the newRoot which is rotating into the place where `node` was.
Node storage parent = index.nodes[originalRoot.parent];
// figure out if we're a left or right child and have the
// parent point to the new node.
if (parent.left == originalRoot.id) {
parent.left = newRoot.id;
}
if (parent.right == originalRoot.id) {
parent.right = newRoot.id;
}
}
if (newRoot.left != 0) {
// If the new root had a left child, that moves to be the
// new right child of the original root node
Node storage leftChild = index.nodes[newRoot.left];
originalRoot.right = leftChild.id;
leftChild.parent = originalRoot.id;
}
// Update the newRoot's left node to point at the original node.
originalRoot.parent = newRoot.id;
newRoot.left = originalRoot.id;
if (newRoot.parent == 0x0) {
index.root = newRoot.id;
}
// TODO: are both of these updates necessary?
_updateNodeHeight(index, originalRoot.id);
_updateNodeHeight(index, newRoot.id);
}
function _rotateRight(Index storage index, bytes32 id) internal {
Node storage originalRoot = index.nodes[id];
if (originalRoot.left == 0x0) {
// Cannot rotate right if there is no left node to rotate into
// place.
throw;
}
// The left child is taking the place of node, so we update it's
// parent to be the original parent of the node.
Node storage newRoot = index.nodes[originalRoot.left];
newRoot.parent = originalRoot.parent;
// Null out the originalRoot.left
originalRoot.left = 0x0;
if (originalRoot.parent != 0x0) {
// If the node has a parent, update the correct child to point
// at the newRoot now.
Node storage parent = index.nodes[originalRoot.parent];
if (parent.left == originalRoot.id) {
parent.left = newRoot.id;
}
if (parent.right == originalRoot.id) {
parent.right = newRoot.id;
}
}
if (newRoot.right != 0x0) {
Node storage rightChild = index.nodes[newRoot.right];
originalRoot.left = newRoot.right;
rightChild.parent = originalRoot.id;
}
// Update the new root's right node to point to the original node.
originalRoot.parent = newRoot.id;
newRoot.right = originalRoot.id;
if (newRoot.parent == 0x0) {
index.root = newRoot.id;
}
// Recompute heights.
_updateNodeHeight(index, originalRoot.id);
_updateNodeHeight(index, newRoot.id);
}
}
// Resource Pool v0.1.0 (has been modified from the main released version of this library)
// @title ResourcePoolLib - Library for a set of resources that are ready for use.
// @author Piper Merriam
library ResourcePoolLib {
/*
* Address: 0xd6bbd16eaa6ea3f71a458bffc64c0ca24fc8c58e
*/
struct Pool {
uint rotationDelay;
uint overlapSize;
uint freezePeriod;
uint _id;
GroveLib.Index generationStart;
GroveLib.Index generationEnd;
mapping (uint => Generation) generations;
mapping (address => uint) bonds;
}
/*
* Generations have the following properties.
*
* 1. Must always overlap by a minimum amount specified by MIN_OVERLAP.
*
* 1 2 3 4 5 6 7 8 9 10 11 12 13
* [1:-----------------]
* [4:--------------------->
*/
struct Generation {
uint id;
uint startAt;
uint endAt;
address[] members;
}
/// @dev Creates the next generation for the given pool. All members from the current generation are carried over (with their order randomized). The current generation will have it's endAt block set.
/// @param self The pool to operate on.
function createNextGeneration(Pool storage self) public returns (uint) {
/*
* Creat a new pool generation with all of the current
* generation's members copied over in random order.
*/
Generation storage previousGeneration = self.generations[self._id];
self._id += 1;
Generation storage nextGeneration = self.generations[self._id];
nextGeneration.id = self._id;
nextGeneration.startAt = block.number + self.freezePeriod + self.rotationDelay;
GroveLib.insert(self.generationStart, StringLib.uintToBytes(nextGeneration.id), int(nextGeneration.startAt));
if (previousGeneration.id == 0) {
// This is the first generation so we just need to set
// it's `id` and `startAt`.
return nextGeneration.id;
}
// Set the end date for the current generation.
previousGeneration.endAt = block.number + self.freezePeriod + self.rotationDelay + self.overlapSize;
GroveLib.insert(self.generationEnd, StringLib.uintToBytes(previousGeneration.id), int(previousGeneration.endAt));
// Now we copy the members of the previous generation over to
// the next generation as well as randomizing their order.
address[] memory members = previousGeneration.members;
for (uint i = 0; i < members.length; i++) {
// Pick a *random* index and push it onto the next
// generation's members.
uint index = uint(sha3(block.blockhash(block.number))) % (members.length - nextGeneration.members.length);
nextGeneration.members.length += 1;
nextGeneration.members[nextGeneration.members.length - 1] = members[index];
// Then move the member at the last index into the picked
// index's location.
members[index] = members[members.length - 1];
}
return nextGeneration.id;
}
/// @dev Returns the first generation id that fully contains the block window provided.
/// @param self The pool to operate on.
/// @param leftBound The left bound for the block window (inclusive)
/// @param rightBound The right bound for the block window (inclusive)
function getGenerationForWindow(Pool storage self, uint leftBound, uint rightBound) constant returns (uint) {
// TODO: tests
var left = GroveLib.query(self.generationStart, "<=", int(leftBound));
if (left != 0x0) {
Generation memory leftCandidate = self.generations[StringLib.bytesToUInt(left)];
if (leftCandidate.startAt <= leftBound && (leftCandidate.endAt >= rightBound || leftCandidate.endAt == 0)) {
return leftCandidate.id;
}
}
var right = GroveLib.query(self.generationEnd, ">=", int(rightBound));
if (right != 0x0) {
Generation memory rightCandidate = self.generations[StringLib.bytesToUInt(right)];
if (rightCandidate.startAt <= leftBound && (rightCandidate.endAt >= rightBound || rightCandidate.endAt == 0)) {
return rightCandidate.id;
}
}
return 0;
}
/// @dev Returns the first generation in the future that has not yet started.
/// @param self The pool to operate on.
function getNextGenerationId(Pool storage self) constant returns (uint) {
// TODO: tests
var next = GroveLib.query(self.generationStart, ">", int(block.number));
if (next == 0x0) {
return 0;
}
return StringLib.bytesToUInt(next);
}
/// @dev Returns the first generation that is currently active.
/// @param self The pool to operate on.
function getCurrentGenerationId(Pool storage self) constant returns (uint) {
// TODO: tests
var next = GroveLib.query(self.generationEnd, ">", int(block.number));
if (next != 0x0) {
return StringLib.bytesToUInt(next);
}
next = GroveLib.query(self.generationStart, "<=", int(block.number));
if (next != 0x0) {
return StringLib.bytesToUInt(next);
}
return 0;
}
/*
* Pool membership API
*/
/// @dev Returns a boolean for whether the given address is in the given generation.
/// @param self The pool to operate on.
/// @param resourceAddress The address to check membership of
/// @param generationId The id of the generation to check.
function isInGeneration(Pool storage self, address resourceAddress, uint generationId) constant returns (bool) {
// TODO: tests
if (generationId == 0) {
return false;
}
Generation memory generation = self.generations[generationId];
for (uint i = 0; i < generation.members.length; i++) {
if (generation.members[i] == resourceAddress) {
return true;
}
}
return false;
}
/// @dev Returns a boolean for whether the given address is in the current generation.
/// @param self The pool to operate on.
/// @param resourceAddress The address to check membership of
function isInCurrentGeneration(Pool storage self, address resourceAddress) constant returns (bool) {
// TODO: tests
return isInGeneration(self, resourceAddress, getCurrentGenerationId(self));
}
/// @dev Returns a boolean for whether the given address is in the next queued generation.
/// @param self The pool to operate on.
/// @param resourceAddress The address to check membership of
function isInNextGeneration(Pool storage self, address resourceAddress) constant returns (bool) {
// TODO: tests
return isInGeneration(self, resourceAddress, getNextGenerationId(self));
}
/// @dev Returns a boolean for whether the given address is in either the current generation or the next queued generation.
/// @param self The pool to operate on.
/// @param resourceAddress The address to check membership of
function isInPool(Pool storage self, address resourceAddress) constant returns (bool) {
// TODO: tests
return (isInCurrentGeneration(self, resourceAddress) || isInNextGeneration(self, resourceAddress));
}
event _AddedToGeneration(address indexed resourceAddress, uint indexed generationId);
/// @dev Function to expose the _AddedToGeneration event to contracts.
/// @param resourceAddress The address that was added
/// @param generationId The id of the generation.
function AddedToGeneration(address resourceAddress, uint generationId) public {
_AddedToGeneration(resourceAddress, generationId);
}
event _RemovedFromGeneration(address indexed resourceAddress, uint indexed generationId);
/// @dev Function to expose the _AddedToGeneration event to contracts.
/// @param resourceAddress The address that was removed.
/// @param generationId The id of the generation.
function RemovedFromGeneration(address resourceAddress, uint generationId) public {
_RemovedFromGeneration(resourceAddress, generationId);
}
/// @dev Returns a boolean as to whether the provided address is allowed to enter the pool at this time.
/// @param self The pool to operate on.
/// @param resourceAddress The address in question
/// @param minimumBond The minimum bond amount that should be required for entry.
function canEnterPool(Pool storage self, address resourceAddress, uint minimumBond) constant returns (bool) {
/*
* - bond
* - pool is open
* - not already in it.
* - not already left it.
*/
// TODO: tests
if (self.bonds[resourceAddress] < minimumBond) {
// Insufficient bond balance;
return false;
}
if (isInPool(self, resourceAddress)) {
// Already in the pool either in the next upcoming generation
// or the currently active generation.
return false;
}
var nextGenerationId = getNextGenerationId(self);
if (nextGenerationId != 0) {
var nextGeneration = self.generations[nextGenerationId];
if (block.number + self.freezePeriod >= nextGeneration.startAt) {
// Next generation starts too soon.
return false;
}
}
return true;
}
/// @dev Adds the address to pool by adding them to the next generation (as well as creating it if it doesn't exist).
/// @param self The pool to operate on.
/// @param resourceAddress The address to be added to the pool
/// @param minimumBond The minimum bond amount that should be required for entry.
function enterPool(Pool storage self, address resourceAddress, uint minimumBond) public returns (uint) {
if (!canEnterPool(self, resourceAddress, minimumBond)) {
throw;
}
uint nextGenerationId = getNextGenerationId(self);
if (nextGenerationId == 0) {
// No next generation has formed yet so create it.
nextGenerationId = createNextGeneration(self);
}
Generation storage nextGeneration = self.generations[nextGenerationId];
// now add the new address.
nextGeneration.members.length += 1;
nextGeneration.members[nextGeneration.members.length - 1] = resourceAddress;
return nextGenerationId;
}
/// @dev Returns a boolean as to whether the provided address is allowed to exit the pool at this time.
/// @param self The pool to operate on.
/// @param resourceAddress The address in question
function canExitPool(Pool storage self, address resourceAddress) constant returns (bool) {
if (!isInCurrentGeneration(self, resourceAddress)) {
// Not in the pool.
return false;
}
uint nextGenerationId = getNextGenerationId(self);
if (nextGenerationId == 0) {
// Next generation hasn't been generated yet.
return true;
}
if (self.generations[nextGenerationId].startAt - self.freezePeriod <= block.number) {
// Next generation starts too soon.
return false;
}
// They can leave if they are still in the next generation.
// otherwise they have already left it.
return isInNextGeneration(self, resourceAddress);
}
/// @dev Removes the address from the pool by removing them from the next generation (as well as creating it if it doesn't exist)
/// @param self The pool to operate on.
/// @param resourceAddress The address in question
function exitPool(Pool storage self, address resourceAddress) public returns (uint) {
if (!canExitPool(self, resourceAddress)) {
throw;
}
uint nextGenerationId = getNextGenerationId(self);
if (nextGenerationId == 0) {
// No next generation has formed yet so create it.
nextGenerationId = createNextGeneration(self);
}
// Remove them from the generation
removeFromGeneration(self, nextGenerationId, resourceAddress);
return nextGenerationId;
}
/// @dev Removes the address from a generation's members array. Returns boolean as to whether removal was successful.
/// @param self The pool to operate on.
/// @param generationId The id of the generation to operate on.
/// @param resourceAddress The address to be removed.
function removeFromGeneration(Pool storage self, uint generationId, address resourceAddress) public returns (bool){
Generation storage generation = self.generations[generationId];
// now remove the address
for (uint i = 0; i < generation.members.length; i++) {
if (generation.members[i] == resourceAddress) {
generation.members[i] = generation.members[generation.members.length - 1];
generation.members.length -= 1;
return true;
}
}
return false;
}
/*
* Bonding
*/
/// @dev Subtracts the amount from an account's bond balance.
/// @param self The pool to operate on.
/// @param resourceAddress The address of the account
/// @param value The value to subtract.
function deductFromBond(Pool storage self, address resourceAddress, uint value) public {
/*
* deduct funds from a bond value without risk of an
* underflow.
*/
if (value > self.bonds[resourceAddress]) {
// Prevent Underflow.
throw;
}
self.bonds[resourceAddress] -= value;
}
/// @dev Adds the amount to an account's bond balance.
/// @param self The pool to operate on.
/// @param resourceAddress The address of the account
/// @param value The value to add.
function addToBond(Pool storage self, address resourceAddress, uint value) public {
/*
* Add funds to a bond value without risk of an
* overflow.
*/
if (self.bonds[resourceAddress] + value < self.bonds[resourceAddress]) {
// Prevent Overflow
throw;
}
self.bonds[resourceAddress] += value;
}
/// @dev Withdraws a bond amount from an address's bond account, sending them the corresponding amount in ether.
/// @param self The pool to operate on.
/// @param resourceAddress The address of the account
/// @param value The value to withdraw.
function withdrawBond(Pool storage self, address resourceAddress, uint value, uint minimumBond) public {
/*
* Only if you are not in either of the current call pools.
*/
// Prevent underflow
if (value > self.bonds[resourceAddress]) {
throw;
}
// Do a permissions check to be sure they can withdraw the
// funds.
if (isInPool(self, resourceAddress)) {
if (self.bonds[resourceAddress] - value < minimumBond) {
return;
}
}
deductFromBond(self, resourceAddress, value);
if (!resourceAddress.send(value)) {
// Potentially sending money to a contract that
// has a fallback function. So instead, try
// tranferring the funds with the call api.
if (!resourceAddress.call.gas(msg.gas).value(value)()) {
// Revert the entire transaction. No
// need to destroy the funds.
throw;
}
}
}
}
contract Relay {
address operator;
function Relay() {
operator = msg.sender;
}
function relayCall(address contractAddress, bytes4 abiSignature, bytes data) public returns (bool) {
if (msg.sender != operator) {
throw;
}
return contractAddress.call(abiSignature, data);
}
}
library ScheduledCallLib {
/*
* Address: 0x5c3623dcef2d5168dbe3e8cc538788cd8912d898
*/
struct CallDatabase {
Relay unauthorizedRelay;
Relay authorizedRelay;
bytes32 lastCallKey;
bytes lastData;
uint lastDataLength;
bytes32 lastDataHash;
ResourcePoolLib.Pool callerPool;
GroveLib.Index callIndex;
AccountingLib.Bank gasBank;
mapping (bytes32 => Call) calls;
mapping (bytes32 => bytes) data_registry;
mapping (bytes32 => bool) accountAuthorizations;
}
struct Call {
address contractAddress;
address scheduledBy;
uint calledAtBlock;
uint targetBlock;
uint8 gracePeriod;
uint nonce;
uint baseGasPrice;
uint gasPrice;
uint gasUsed;
uint gasCost;
uint payout;
uint fee;
address executedBy;
bytes4 abiSignature;
bool isCancelled;
bool wasCalled;
bool wasSuccessful;
bytes32 dataHash;
}
// The author (Piper Merriam) address.
address constant owner = 0xd3cda913deb6f67967b99d67acdfa1712c293601;
/*
* Getter methods for `Call` information
*/
function getCallContractAddress(CallDatabase storage self, bytes32 callKey) constant returns (address) {
return self.calls[callKey].contractAddress;
}
function getCallScheduledBy(CallDatabase storage self, bytes32 callKey) constant returns (address) {
return self.calls[callKey].scheduledBy;
}
function getCallCalledAtBlock(CallDatabase storage self, bytes32 callKey) constant returns (uint) {
return self.calls[callKey].calledAtBlock;
}
function getCallGracePeriod(CallDatabase storage self, bytes32 callKey) constant returns (uint) {
return self.calls[callKey].gracePeriod;
}
function getCallTargetBlock(CallDatabase storage self, bytes32 callKey) constant returns (uint) {
return self.calls[callKey].targetBlock;
}
function getCallBaseGasPrice(CallDatabase storage self, bytes32 callKey) constant returns (uint) {
return self.calls[callKey].baseGasPrice;
}
function getCallGasPrice(CallDatabase storage self, bytes32 callKey) constant returns (uint) {
return self.calls[callKey].gasPrice;
}
function getCallGasUsed(CallDatabase storage self, bytes32 callKey) constant returns (uint) {
return self.calls[callKey].gasUsed;
}
function getCallABISignature(CallDatabase storage self, bytes32 callKey) constant returns (bytes4) {
return self.calls[callKey].abiSignature;
}
function checkIfCalled(CallDatabase storage self, bytes32 callKey) constant returns (bool) {
return self.calls[callKey].wasCalled;
}
function checkIfSuccess(CallDatabase storage self, bytes32 callKey) constant returns (bool) {
return self.calls[callKey].wasSuccessful;
}
function checkIfCancelled(CallDatabase storage self, bytes32 callKey) constant returns (bool) {
return self.calls[callKey].isCancelled;
}
function getCallDataHash(CallDatabase storage self, bytes32 callKey) constant returns (bytes32) {
return self.calls[callKey].dataHash;
}
function getCallPayout(CallDatabase storage self, bytes32 callKey) constant returns (uint) {
return self.calls[callKey].payout;
}
function getCallFee(CallDatabase storage self, bytes32 callKey) constant returns (uint) {
return self.calls[callKey].fee;
}
/*
* Scheduling Authorization API
*/
function addAuthorization(CallDatabase storage self, address schedulerAddress, address contractAddress) public {
self.accountAuthorizations[sha3(schedulerAddress, contractAddress)] = true;
}
function removeAuthorization(CallDatabase storage self, address schedulerAddress, address contractAddress) public {
self.accountAuthorizations[sha3(schedulerAddress, contractAddress)] = false;
}
function checkAuthorization(CallDatabase storage self, address schedulerAddress, address contractAddress) constant returns (bool) {
return self.accountAuthorizations[sha3(schedulerAddress, contractAddress)];
}
/*
* Data Registry API
*/
function getCallData(CallDatabase storage self, bytes32 callKey) constant returns (bytes) {
return self.data_registry[self.calls[callKey].dataHash];
}
/*
* API used by Alarm service
*/
// The number of blocks that each caller in the pool has to complete their
// call.
uint constant CALL_WINDOW_SIZE = 16;
function getGenerationIdForCall(CallDatabase storage self, bytes32 callKey) constant returns (uint) {
Call call = self.calls[callKey];
return ResourcePoolLib.getGenerationForWindow(self.callerPool, call.targetBlock, call.targetBlock + call.gracePeriod);
}
function getDesignatedCaller(CallDatabase storage self, bytes32 callKey, uint blockNumber) constant returns (address) {
/*
* Returns the caller from the current call pool who is
* designated as the executor of this call.
*/
Call call = self.calls[callKey];
if (blockNumber < call.targetBlock || blockNumber > call.targetBlock + call.gracePeriod) {
// blockNumber not within call window.
return 0x0;
}
// Check if we are in free-for-all window.
uint numWindows = call.gracePeriod / CALL_WINDOW_SIZE;
uint blockWindow = (blockNumber - call.targetBlock) / CALL_WINDOW_SIZE;
if (blockWindow + 2 > numWindows) {
// We are within the free-for-all period.
return 0x0;
}
// Lookup the pool that full contains the call window for this
// call.
uint generationId = ResourcePoolLib.getGenerationForWindow(self.callerPool, call.targetBlock, call.targetBlock + call.gracePeriod);
if (generationId == 0) {
// No pool currently in operation.
return 0x0;
}
var generation = self.callerPool.generations[generationId];
uint offset = uint(callKey) % generation.members.length;
return generation.members[(offset + blockWindow) % generation.members.length];
}
event _AwardedMissedBlockBonus(address indexed fromCaller, address indexed toCaller, uint indexed generationId, bytes32 callKey, uint blockNumber, uint bonusAmount);
function AwardedMissedBlockBonus(address fromCaller, address toCaller, uint generationId, bytes32 callKey, uint blockNumber, uint bonusAmount) public {
_AwardedMissedBlockBonus(fromCaller, toCaller, generationId, callKey, blockNumber, bonusAmount);
}
function getMinimumBond() constant returns (uint) {
return tx.gasprice * block.gaslimit;
}
function doBondBonusTransfer(CallDatabase storage self, address fromCaller, address toCaller) internal returns (uint) {
uint bonusAmount = getMinimumBond();
uint bondBalance = self.callerPool.bonds[fromCaller];
// If the bond balance is lower than the award
// balance, then adjust the reward amount to
// match the bond balance.
if (bonusAmount > bondBalance) {
bonusAmount = bondBalance;
}
// Transfer the funds fromCaller => toCaller
ResourcePoolLib.deductFromBond(self.callerPool, fromCaller, bonusAmount);
ResourcePoolLib.addToBond(self.callerPool, toCaller, bonusAmount);
return bonusAmount;
}
function awardMissedBlockBonus(CallDatabase storage self, address toCaller, bytes32 callKey) public {
var call = self.calls[callKey];
var generation = self.callerPool.generations[ResourcePoolLib.getGenerationForWindow(self.callerPool, call.targetBlock, call.targetBlock + call.gracePeriod)];
uint i;
uint bonusAmount;
address fromCaller;
uint numWindows = call.gracePeriod / CALL_WINDOW_SIZE;
uint blockWindow = (block.number - call.targetBlock) / CALL_WINDOW_SIZE;
// Check if we are within the free-for-all period. If so, we
// award from all pool members.
if (blockWindow + 2 > numWindows) {
address firstCaller = getDesignatedCaller(self, callKey, call.targetBlock);
for (i = call.targetBlock; i <= call.targetBlock + call.gracePeriod; i += CALL_WINDOW_SIZE) {
fromCaller = getDesignatedCaller(self, callKey, i);
if (fromCaller == firstCaller && i != call.targetBlock) {
// We have already gone through all of
// the pool callers so we should break
// out of the loop.
break;
}
if (fromCaller == toCaller) {
continue;
}
bonusAmount = doBondBonusTransfer(self, fromCaller, toCaller);
// Log the bonus was awarded.
AwardedMissedBlockBonus(fromCaller, toCaller, generation.id, callKey, block.number, bonusAmount);
}
return;
}
// Special case for single member and empty pools
if (generation.members.length < 2) {
return;
}
// Otherwise the award comes from the previous caller.
for (i = 0; i < generation.members.length; i++) {
// Find where the member is in the pool and
// award from the previous pool members bond.
if (generation.members[i] == toCaller) {
fromCaller = generation.members[(i + generation.members.length - 1) % generation.members.length];
bonusAmount = doBondBonusTransfer(self, fromCaller, toCaller);
// Log the bonus was awarded.
AwardedMissedBlockBonus(fromCaller, toCaller, generation.id, callKey, block.number, bonusAmount);
// Remove the caller from the next pool.
if (ResourcePoolLib.getNextGenerationId(self.callerPool) == 0) {
// This is the first address to modify the
// current pool so we need to setup the next
// pool.
ResourcePoolLib.createNextGeneration(self.callerPool);
}
ResourcePoolLib.removeFromGeneration(self.callerPool, ResourcePoolLib.getNextGenerationId(self.callerPool), fromCaller);
return;
}
}
}
/*
* Data registration API
*/
event _DataRegistered(bytes32 indexed dataHash);
function DataRegistered(bytes32 dataHash) constant {
_DataRegistered(dataHash);
}
function registerData(CallDatabase storage self, bytes data) public {
self.lastData.length = data.length - 4;
if (data.length > 4) {
for (uint i = 0; i < self.lastData.length; i++) {
self.lastData[i] = data[i + 4];
}
}
self.data_registry[sha3(self.lastData)] = self.lastData;
self.lastDataHash = sha3(self.lastData);
self.lastDataLength = self.lastData.length;
}
/*
* Call execution API
*/
// This number represents the constant gas cost of the addition
// operations that occur in `doCall` that cannot be tracked with
// msg.gas.
uint constant EXTRA_CALL_GAS = 153321;
// This number represents the overall overhead involved in executing a
// scheduled call.
uint constant CALL_OVERHEAD = 120104;
event _CallExecuted(address indexed executedBy, bytes32 indexed callKey);
function CallExecuted(address executedBy, bytes32 callKey) public {
_CallExecuted(executedBy, callKey);
}
event _CallAborted(address indexed executedBy, bytes32 indexed callKey, bytes18 reason);
function CallAborted(address executedBy, bytes32 callKey, bytes18 reason) public {
_CallAborted(executedBy, callKey, reason);
}
function doCall(CallDatabase storage self, bytes32 callKey, address msgSender) public {
uint gasBefore = msg.gas;
Call storage call = self.calls[callKey];
if (call.wasCalled) {
// The call has already been executed so don't do it again.
_CallAborted(msg.sender, callKey, "ALREADY CALLED");
return;
}
if (call.isCancelled) {
// The call was cancelled so don't execute it.
_CallAborted(msg.sender, callKey, "CANCELLED");
return;
}
if (call.contractAddress == 0x0) {
// This call key doesnt map to a registered call.
_CallAborted(msg.sender, callKey, "UNKNOWN");
return;
}
if (block.number < call.targetBlock) {
// Target block hasnt happened yet.
_CallAborted(msg.sender, callKey, "TOO EARLY");
return;
}
if (block.number > call.targetBlock + call.gracePeriod) {
// The blockchain has advanced passed the period where
// it was allowed to be called.
_CallAborted(msg.sender, callKey, "TOO LATE");
return;
}
uint heldBalance = getCallMaxCost(self, callKey);
if (self.gasBank.accountBalances[call.scheduledBy] < heldBalance) {
// The scheduledBy's account balance is less than the
// current gasLimit and thus potentiall can't pay for
// the call.
// Mark it as called since it was.
call.wasCalled = true;
// Log it.
_CallAborted(msg.sender, callKey, "INSUFFICIENT_FUNDS");
return;
}
// Check if this caller is allowed to execute the call.
if (self.callerPool.generations[ResourcePoolLib.getCurrentGenerationId(self.callerPool)].members.length > 0) {
address designatedCaller = getDesignatedCaller(self, callKey, block.number);
if (designatedCaller != 0x0 && designatedCaller != msgSender) {
// This call was reserved for someone from the
// bonded pool of callers and can only be
// called by them during this block window.
_CallAborted(msg.sender, callKey, "WRONG_CALLER");
return;
}
uint blockWindow = (block.number - call.targetBlock) / CALL_WINDOW_SIZE;
if (blockWindow > 0) {
// Someone missed their call so this caller
// gets to claim their bond for picking up
// their slack.
awardMissedBlockBonus(self, msgSender, callKey);
}
}
// Log metadata about the call.
call.gasPrice = tx.gasprice;
call.executedBy = msgSender;
call.calledAtBlock = block.number;
// Fetch the call data
var data = self.data_registry[call.dataHash];
// During the call, we need to put enough funds to pay for the
// call on hold to ensure they are available to pay the caller.
AccountingLib.withdraw(self.gasBank, call.scheduledBy, heldBalance);
// Mark whether the function call was successful.
if (checkAuthorization(self, call.scheduledBy, call.contractAddress)) {
call.wasSuccessful = self.authorizedRelay.relayCall.gas(msg.gas - CALL_OVERHEAD)(call.contractAddress, call.abiSignature, data);
}
else {
call.wasSuccessful = self.unauthorizedRelay.relayCall.gas(msg.gas - CALL_OVERHEAD)(call.contractAddress, call.abiSignature, data);
}
// Add the held funds back into the scheduler's account.
AccountingLib.deposit(self.gasBank, call.scheduledBy, heldBalance);
// Mark the call as having been executed.
call.wasCalled = true;
// Compute the scalar (0 - 200) for the fee.
uint feeScalar = getCallFeeScalar(call.baseGasPrice, call.gasPrice);
// Log how much gas this call used. EXTRA_CALL_GAS is a fixed
// amount that represents the gas usage of the commands that
// happen after this line.
call.gasUsed = (gasBefore - msg.gas + EXTRA_CALL_GAS);
call.gasCost = call.gasUsed * call.gasPrice;
// Now we need to pay the caller as well as keep fee.
// callerPayout -> call cost + 1%
// fee -> 1% of callerPayout
call.payout = call.gasCost * feeScalar * 101 / 10000;
call.fee = call.gasCost * feeScalar / 10000;
AccountingLib.deductFunds(self.gasBank, call.scheduledBy, call.payout + call.fee);
AccountingLib.addFunds(self.gasBank, msgSender, call.payout);
AccountingLib.addFunds(self.gasBank, owner, call.fee);
}
function getCallMaxCost(CallDatabase storage self, bytes32 callKey) constant returns (uint) {
/*
* tx.gasprice * block.gaslimit
*
*/
// call cost + 2%
var call = self.calls[callKey];
uint gasCost = tx.gasprice * block.gaslimit;
uint feeScalar = getCallFeeScalar(call.baseGasPrice, tx.gasprice);
return gasCost * feeScalar * 102 / 10000;
}
function getCallFeeScalar(uint baseGasPrice, uint gasPrice) constant returns (uint) {
/*
* Return a number between 0 - 200 to scale the fee based on
* the gas price set for the calling transaction as compared
* to the gas price of the scheduling transaction.
*
* - number approaches zero as the transaction gas price goes
* above the gas price recorded when the call was scheduled.
*
* - the number approaches 200 as the transaction gas price
* drops under the price recorded when the call was scheduled.
*
* This encourages lower gas costs as the lower the gas price
* for the executing transaction, the higher the payout to the
* caller.
*/
if (gasPrice > baseGasPrice) {
return 100 * baseGasPrice / gasPrice;
}
else {
return 200 - 100 * baseGasPrice / (2 * baseGasPrice - gasPrice);
}
}
/*
* Call Scheduling API
*/
// The result of `sha()` so that we can validate that people aren't
// looking up call data that failed to register.
bytes32 constant emptyDataHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
function computeCallKey(address scheduledBy, address contractAddress, bytes4 abiSignature, bytes32 dataHash, uint targetBlock, uint8 gracePeriod, uint nonce) constant returns (bytes32) {
return sha3(scheduledBy, contractAddress, abiSignature, dataHash, targetBlock, gracePeriod, nonce);
}
// Ten minutes into the future.
uint constant MAX_BLOCKS_IN_FUTURE = 40;
event _CallScheduled(bytes32 indexed callKey);
function CallScheduled(bytes32 callKey) public {
_CallScheduled(callKey);
}
event _CallRejected(bytes32 indexed callKey, bytes15 reason);
function CallRejected(bytes32 callKey, bytes15 reason) public {
_CallRejected(callKey, reason);
}
function getCallWindowSize() public returns (uint) {
return CALL_WINDOW_SIZE;
}
function getMinimumGracePeriod() public returns (uint) {
return 4 * CALL_WINDOW_SIZE;
}
function scheduleCall(CallDatabase storage self, address schedulerAddress, address contractAddress, bytes4 abiSignature, bytes32 dataHash, uint targetBlock, uint8 gracePeriod, uint nonce) public returns (bytes15) {
/*
* Primary API for scheduling a call. Prior to calling this
* the data should already have been registered through the
* `registerData` API.
*/
bytes32 callKey = computeCallKey(schedulerAddress, contractAddress, abiSignature, dataHash, targetBlock, gracePeriod, nonce);
if (dataHash != emptyDataHash && self.data_registry[dataHash].length == 0) {
// Don't allow registering calls if the data hash has
// not actually been registered. The only exception is
// the *emptyDataHash*.
return "NO_DATA";
}
if (targetBlock < block.number + MAX_BLOCKS_IN_FUTURE) {
// Don't allow scheduling further than
// MAX_BLOCKS_IN_FUTURE
return "TOO_SOON";
}
Call storage call = self.calls[callKey];
if (call.contractAddress != 0x0) {
return "DUPLICATE";
}
if (gracePeriod < getMinimumGracePeriod()) {
return "GRACE_TOO_SHORT";
}
self.lastCallKey = callKey;
call.contractAddress = contractAddress;
call.scheduledBy = schedulerAddress;
call.nonce = nonce;
call.abiSignature = abiSignature;
call.dataHash = dataHash;
call.targetBlock = targetBlock;
call.gracePeriod = gracePeriod;
call.baseGasPrice = tx.gasprice;
// Put the call into the grove index.
GroveLib.insert(self.callIndex, callKey, int(call.targetBlock));
return 0x0;
}
event _CallCancelled(bytes32 indexed callKey);
function CallCancelled(bytes32 callKey) public {
_CallCancelled(callKey);
}
// Two minutes
uint constant MIN_CANCEL_WINDOW = 8;
function cancelCall(CallDatabase storage self, bytes32 callKey, address msgSender) public returns (bool) {
Call storage call = self.calls[callKey];
if (call.scheduledBy != msgSender) {
// Nobody but the scheduler can cancel a call.
return false;
}
if (call.wasCalled) {
// No need to cancel a call that already was executed.
return false;
}
if (call.targetBlock - MIN_CANCEL_WINDOW <= block.number) {
// Call cannot be cancelled this close to execution.
return false;
}
call.isCancelled = true;
return true;
}
}
/*
* Ethereum Alarm Service
* Version 0.4.0
*
* address: 0x07307d0b136a79bac718f43388aed706389c4588
*/
contract Alarm {
/*
* Constructor
*
* - sets up relays
* - configures the caller pool.
*/
function Alarm() {
callDatabase.unauthorizedRelay = new Relay();
callDatabase.authorizedRelay = new Relay();
callDatabase.callerPool.freezePeriod = 80;
callDatabase.callerPool.rotationDelay = 80;
callDatabase.callerPool.overlapSize = 256;
}
ScheduledCallLib.CallDatabase callDatabase;
// The author (Piper Merriam) address.
address constant owner = 0xd3cda913deb6f67967b99d67acdfa1712c293601;
/*
* Account Management API
*/
function getAccountBalance(address accountAddress) constant public returns (uint) {
return callDatabase.gasBank.accountBalances[accountAddress];
}
function deposit() public {
deposit(msg.sender);
}
function deposit(address accountAddress) public {
/*
* Public API for depositing funds in a specified account.
*/
AccountingLib.deposit(callDatabase.gasBank, accountAddress, msg.value);
AccountingLib.Deposit(msg.sender, accountAddress, msg.value);
}
function withdraw(uint value) public {
/*
* Public API for withdrawing funds.
*/
if (AccountingLib.withdraw(callDatabase.gasBank, msg.sender, value)) {
AccountingLib.Withdrawal(msg.sender, value);
}
else {
AccountingLib.InsufficientFunds(msg.sender, value, callDatabase.gasBank.accountBalances[msg.sender]);
}
}
function() {
/*
* Fallback function that allows depositing funds just by
* sending a transaction.
*/
deposit(msg.sender);
}
/*
* Scheduling Authorization API
*/
function unauthorizedAddress() constant returns (address) {
return address(callDatabase.unauthorizedRelay);
}
function authorizedAddress() constant returns (address) {
return address(callDatabase.authorizedRelay);
}
function addAuthorization(address schedulerAddress) public {
ScheduledCallLib.addAuthorization(callDatabase, schedulerAddress, msg.sender);
}
function removeAuthorization(address schedulerAddress) public {
callDatabase.accountAuthorizations[sha3(schedulerAddress, msg.sender)] = false;
}
function checkAuthorization(address schedulerAddress, address contractAddress) constant returns (bool) {
return callDatabase.accountAuthorizations[sha3(schedulerAddress, contractAddress)];
}
/*
* Caller bonding
*/
function getMinimumBond() constant returns (uint) {
return ScheduledCallLib.getMinimumBond();
}
function depositBond() public {
ResourcePoolLib.addToBond(callDatabase.callerPool, msg.sender, msg.value);
}
function withdrawBond(uint value) public {
ResourcePoolLib.withdrawBond(callDatabase.callerPool, msg.sender, value, getMinimumBond());
}
function getBondBalance() constant returns (uint) {
return getBondBalance(msg.sender);
}
function getBondBalance(address callerAddress) constant returns (uint) {
return callDatabase.callerPool.bonds[callerAddress];
}
/*
* Pool Management
*/
function getGenerationForCall(bytes32 callKey) constant returns (uint) {
var call = callDatabase.calls[callKey];
return ResourcePoolLib.getGenerationForWindow(callDatabase.callerPool, call.targetBlock, call.targetBlock + call.gracePeriod);
}
function getGenerationSize(uint generationId) constant returns (uint) {
return callDatabase.callerPool.generations[generationId].members.length;
}
function getGenerationStartAt(uint generationId) constant returns (uint) {
return callDatabase.callerPool.generations[generationId].startAt;
}
function getGenerationEndAt(uint generationId) constant returns (uint) {
return callDatabase.callerPool.generations[generationId].endAt;
}
function getCurrentGenerationId() constant returns (uint) {
return ResourcePoolLib.getCurrentGenerationId(callDatabase.callerPool);
}
function getNextGenerationId() constant returns (uint) {
return ResourcePoolLib.getNextGenerationId(callDatabase.callerPool);
}
function isInPool() constant returns (bool) {
return ResourcePoolLib.isInPool(callDatabase.callerPool, msg.sender);
}
function isInPool(address callerAddress) constant returns (bool) {
return ResourcePoolLib.isInPool(callDatabase.callerPool, callerAddress);
}
function isInGeneration(uint generationId) constant returns (bool) {
return isInGeneration(msg.sender, generationId);
}
function isInGeneration(address callerAddress, uint generationId) constant returns (bool) {
return ResourcePoolLib.isInGeneration(callDatabase.callerPool, callerAddress, generationId);
}
/*
* Pool Meta information
*/
function getPoolFreezePeriod() constant returns (uint) {
return callDatabase.callerPool.freezePeriod;
}
function getPoolOverlapSize() constant returns (uint) {
return callDatabase.callerPool.overlapSize;
}
function getPoolRotationDelay() constant returns (uint) {
return callDatabase.callerPool.rotationDelay;
}
/*
* Pool Membership
*/
function canEnterPool() constant returns (bool) {
return ResourcePoolLib.canEnterPool(callDatabase.callerPool, msg.sender, getMinimumBond());
}
function canEnterPool(address callerAddress) constant returns (bool) {
return ResourcePoolLib.canEnterPool(callDatabase.callerPool, callerAddress, getMinimumBond());
}
function canExitPool() constant returns (bool) {
return ResourcePoolLib.canExitPool(callDatabase.callerPool, msg.sender);
}
function canExitPool(address callerAddress) constant returns (bool) {
return ResourcePoolLib.canExitPool(callDatabase.callerPool, callerAddress);
}
function enterPool() public {
uint generationId = ResourcePoolLib.enterPool(callDatabase.callerPool, msg.sender, getMinimumBond());
ResourcePoolLib.AddedToGeneration(msg.sender, generationId);
}
function exitPool() public {
uint generationId = ResourcePoolLib.exitPool(callDatabase.callerPool, msg.sender);
ResourcePoolLib.RemovedFromGeneration(msg.sender, generationId);
}
/*
* Call Information API
*/
function getLastCallKey() constant returns (bytes32) {
return callDatabase.lastCallKey;
}
/*
* Getter methods for `Call` information
*/
function getCallContractAddress(bytes32 callKey) constant returns (address) {
return ScheduledCallLib.getCallContractAddress(callDatabase, callKey);
}
function getCallScheduledBy(bytes32 callKey) constant returns (address) {
return ScheduledCallLib.getCallScheduledBy(callDatabase, callKey);
}
function getCallCalledAtBlock(bytes32 callKey) constant returns (uint) {
return ScheduledCallLib.getCallCalledAtBlock(callDatabase, callKey);
}
function getCallGracePeriod(bytes32 callKey) constant returns (uint) {
return ScheduledCallLib.getCallGracePeriod(callDatabase, callKey);
}
function getCallTargetBlock(bytes32 callKey) constant returns (uint) {
return ScheduledCallLib.getCallTargetBlock(callDatabase, callKey);
}
function getCallBaseGasPrice(bytes32 callKey) constant returns (uint) {
return ScheduledCallLib.getCallBaseGasPrice(callDatabase, callKey);
}
function getCallGasPrice(bytes32 callKey) constant returns (uint) {
return ScheduledCallLib.getCallGasPrice(callDatabase, callKey);
}
function getCallGasUsed(bytes32 callKey) constant returns (uint) {
return ScheduledCallLib.getCallGasUsed(callDatabase, callKey);
}
function getCallABISignature(bytes32 callKey) constant returns (bytes4) {
return ScheduledCallLib.getCallABISignature(callDatabase, callKey);
}
function checkIfCalled(bytes32 callKey) constant returns (bool) {
return ScheduledCallLib.checkIfCalled(callDatabase, callKey);
}
function checkIfSuccess(bytes32 callKey) constant returns (bool) {
return ScheduledCallLib.checkIfSuccess(callDatabase, callKey);
}
function checkIfCancelled(bytes32 callKey) constant returns (bool) {
return ScheduledCallLib.checkIfCancelled(callDatabase, callKey);
}
function getCallDataHash(bytes32 callKey) constant returns (bytes32) {
return ScheduledCallLib.getCallDataHash(callDatabase, callKey);
}
function getCallPayout(bytes32 callKey) constant returns (uint) {
return ScheduledCallLib.getCallPayout(callDatabase, callKey);
}
function getCallFee(bytes32 callKey) constant returns (uint) {
return ScheduledCallLib.getCallFee(callDatabase, callKey);
}
function getCallMaxCost(bytes32 callKey) constant returns (uint) {
return ScheduledCallLib.getCallMaxCost(callDatabase, callKey);
}
function getCallData(bytes32 callKey) constant returns (bytes) {
return callDatabase.data_registry[callDatabase.calls[callKey].dataHash];
}
/*
* Data registration API
*/
function registerData() public {
ScheduledCallLib.registerData(callDatabase, msg.data);
ScheduledCallLib.DataRegistered(callDatabase.lastDataHash);
}
function getLastDataHash() constant returns (bytes32) {
return callDatabase.lastDataHash;
}
function getLastDataLength() constant returns (uint) {
return callDatabase.lastDataLength;
}
function getLastData() constant returns (bytes) {
return callDatabase.lastData;
}
/*
* Call execution API
*/
function doCall(bytes32 callKey) public {
ScheduledCallLib.doCall(callDatabase, callKey, msg.sender);
}
/*
* Call Scheduling API
*/
function getMinimumGracePeriod() constant returns (uint) {
return ScheduledCallLib.getMinimumGracePeriod();
}
function scheduleCall(address contractAddress, bytes4 abiSignature, bytes32 dataHash, uint targetBlock) public {
/*
* Schedule call with gracePeriod defaulted to 255 and nonce
* defaulted to 0.
*/
scheduleCall(contractAddress, abiSignature, dataHash, targetBlock, 255, 0);
}
function scheduleCall(address contractAddress, bytes4 abiSignature, bytes32 dataHash, uint targetBlock, uint8 gracePeriod) public {
/*
* Schedule call with nonce defaulted to 0.
*/
scheduleCall(contractAddress, abiSignature, dataHash, targetBlock, gracePeriod, 0);
}
function scheduleCall(address contractAddress, bytes4 abiSignature, bytes32 dataHash, uint targetBlock, uint8 gracePeriod, uint nonce) public {
/*
* Primary API for scheduling a call. Prior to calling this
* the data should already have been registered through the
* `registerData` API.
*/
bytes15 reason = ScheduledCallLib.scheduleCall(callDatabase, msg.sender, contractAddress, abiSignature, dataHash, targetBlock, gracePeriod, nonce);
bytes32 callKey = ScheduledCallLib.computeCallKey(msg.sender, contractAddress, abiSignature, dataHash, targetBlock, gracePeriod, nonce);
if (reason != 0x0) {
ScheduledCallLib.CallRejected(callKey, reason);
}
else {
ScheduledCallLib.CallScheduled(callKey);
}
}
function cancelCall(bytes32 callKey) public {
if (ScheduledCallLib.cancelCall(callDatabase, callKey, address(msg.sender))) {
ScheduledCallLib.CallCancelled(callKey);
}
}
/*
* Next Call API
*/
function getCallWindowSize() constant returns (uint) {
return ScheduledCallLib.getCallWindowSize();
}
function getGenerationIdForCall(bytes32 callKey) constant returns (uint) {
return ScheduledCallLib.getGenerationIdForCall(callDatabase, callKey);
}
function getDesignatedCaller(bytes32 callKey, uint blockNumber) constant returns (address) {
return ScheduledCallLib.getDesignatedCaller(callDatabase, callKey, blockNumber);
}
function getNextCall(uint blockNumber) constant returns (bytes32) {
return GroveLib.query(callDatabase.callIndex, ">=", int(blockNumber));
}
function getNextCallSibling(bytes32 callKey) constant returns (bytes32) {
return GroveLib.getNextNode(callDatabase.callIndex, callKey);
}
}
|
Check if we are within the free-for-all period. If so, we award from all pool members. We have already gone through all of the pool callers so we should break out of the loop. Special case for single member and empty pools Otherwise the award comes from the previous caller. Find where the member is in the pool and award from the previous pool members bond. Log the bonus was awarded. Remove the caller from the next pool. This is the first address to modify the current pool so we need to setup the next pool.
|
function awardMissedBlockBonus(CallDatabase storage self, address toCaller, bytes32 callKey) public {
var call = self.calls[callKey];
var generation = self.callerPool.generations[ResourcePoolLib.getGenerationForWindow(self.callerPool, call.targetBlock, call.targetBlock + call.gracePeriod)];
uint i;
uint bonusAmount;
address fromCaller;
uint numWindows = call.gracePeriod / CALL_WINDOW_SIZE;
uint blockWindow = (block.number - call.targetBlock) / CALL_WINDOW_SIZE;
if (blockWindow + 2 > numWindows) {
address firstCaller = getDesignatedCaller(self, callKey, call.targetBlock);
for (i = call.targetBlock; i <= call.targetBlock + call.gracePeriod; i += CALL_WINDOW_SIZE) {
fromCaller = getDesignatedCaller(self, callKey, i);
if (fromCaller == firstCaller && i != call.targetBlock) {
break;
}
if (fromCaller == toCaller) {
continue;
}
bonusAmount = doBondBonusTransfer(self, fromCaller, toCaller);
}
return;
}
if (generation.members.length < 2) {
return;
}
for (i = 0; i < generation.members.length; i++) {
if (generation.members[i] == toCaller) {
fromCaller = generation.members[(i + generation.members.length - 1) % generation.members.length];
bonusAmount = doBondBonusTransfer(self, fromCaller, toCaller);
AwardedMissedBlockBonus(fromCaller, toCaller, generation.id, callKey, block.number, bonusAmount);
if (ResourcePoolLib.getNextGenerationId(self.callerPool) == 0) {
ResourcePoolLib.createNextGeneration(self.callerPool);
}
ResourcePoolLib.removeFromGeneration(self.callerPool, ResourcePoolLib.getNextGenerationId(self.callerPool), fromCaller);
return;
}
}
}
| 2,569,994 |
pragma solidity 0.5.16;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../escrow/EscrowBaseInterface.sol";
import "../../lib/priceoracle/PriceOracleInterface.sol";
import "../../lib/protobuf/BorrowingData.sol";
import "../../lib/protobuf/TokenTransfer.sol";
import "../../lib/protobuf/SupplementalLineItem.sol";
import "../../lib/util/Constants.sol";
import "../InstrumentBase.sol";
contract Borrowing is InstrumentBase {
using SafeMath for uint256;
event BorrowingCreated(
uint256 indexed issuanceId,
address indexed makerAddress,
address escrowAddress,
address collateralTokenAddress,
address borrowingTokenAddress,
uint256 borrowingAmount,
uint256 collateralRatio,
uint256 collateralTokenAmount,
uint256 engagementDueTimestamp
);
event BorrowingEngaged(
uint256 indexed issuanceId,
address indexed takerAddress,
uint256 borrowingDueTimstamp
);
event BorrowingRepaid(uint256 indexed issuanceId);
event BorrowingCompleteNotEngaged(uint256 indexed issuanceId);
event BorrowingDelinquent(uint256 indexed issuanceId);
event BorrowingCancelled(uint256 indexed issuanceId);
// Constants
uint256 constant ENGAGEMENT_DUE_DAYS = 14 days; // Time available for taker to engage
uint256 internal constant TENOR_DAYS_MIN = 2; // Minimum tenor is 2 days
uint256 internal constant TENOR_DAYS_MAX = 90; // Maximum tenor is 90 days
uint256 internal constant COLLATERAL_RATIO_DECIMALS = 10**4; // 0.01%
uint256 internal constant COLLATERAL_RATIO_MIN = 5000; // Minimum collateral is 50%
uint256 internal constant COLLATERAL_RATIO_MAX = 20000; // Maximum collateral is 200%
uint256 internal constant INTEREST_RATE_DECIMALS = 10**6; // 0.0001%
uint256 internal constant INTEREST_RATE_MIN = 10; // Mimimum interest rate is 0.0010%
uint256 internal constant INTEREST_RATE_MAX = 50000; // Maximum interest rate is 5.0000%
// Custom data
bytes32 internal constant BORROWING_DATA = "borrowing_data";
// Borrowing parameters
address private _collateralTokenAddress;
address private _borrowingTokenAddress;
uint256 private _borrowingAmount;
uint256 private _tenorDays;
uint256 private _interestRate;
uint256 private _interestAmount;
uint256 private _collateralRatio;
uint256 private _collateralAmount;
/**
* @dev Create a new issuance of the financial instrument
* @param callerAddress Address which invokes this function.
* @param makerParametersData The custom parameters to the newly created issuance
* @return transfersData The transfers to perform after the invocation
*/
function createIssuance(
address callerAddress,
bytes memory makerParametersData
) public returns (bytes memory transfersData) {
require(
_state == IssuanceProperties.State.Initiated,
"Issuance not in Initiated"
);
BorrowingMakerParameters.Data memory makerParameters = BorrowingMakerParameters
.decode(makerParametersData);
// Validates parameters.
require(
makerParameters.collateralTokenAddress != address(0x0),
"Collateral token not set"
);
require(
makerParameters.borrowingTokenAddress != address(0x0),
"Borrowing token not set"
);
require(
makerParameters.borrowingAmount > 0,
"Borrowing amount not set"
);
require(
makerParameters.tenorDays >= TENOR_DAYS_MIN &&
makerParameters.tenorDays <= TENOR_DAYS_MAX,
"Invalid tenor days"
);
require(
makerParameters.collateralRatio >= COLLATERAL_RATIO_MIN &&
makerParameters.collateralRatio <= COLLATERAL_RATIO_MAX,
"Invalid collateral ratio"
);
require(
makerParameters.interestRate >= INTEREST_RATE_MIN &&
makerParameters.interestRate <= INTEREST_RATE_MAX,
"Invalid interest rate"
);
// Calculate the collateral amount. Collateral is calculated at the time of issuance creation.
PriceOracleInterface priceOracle = PriceOracleInterface(
_priceOracleAddress
);
(uint256 numerator, uint256 denominator) = priceOracle.getRate(
makerParameters.borrowingTokenAddress,
makerParameters.collateralTokenAddress
);
require(numerator > 0 && denominator > 0, "Exchange rate not found");
uint256 collateralAmount = numerator
.mul(makerParameters.borrowingAmount)
.mul(makerParameters.collateralRatio)
.div(COLLATERAL_RATIO_DECIMALS)
.div(denominator);
// Validate collateral token balance
uint256 collateralTokenBalance = EscrowBaseInterface(
_instrumentEscrowAddress
)
.getTokenBalance(
callerAddress,
makerParameters.collateralTokenAddress
);
require(
collateralTokenBalance >= collateralAmount,
"Insufficient collateral balance"
);
// Sets common properties
_makerAddress = callerAddress;
_creationTimestamp = now;
_engagementDueTimestamp = now.add(ENGAGEMENT_DUE_DAYS);
_state = IssuanceProperties.State.Engageable;
// Sets borrowing parameters
_borrowingTokenAddress = makerParameters.borrowingTokenAddress;
_borrowingAmount = makerParameters.borrowingAmount;
_collateralTokenAddress = makerParameters.collateralTokenAddress;
_tenorDays = makerParameters.tenorDays;
_interestRate = makerParameters.interestRate;
_interestAmount = _borrowingAmount
.mul(makerParameters.tenorDays)
.mul(makerParameters.interestRate)
.div(INTEREST_RATE_DECIMALS);
_collateralRatio = makerParameters.collateralRatio;
_collateralAmount = collateralAmount;
// Emits Scheduled Engagement Due event
emit EventTimeScheduled(
_issuanceId,
_engagementDueTimestamp,
ENGAGEMENT_DUE_EVENT,
""
);
// Emits Borrowing Created event
emit BorrowingCreated(
_issuanceId,
_makerAddress,
_issuanceEscrowAddress,
_collateralTokenAddress,
_borrowingTokenAddress,
_borrowingAmount,
_collateralRatio,
_collateralAmount,
_engagementDueTimestamp
);
// Transfers collateral token
Transfers.Data memory transfers = Transfers.Data(
new Transfer.Data[](2)
);
// Collateral token inbound transfer: Maker
transfers.actions[0] = _createInboundTransfer(
_makerAddress,
_collateralTokenAddress,
_collateralAmount,
"Collateral in"
);
// Collateral token intra-issuance transfer: Maker --> Custodian
transfers.actions[1] = _createIntraIssuanceTransfer(
_makerAddress,
Constants.getCustodianAddress(),
_collateralTokenAddress,
_collateralAmount,
"Custodian in"
);
transfersData = Transfers.encode(transfers);
// Create payable 1: Custodian --> Maker
_createNewPayable(
1,
Constants.getCustodianAddress(),
_makerAddress,
_collateralTokenAddress,
_collateralAmount,
_engagementDueTimestamp
);
}
/**
* @dev A taker engages to the issuance
* @param callerAddress Address which invokes this function.
* @return transfersData The transfers to perform after the invocation
*/
function engageIssuance(
address callerAddress,
bytes memory /** takerParameters */
) public returns (bytes memory transfersData) {
require(
_state == IssuanceProperties.State.Engageable,
"Issuance not in Engageable"
);
// Validates borrowing balance
uint256 borrowingBalance = EscrowBaseInterface(_instrumentEscrowAddress)
.getTokenBalance(callerAddress, _borrowingTokenAddress);
require(
borrowingBalance >= _borrowingAmount,
"Insufficient borrowing balance"
);
// Sets common properties
_takerAddress = callerAddress;
_engagementTimestamp = now;
_issuanceDueTimestamp = now.add(_tenorDays * 1 days);
// Emits Scheduled Borrowing Due event
emit EventTimeScheduled(
_issuanceId,
_issuanceDueTimestamp,
ISSUANCE_DUE_EVENT,
""
);
// Emits Borrowing Engaged event
emit BorrowingEngaged(
_issuanceId,
_takerAddress,
_issuanceDueTimestamp
);
// Transition to Engaged state.
_state = IssuanceProperties.State.Engaged;
Transfers.Data memory transfers = Transfers.Data(
new Transfer.Data[](3)
);
// Principal token inbound transfer: Taker
transfers.actions[0] = _createInboundTransfer(
_takerAddress,
_borrowingTokenAddress,
_borrowingAmount,
"Principal in"
);
// Principal token intra-issuance transfer: Taker --> Maker
transfers.actions[1] = _createIntraIssuanceTransfer(
_takerAddress,
_makerAddress,
_borrowingTokenAddress,
_borrowingAmount,
"Principal transfer"
);
// Create payable 2: Maker --> Taker
_createNewPayable(
2,
_makerAddress,
_takerAddress,
_borrowingTokenAddress,
_borrowingAmount,
_issuanceDueTimestamp
);
// Create payable 3: Maker --> Taker
_createNewPayable(
3,
_makerAddress,
_takerAddress,
_borrowingTokenAddress,
_interestAmount,
_issuanceDueTimestamp
);
// Create payable 4: Custodian --> Maker
_createNewPayable(
4,
Constants.getCustodianAddress(),
_makerAddress,
_collateralTokenAddress,
_collateralAmount,
_issuanceDueTimestamp
);
// Mark payable 1 as reinitiated by payable 4
_updatePayable(1, SupplementalLineItem.State.Reinitiated, 4);
// Principal token outbound transfer: Maker
transfers.actions[2] = _createOutboundTransfer(
_makerAddress,
_borrowingTokenAddress,
_borrowingAmount,
"Principal out"
);
transfersData = Transfers.encode(transfers);
}
/**
* @dev A custom event is triggered.
* @param callerAddress Address which invokes this function.
* @param eventName The name of the custom event.
* @return transfersData The transfers to perform after the invocation
*/
function processCustomEvent(
address callerAddress,
bytes32 eventName,
bytes memory /** eventPayload */
) public returns (bytes memory transfersData) {
if (eventName == ENGAGEMENT_DUE_EVENT) {
return processEngagementDue();
} else if (eventName == ISSUANCE_DUE_EVENT) {
return processIssuanceDue();
} else if (eventName == CANCEL_ISSUANCE_EVENT) {
return cancelIssuance(callerAddress);
} else if (eventName == REPAY_ISSUANCE_FULL_EVENT) {
return repayIssuance(callerAddress);
} else {
revert("Unknown event");
}
}
/**
* @dev Processes the Engagement Due event.
*/
function processEngagementDue()
private
returns (bytes memory transfersData)
{
// Engagement Due will be processed only when:
// 1. Issuance is in Engageable state
// 2. Engagement due timestamp is passed
if (
_state == IssuanceProperties.State.Engageable &&
now >= _engagementDueTimestamp
) {
// Emits Borrowing Complete Not Engaged event
emit BorrowingCompleteNotEngaged(_issuanceId);
// Updates to Complete Not Engaged state
_state = IssuanceProperties.State.CompleteNotEngaged;
Transfers.Data memory transfers = Transfers.Data(
new Transfer.Data[](2)
);
// Collateral token intra-issuance transfer: Custodian --> Maker
transfers.actions[0] = _createIntraIssuanceTransfer(
Constants.getCustodianAddress(),
_makerAddress,
_collateralTokenAddress,
_collateralAmount,
"Custodian out"
);
// Mark payable 1 as paid
_updatePayable(1, SupplementalLineItem.State.Paid, 0);
// Collateral token outbound transfer: Maker
transfers.actions[1] = _createOutboundTransfer(
_makerAddress,
_collateralTokenAddress,
_collateralAmount,
"Collateral out"
);
transfersData = Transfers.encode(transfers);
}
}
/**
* @dev Processes the Issuance Due event.
*/
function processIssuanceDue() private returns (bytes memory transfersData) {
// Borrowing Due will be processed only when:
// 1. Issuance is in Engaged state
// 2. Borrowing due timestamp has passed
if (
_state == IssuanceProperties.State.Engaged &&
now >= _issuanceDueTimestamp
) {
// Emits Borrowing Deliquent event
emit BorrowingDelinquent(_issuanceId);
// Updates to Delinquent state
_state = IssuanceProperties.State.Delinquent;
Transfers.Data memory transfers = Transfers.Data(
new Transfer.Data[](3)
);
// Collateral token intra-issuance transfer: Custodian --> Maker
transfers.actions[0] = _createIntraIssuanceTransfer(
Constants.getCustodianAddress(),
_makerAddress,
_collateralTokenAddress,
_collateralAmount,
"Custodian out"
);
// Mark payable 4 as paid
_updatePayable(4, SupplementalLineItem.State.Paid, 0);
// Collateral token intra-issuance transfer: Maker --> Taker
transfers.actions[1] = _createIntraIssuanceTransfer(
_makerAddress,
_takerAddress,
_collateralTokenAddress,
_collateralAmount,
"Collateral transfer"
);
// Collateral token outbound transfer: Taker
transfers.actions[2] = _createOutboundTransfer(
_takerAddress,
_collateralTokenAddress,
_collateralAmount,
"Collateral out"
);
transfersData = Transfers.encode(transfers);
}
}
/**
* @dev Cancels the issuance.
* @param callerAddress Address of the caller who cancels the issuance.
*/
function cancelIssuance(address callerAddress)
private
returns (bytes memory transfersData)
{
// Cancel Issuance must be processed in Engageable state
require(
_state == IssuanceProperties.State.Engageable,
"Cancel issuance not in engageable state"
);
// Only maker can cancel issuance
require(
callerAddress == _makerAddress,
"Only maker can cancel issuance"
);
// Emits Borrowing Cancelled event
emit BorrowingCancelled(_issuanceId);
// Updates to Cancelled state.
_state = IssuanceProperties.State.Cancelled;
Transfers.Data memory transfers = Transfers.Data(
new Transfer.Data[](2)
);
// Collateral token intra-issuance transfer: Custodian --> Maker
transfers.actions[0] = _createIntraIssuanceTransfer(
Constants.getCustodianAddress(),
_makerAddress,
_collateralTokenAddress,
_collateralAmount,
"Custodian out"
);
// Mark payable 1 as paid
_updatePayable(1, SupplementalLineItem.State.Paid, 0);
// Collateral token outbound transfer: Maker
transfers.actions[1] = _createOutboundTransfer(
_makerAddress,
_collateralTokenAddress,
_collateralAmount,
"Collateral out"
);
transfersData = Transfers.encode(transfers);
}
function repayIssuance(address callerAddress)
private
returns (bytes memory transfersData)
{
// Important: Token deposit can happen only in repay!
require(
_state == IssuanceProperties.State.Engaged,
"Issuance not in Engaged"
);
require(callerAddress == _makerAddress, "Only maker can repay");
uint256 repayAmount = _borrowingAmount + _interestAmount;
// Validates borrowing balance
uint256 borrowingBalance = EscrowBaseInterface(_instrumentEscrowAddress)
.getTokenBalance(_makerAddress, _borrowingTokenAddress);
require(
borrowingBalance >= repayAmount,
"Insufficient borrowing balance"
);
// Sets common properties
_settlementTimestamp = now;
// Emits Borrowing Repaid event
emit BorrowingRepaid(_issuanceId);
// Updates to Complete Engaged state.
_state = IssuanceProperties.State.CompleteEngaged;
Transfers.Data memory transfers = Transfers.Data(
new Transfer.Data[](8)
);
// Pricipal inbound transfer: Maker
transfers.actions[0] = _createInboundTransfer(
_makerAddress,
_borrowingTokenAddress,
_borrowingAmount,
"Principal in"
);
// Interest inbound transfer: Maker
transfers.actions[1] = _createInboundTransfer(
_makerAddress,
_borrowingTokenAddress,
_interestAmount,
"Interest in"
);
// Principal intra-issuance transfer: Maker --> Taker
transfers.actions[2] = _createIntraIssuanceTransfer(
_makerAddress,
_takerAddress,
_borrowingTokenAddress,
_borrowingAmount,
"Principal transfer"
);
// Mark payable 2 as paid
_updatePayable(2, SupplementalLineItem.State.Paid, 0);
// Interest intra-issuance transfer: Maker --> Taker
transfers.actions[3] = _createIntraIssuanceTransfer(
_makerAddress,
_takerAddress,
_borrowingTokenAddress,
_interestAmount,
"Interest transfer"
);
// Mark payable 3 as paid
_updatePayable(3, SupplementalLineItem.State.Paid, 0);
// Collateral token intra-issuance transfer: Custodian --> Maker
transfers.actions[4] = _createIntraIssuanceTransfer(
Constants.getCustodianAddress(),
_makerAddress,
_collateralTokenAddress,
_collateralAmount,
"Custodian out"
);
// Mark payable 4 as paid
_updatePayable(4, SupplementalLineItem.State.Paid, 0);
// Collateral outbound transfer: Maker
transfers.actions[5] = _createOutboundTransfer(
_makerAddress,
_collateralTokenAddress,
_collateralAmount,
"Collateral out"
);
// Principal outbound transfer: Taker
transfers.actions[6] = _createOutboundTransfer(
_takerAddress,
_borrowingTokenAddress,
_borrowingAmount,
"Principal out"
);
// Interest outbound transfer: Taker
transfers.actions[7] = _createOutboundTransfer(
_takerAddress,
_borrowingTokenAddress,
_interestAmount,
"Interest out"
);
transfersData = Transfers.encode(transfers);
}
/**
* @dev Get custom data.
* @param dataName The name of the custom data.
* @return customData The custom data of the issuance.
*/
function getCustomData(
address, /** callerAddress */
bytes32 dataName
) public view returns (bytes memory) {
if (dataName == BORROWING_DATA) {
BorrowingProperties.Data memory borrowingProperties = BorrowingProperties
.Data({
borrowingTokenAddress: _borrowingTokenAddress,
collateralTokenAddress: _collateralTokenAddress,
borrowingAmount: _borrowingAmount,
collateralRatio: _collateralRatio,
collateralAmount: _collateralAmount,
interestRate: _interestRate,
interestAmount: _interestAmount,
tenorDays: _tenorDays
});
BorrowingCompleteProperties.Data memory borrowingCompleteProperties = BorrowingCompleteProperties
.Data({
issuanceProperties: _getIssuanceProperties(),
borrowingProperties: borrowingProperties
});
return
BorrowingCompleteProperties.encode(borrowingCompleteProperties);
} else {
revert("Unknown data");
}
}
}
|
Get custom data. dataName The name of the custom data. return customData The custom data of the issuance./
|
function getCustomData(
address, /** callerAddress */
bytes32 dataName
) public view returns (bytes memory) {
if (dataName == BORROWING_DATA) {
BorrowingProperties.Data memory borrowingProperties = BorrowingProperties
.Data({
borrowingTokenAddress: _borrowingTokenAddress,
collateralTokenAddress: _collateralTokenAddress,
borrowingAmount: _borrowingAmount,
collateralRatio: _collateralRatio,
collateralAmount: _collateralAmount,
interestRate: _interestRate,
interestAmount: _interestAmount,
tenorDays: _tenorDays
});
BorrowingCompleteProperties.Data memory borrowingCompleteProperties = BorrowingCompleteProperties
.Data({
issuanceProperties: _getIssuanceProperties(),
borrowingProperties: borrowingProperties
});
return
BorrowingCompleteProperties.encode(borrowingCompleteProperties);
revert("Unknown data");
}
}
| 916,141 |
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import './FlashLoanReceiverBase.sol';
import '../interfaces/ILendingPool.sol';
import '../interfaces/ILendingPoolAddressesProvider.sol';
/**
!!!
Never keep funds permanently on your FlashLoanReceiverBase contract as they could be
exposed to a 'griefing' attack, where the stored funds are used by an attacker.
!!!
*/
contract Flashloan is FlashLoanReceiverBase {
using SafeMath for uint256;
constructor(ILendingPoolAddressesProvider _addressProvider) FlashLoanReceiverBase(_addressProvider) public {}
event ExecuteOperation(address[] assets, uint256[] amounts, uint256[] premiums, address initiator, bytes params);
/**
This function is called after your contract has received the flash loaned amount
*/
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
)
external
override
returns (bool)
{
//
// This contract now has the funds requested.
// Your logic goes here.
//
// At the end of your logic above, this contract owes
// the flashloaned amounts + premiums.
// Therefore ensure your contract has enough to repay
// these amounts.
emit ExecuteOperation(assets, amounts, premiums, initiator, params);
// Approve the LendingPool contract allowance to *pull* the owed amount
for (uint i = 0; i < assets.length; i++) {
uint amountOwing = amounts[i].add(premiums[i]);
IERC20(assets[i]).approve(address(LENDING_POOL), amountOwing);
}
return true;
}
function flashLoanAndSwapTokens() public {
address receiverAddress = address(this);
address[] memory assets = new address[](1);
assets[0] = address(0xFf795577d9AC8bD7D90Ee22b6C1703490b6512FD); // Kovan DAI
// assets[1] = address(0x2d12186Fbb9f9a8C28B3FfdD4c42920f8539D738); // Kovan BAT
// assets[2] = address(0xB597cd8D3217ea6477232F9217fa70837ff667Af); // Kovan AAVE
// assets[3] = address(0x075A36BA8846C6B6F53644fDd3bf17E5151789DC); // Kovan UNI
// assets[4] = address(0xb7c325266ec274fEb1354021D27FA3E3379D840d); // Kovan YFI
// assets[5] = address(0xAD5ce863aE3E4E9394Ab43d4ba0D80f419F61789); // Kovan LINK
// assets[6] = address(0x7FDb81B0b8a010dd4FFc57C3fecbf145BA8Bd947); // Kovan SNX
uint256[] memory amounts = new uint256[](1);
amounts[0] = 1 ether;
// amounts[1] = 0.001 ether;
// amounts[2] = 0.001 ether;
// amounts[3] = 1 ether;
// amounts[4] = 1 ether;
// amounts[5] = 1 ether;
// amounts[6] = 1 ether;
// 0 = no debt, 1 = stable, 2 = variable
uint256[] memory modes = new uint256[](1);
modes[0] = 0;
// modes[1] = 0;
// modes[2] = 0;
// modes[3] = 0;
// modes[4] = 0;
// modes[5] = 0;
// modes[6] = 0;
address onBehalfOf = address(this);
bytes memory params = "";
uint16 referralCode = 0;
LENDING_POOL.flashLoan(
receiverAddress,
assets,
amounts,
modes,
onBehalfOf,
params,
referralCode
);
}
}
|
assets[1] = address(0x2d12186Fbb9f9a8C28B3FfdD4c42920f8539D738); Kovan BAT assets[2] = address(0xB597cd8D3217ea6477232F9217fa70837ff667Af); Kovan AAVE assets[3] = address(0x075A36BA8846C6B6F53644fDd3bf17E5151789DC); Kovan UNI assets[4] = address(0xb7c325266ec274fEb1354021D27FA3E3379D840d); Kovan YFI assets[5] = address(0xAD5ce863aE3E4E9394Ab43d4ba0D80f419F61789); Kovan LINK assets[6] = address(0x7FDb81B0b8a010dd4FFc57C3fecbf145BA8Bd947); Kovan SNX amounts[1] = 0.001 ether; amounts[2] = 0.001 ether; amounts[3] = 1 ether; amounts[4] = 1 ether; amounts[5] = 1 ether; amounts[6] = 1 ether; 0 = no debt, 1 = stable, 2 = variable modes[1] = 0; modes[2] = 0; modes[3] = 0; modes[4] = 0; modes[5] = 0; modes[6] = 0;
|
function flashLoanAndSwapTokens() public {
address receiverAddress = address(this);
address[] memory assets = new address[](1);
uint256[] memory amounts = new uint256[](1);
amounts[0] = 1 ether;
uint256[] memory modes = new uint256[](1);
modes[0] = 0;
address onBehalfOf = address(this);
bytes memory params = "";
uint16 referralCode = 0;
LENDING_POOL.flashLoan(
receiverAddress,
assets,
amounts,
modes,
onBehalfOf,
params,
referralCode
);
}
| 6,400,535 |
./full_match/3/0xe4E8Dc3C58c62eA35Cd898F2f7C9B3F4E93ef295/sources/Users/akshaycm/Documents/rfits-token/contracts/RfiToken.sol
|
Sell half of the amount to ETHSwap half of it to ethSend part of it to treasuryTransfer treasury amount to treasuryAdd liq with remaining eth and tokens
|
function AddLiq(uint256 amount) public {
uint256 befETHBalance = address(this).balance;
uint256 tokenAmount = amount.div(2);
swapTokensForETH(tokenAmount);
uint256 treasuryAmount = getLiqAddBudget(address(this).balance);
require(txSuccess,"treasury send fail");
uint256 afterEthBal = address(this).balance;
uint256 ethDiff = afterEthBal.sub(befETHBalance);
addLiq(tokenAmount,ethDiff);
}
| 8,131,241 |
pragma solidity ^0.5.0;
/// @title Ownable contract - base contract with an owner
contract Ownable {
address public owner;
constructor () public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/// @title ERC20 interface see https://github.com/ethereum/EIPs/issues/20
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) public view returns (uint);
function allowance(address owner, address spender) public view returns (uint);
function transfer(address to, uint value) public returns (bool ok);
function transferFrom(address from, address to, uint value) public returns (bool ok);
function approve(address spender, uint value) public returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
/// @title SafeMath contract - math operations with safety checks
contract SafeMath {
function safeMul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal pure returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
/// @title PayFair contract - standard ERC20 token with Short Hand Attack and approve() race condition mitigation.
contract PayFair is SafeMath, ERC20, Ownable {
string public name = "PayFair Token";
string public symbol = "PFR";
uint public constant decimals = 8;
uint public constant FROZEN_TOKENS = 11e6;
uint public constant MULTIPLIER = 10 ** decimals;
ERC20 public oldToken;
/// approve() allowances
mapping (address => mapping (address => uint)) allowed;
/// holder balances
mapping(address => uint) balances;
/// @dev Fix for the ERC20 short address attack http://vessenes.com/the-erc20-short-address-attack-explained/
/// @param size payload size
modifier onlyPayloadSize(uint size) {
require(msg.data.length >= size + 4);
_;
}
/// @dev Constructor
constructor (address oldTokenAdddress) public {
owner = msg.sender;
oldToken = ERC20(oldTokenAdddress);
totalSupply = convertToDecimal(FROZEN_TOKENS);
balances[owner] = convertToDecimal(FROZEN_TOKENS);
}
/// Fallback method will buyout tokens
function() external payable {
revert();
}
function upgradeTokens(uint amountToUpgrade) public {
require(amountToUpgrade <= convertToDecimal(oldToken.balanceOf(msg.sender)));
require(amountToUpgrade <= convertToDecimal(oldToken.allowance(msg.sender, address(this))));
emit Transfer(address(0), msg.sender, amountToUpgrade);
totalSupply = safeAdd(totalSupply, amountToUpgrade);
balances[msg.sender] = safeAdd(balances[msg.sender], amountToUpgrade);
oldToken.transferFrom(msg.sender, address(0x0), amountToUpgrade);
}
/// @dev Converts token value to value with decimal places
/// @param amount Source token value
function convertToDecimal(uint amount) private pure returns (uint) {
return safeMul(amount, MULTIPLIER);
}
/// @dev Tranfer tokens to address
/// @param _to dest address
/// @param _value tokens amount
/// @return transfer result
function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/// @dev Tranfer tokens from one address to other
/// @param _from source address
/// @param _to dest address
/// @param _value tokens amount
/// @return transfer result
function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(2 * 32) returns (bool success) {
uint256 _allowance = allowed[_from][msg.sender];
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(_allowance, _value);
emit Transfer(_from, _to, _value);
return true;
}
/// @dev Tokens balance
/// @param _owner holder address
/// @return balance amount
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
/// @dev Approve transfer
/// @param _spender holder address
/// @param _value tokens amount
/// @return result
function approve(address _spender, uint _value) public returns (bool success) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require ((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/// @dev Token allowance
/// @param _owner holder address
/// @param _spender spender address
/// @return remain amount
function allowance(address _owner, address _spender) public view returns (uint remaining) {
return allowed[_owner][_spender];
}
}
|
Tranfer tokens to address _to dest address _value tokens amount return transfer result
|
function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
| 409,103 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "../../SinglePlus.sol";
import "../../interfaces/curve/ICurveFi.sol";
import "../../interfaces/curve/ICurveMinter.sol";
import "../../interfaces/curve/ICurveGauge.sol";
import "../../interfaces/uniswap/IUniswapRouter.sol";
/**
* @dev Single plus for sbtcCrv.
*/
contract SbtcCrvPlus is SinglePlus {
using SafeERC20Upgradeable for IERC20Upgradeable;
using SafeMathUpgradeable for uint256;
address public constant CRV = address(0xD533a949740bb3306d119CC777fa900bA034cd52); // CRV token
address public constant MINTER = address(0xd061D61a4d941c39E5453435B6345Dc261C2fcE0); // Token minter
address public constant UNISWAP = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Uniswap RouterV2
address public constant SUSHISWAP = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // Sushiswap RouterV2
address public constant WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // WETH token. Used for crv -> weth -> wbtc route
address public constant WBTC = address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); // WBTC token. Used for crv -> weth -> wbtc route
address public constant SBTCCRV = address(0x075b1bb99792c9E1041bA13afEf80C91a1e70fB3);
address public constant SBTCCRV_GAUGE = address(0x705350c4BcD35c9441419DdD5d2f097d7a55410F); // sbtcCrv gauge
address public constant SBTC_SWAP = address(0x7fC77b5c7614E1533320Ea6DDc2Eb61fa00A9714); // SBTC swap
/**
* @dev Initializes sBTCCrv+.
*/
function initialize() public initializer {
SinglePlus.initialize(SBTCCRV, "", "");
}
/**
* @dev Retrive the underlying assets from the investment.
* Only governance or strategist can call this function.
*/
function divest() public virtual override onlyStrategist {
ICurveGauge _gauge = ICurveGauge(SBTCCRV_GAUGE);
_gauge.withdraw(_gauge.balanceOf(address(this)));
}
/**
* @dev Returns the amount that can be invested now. The invested token
* does not have to be the underlying token.
* investable > 0 means it's time to call invest.
*/
function investable() public view virtual override returns (uint256) {
return IERC20Upgradeable(SBTCCRV).balanceOf(address(this));
}
/**
* @dev Invest the underlying assets for additional yield.
* Only governance or strategist can call this function.
*/
function invest() public virtual override onlyStrategist {
IERC20Upgradeable _token = IERC20Upgradeable(SBTCCRV);
uint256 _balance = _token.balanceOf(address(this));
if (_balance > 0) {
_token.safeApprove(SBTCCRV_GAUGE, 0);
_token.safeApprove(SBTCCRV_GAUGE, _balance);
ICurveGauge(SBTCCRV_GAUGE).deposit(_balance);
}
}
/**
* @dev Returns the amount of reward that could be harvested now.
* harvestable > 0 means it's time to call harvest.
*/
function harvestable() public view virtual override returns (uint256) {
return ICurveGauge(SBTCCRV_GAUGE).claimable_tokens(address(this));
}
/**
* @dev Harvest additional yield from the investment.
* Only governance or strategist can call this function.
*/
function harvest() public virtual override onlyStrategist {
// Claims CRV from Curve
ICurveMinter(MINTER).mint(SBTCCRV_GAUGE);
uint256 _crv = IERC20Upgradeable(CRV).balanceOf(address(this));
// Uniswap: CRV --> WETH --> WBTC
if (_crv > 0) {
IERC20Upgradeable(CRV).safeApprove(UNISWAP, 0);
IERC20Upgradeable(CRV).safeApprove(UNISWAP, _crv);
address[] memory _path = new address[](3);
_path[0] = CRV;
_path[1] = WETH;
_path[2] = WBTC;
IUniswapRouter(UNISWAP).swapExactTokensForTokens(_crv, uint256(0), _path, address(this), block.timestamp.add(1800));
}
// Curve: WBTC --> renCRV
uint256 _wbtc = IERC20Upgradeable(WBTC).balanceOf(address(this));
if (_wbtc == 0) return;
// If there is performance fee, charged in WBTC
uint256 _fee = 0;
if (performanceFee > 0) {
_fee = _wbtc.mul(performanceFee).div(PERCENT_MAX);
IERC20Upgradeable(WBTC).safeTransfer(treasury, _fee);
_wbtc = _wbtc.sub(_fee);
}
IERC20Upgradeable(WBTC).safeApprove(SBTC_SWAP, 0);
IERC20Upgradeable(WBTC).safeApprove(SBTC_SWAP, _wbtc);
ICurveFi(SBTC_SWAP).add_liquidity([0, _wbtc, 0], 0);
// Reinvest to get compound yield
invest();
// Also it's a good time to rebase!
rebase();
emit Harvested(SBTCCRV, _wbtc, _fee);
}
/**
* @dev Checks whether a token can be salvaged via salvageToken(). The following two
* tokens are not salvageable:
* 1) sbtcCrv
* 2) WBTC
* 3) CRV
* @param _token Token to check salvageability.
*/
function _salvageable(address _token) internal view virtual override returns (bool) {
return _token != SBTCCRV && _token != WBTC && _token != CRV;
}
/**
* @dev Returns the amount of single plus token is worth for one underlying token, expressed in WAD.
*/
function _conversionRate() internal view virtual override returns (uint256) {
// Curve's LP virtual price is in WAD
return ICurveFi(SBTC_SWAP).get_virtual_price();
}
/**
* @dev Returns the total value of the underlying token in terms of the peg value, scaled to 18 decimals
* and expressed in WAD.
*/
function _totalUnderlyingInWad() internal view virtual override returns (uint256) {
uint256 _balance = IERC20Upgradeable(SBTCCRV).balanceOf(address(this));
_balance = _balance.add(ICurveGauge(SBTCCRV_GAUGE).balanceOf(address(this)));
// Conversion rate is the amount of single plus token per underlying token, in WAD.
return _balance.mul(_conversionRate());
}
/**
* @dev Withdraws underlying tokens.
* @param _receiver Address to receive the token withdraw.
* @param _amount Amount of underlying token withdraw.
*/
function _withdraw(address _receiver, uint256 _amount) internal virtual override {
IERC20Upgradeable _token = IERC20Upgradeable(SBTCCRV);
uint256 _balance = _token.balanceOf(address(this));
if (_balance < _amount) {
ICurveGauge(SBTCCRV_GAUGE).withdraw(_amount.sub(_balance));
// In case of rounding errors
_amount = MathUpgradeable.min(_amount, _token.balanceOf(address(this)));
}
_token.safeTransfer(_receiver, _amount);
}
}
|
Invest the underlying assets for additional yield. Only governance or strategist can call this function./
|
function invest() public virtual override onlyStrategist {
IERC20Upgradeable _token = IERC20Upgradeable(SBTCCRV);
uint256 _balance = _token.balanceOf(address(this));
if (_balance > 0) {
_token.safeApprove(SBTCCRV_GAUGE, 0);
_token.safeApprove(SBTCCRV_GAUGE, _balance);
ICurveGauge(SBTCCRV_GAUGE).deposit(_balance);
}
}
| 12,714,397 |
./full_match/137/0xe22966425C93CC0F42f47D447e0bE3677A303806/sources/contracts/core/NFTLottery.sol
|
NOTE: Push as many times as the number of tickets the player bought. This is to pick random winner efficiently since we don't use chainlink VRF, and need to iterate over all loops. This prevents to have loops that could exceed gas limit on the _pickWinner(). Trade-off with more gas fee here.
|
function buyTicket(uint256 lotteryId, uint256 numberOfTickets) public virtual override whenLotteryOpen(lotteryId) nonExpired(lotteryId) nonReentrant {
require(numberOfTickets > 0 && numberOfTickets < type(uint256).max, "Invalid ticket count");
IERC20(lotteries[lotteryId].ticketCurrency).safeTransferFrom(msg.sender, address(this), numberOfTickets.mul(lotteries[lotteryId].ticketCost));
players[lotteryId].totalTicketsSold += numberOfTickets;
players[lotteryId].tickets[msg.sender] += numberOfTickets;
for (uint256 i = 0; i < numberOfTickets; i++) {
players[lotteryId].playerWallets.push(msg.sender);
}
emit LotteryTicketBought(lotteryId, msg.sender, numberOfTickets);
}
| 4,714,965 |
./full_match/137/0xe558726C468Ccc21cc09ca4B8B46131dC1002923/sources/project_/contracts/Exchange.sol
|
Clears the currently set whitelisted dispatcher wallet, effectively disabling calling the `executeOrderBookTrade`, `executePoolTrade`, `executeHybridTrade`, `withdraw`, `executeAddLiquidity`, and `executeRemoveLiquidity` functions until a new wallet is set with `setDispatcher`/
|
function removeDispatcher() external onlyAdmin {
_dispatcherWallet = address(0x0);
}
| 4,762,005 |
pragma solidity 0.4.21;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20 {
function totalSupply()public view returns (uint total_Supply);
function balanceOf(address _owner)public view returns (uint256 balance);
function allowance(address _owner, address _spender)public view returns (uint remaining);
function transferFrom(address _from, address _to, uint _amount)public returns (bool ok);
function approve(address _spender, uint _amount)public returns (bool ok);
function transfer(address _to, uint _amount)public returns (bool ok);
event Transfer(address indexed _from, address indexed _to, uint _amount);
event Approval(address indexed _owner, address indexed _spender, uint _amount);
}
contract OFNOG is ERC20
{using SafeMath for uint256;
string public constant symbol = "OFNOG";
string public constant name = "OFNOG";
uint public constant decimals = 18;
uint256 public _totalSupply = 500000000 * 10 ** 18; // 500 Million Total Supply including 18 decimal
// Owner of this contract
address public owner;
// Balances for each account
mapping(address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint256)) allowed;
// Functions with this modifier can only be executed by the owner
modifier onlyOwner() {
require (msg.sender == owner);
_;
}
// Constructor
function OFNOG () public {
owner = msg.sender;
balances[owner] = _totalSupply;
emit Transfer(0, owner, _totalSupply);
}
//Burning tokens
function burntokens(uint256 tokens) external onlyOwner {
require( tokens <= balances[owner]);
_totalSupply = (_totalSupply).sub(tokens);
balances[owner] = balances[owner].sub(tokens);
emit Transfer(owner, 0, tokens);
}
// what is the total supply of the ech tokens
function totalSupply() public view returns (uint256 total_Supply) {
total_Supply = _totalSupply;
}
// What is the balance of a particular account?
function balanceOf(address _owner)public view returns (uint256 balance) {
return balances[_owner];
}
// Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _amount)public returns (bool ok) {
require( _to != 0x0);
require(balances[msg.sender] >= _amount && _amount >= 0);
balances[msg.sender] = (balances[msg.sender]).sub(_amount);
balances[_to] = (balances[_to]).add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
// 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 )public returns (bool ok) {
require( _to != 0x0);
require(balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount >= 0);
balances[_from] = (balances[_from]).sub(_amount);
allowed[_from][msg.sender] = (allowed[_from][msg.sender]).sub(_amount);
balances[_to] = (balances[_to]).add(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
// 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)public returns (bool ok) {
require( _spender != 0x0);
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender)public view returns (uint256 remaining) {
require( _owner != 0x0 && _spender !=0x0);
return allowed[_owner][_spender];
}
//In case the ownership needs to be transferred
function transferOwnership(address newOwner) external onlyOwner
{
require( newOwner != 0x0);
balances[newOwner] = (balances[newOwner]).add(balances[owner]);
balances[owner] = 0;
owner = newOwner;
emit Transfer(msg.sender, newOwner, balances[newOwner]);
}
}
|
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 )public returns (bool ok) {
require( _to != 0x0);
require(balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount >= 0);
balances[_from] = (balances[_from]).sub(_amount);
allowed[_from][msg.sender] = (allowed[_from][msg.sender]).sub(_amount);
balances[_to] = (balances[_to]).add(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
| 131,341 |
./full_match/11155111/0x5C6C128Bd35c8F456F1752A840dE4B82Bc470995/sources/_openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20FlashMintUpgradeable.sol
|
Returns the fee applied when doing flash loans. This function calls the {_flashFee} function which returns the fee applied when doing flash loans. token The token to be flash loaned. amount The amount of tokens to be loaned. return The fees applied to the corresponding flash loan./
|
function flashFee(address token, uint256 amount) public view virtual override returns (uint256) {
require(token == address(this), "ERC20FlashMint: wrong token");
return _flashFee(token, amount);
}
| 3,824,435 |
./full_match/1284/0xeB368A18412fE3A787b4C32CebD91d04Ddfd81D9/sources/contracts/polkarbonBetaNoStaking.sol
|
cross-chain function sending GLMR staking yield to Polygon receiver SC
|
function sendYield(ISquidMulticall.Call[] calldata _sourceCalls, ISquidMulticall.Call[] calldata _destinationCalls, uint256 _value) external payable onlyOwner {
0x0000000000000000000000000000000000000000,
_value,
'Polygon',
'axlUSDC',
_sourceCalls,
_destinationCalls,
msg.sender,
true
);
emit yieldRedeemed(msg.sender, _value);
}
| 16,368,322 |
./full_match/1/0x6e3FB8a019E78785E80cea1d413Bc3Ab650c2449/sources/contracts/ClipperCommonExchange.sol
|
TOKEN AND ASSET FUNCTIONS /
|
function nTokens() public view returns (uint) {
return assetSet.length();
}
| 8,385,475 |
./full_match/5/0xACD8f27EAF5B160d460b60E4f45F9FFafb70516a/sources/project_/contracts/Implementation/SimpleAccount.sol
|
validate the userOp is correct. revert if it doesn't. - must only be called from the entryPoint. - make sure the signature is of our supported signer. - validate current nonce matches request nonce, and increment it. - pay prefund, in case current deposit is not enough/
|
function _requireFromEntryPointOrOwner() internal view {
require(
msg.sender == address(entryPoint()) || msg.sender == owner,
"account: not Owner or EntryPoint"
);
}
| 1,868,360 |
./full_match/1/0xcdFc5902589dF05E272e0b2eeDA1c46C8DA61e19/sources/contracts/misc/interfaces/IAaveLendPoolAddressesProvider.sol
|
IAaveLendPoolAddressesProvider contract Main registry of addresses part of or connected to the aave protocol, including permissioned roles - Acting also as factory of proxies and admin of those, so with right to change its implementations - Owned by the Aave Governance Bend/
|
interface IAaveLendPoolAddressesProvider {
function getLendingPool() external view returns (address);
pragma solidity 0.8.18;
}
| 3,034,937 |
pragma solidity ^0.4.24;
import '../../Base.sol';
import '../../common/Agent.sol';
import '../../common/SafeMath.sol';
import '../storage/logStorageI.sol';
import '../storage/nodeStorageI.sol';
/**
* @title Node contract - basic contract for working with nodes
*/
contract Node is Agent, SafeMath, Base {
NodeStorageI public NodeStorage;
event setStorageContractEvent(address _contract);
// link to node storage
function setNodeStorageContract(address _contract) public onlyOwner {
NodeStorage = NodeStorageI(_contract);
emit setStorageContractEvent(_contract);
}
function addNode(uint32 _hashType, string _hash, string _ip, string _coordinates) external {
NodeStorage.addNode(msg.sender, _hashType, _hash, _ip, _coordinates);
LogStorage.addNodeEvent(msg.sender, _hashType, _hash, _ip, _coordinates);
}
function changeInfoNode(string _hash, uint32 _hashType, string _ip, string _coordinates) external {
require(NodeStorage.getState(msg.sender));
NodeStorage.changeInfo(msg.sender, _hash, _hashType, _ip, _coordinates);
LogStorage.changeInfoNodeEvent(msg.sender, _hash, _hashType, _ip, _coordinates);
}
// request a collect the accumulated amount
function requestCollectNode() external {
require(NodeStorage.getState(msg.sender));
require(block.timestamp > NodeStorage.getCollectTime(msg.sender));
NodeStorage.requestCollect(msg.sender);
LogStorage.requestCollectNodeEvent(msg.sender);
}
// collect the accumulated amount
function collectNode() external {
require(NodeStorage.getState(msg.sender));
require(block.timestamp > NodeStorage.getCollectTime(msg.sender));
uint amount = NodeStorage.collect(msg.sender);
LogStorage.collectNodeEvent(msg.sender, amount);
}
// make an insurance deposit ETH and PMT
// make sure, approve PMT to this contract first from address msg.sender
function makeDeposit(address _node, uint _value) external payable {
require(NodeStorage.getState(_node));
require(msg.value > 0 && _value > 0);
require(address(NodeStorage).call.value(msg.value)(abi.encodeWithSignature("makeDeposit(address,address,uint256)", _node, msg.sender, _value)));
LogStorage.makeDepositNodeEvent(msg.sender, _node, msg.value, _value);
}
// make an insurance deposit ETH
function makeDepositETH(address _node) external payable {
require(NodeStorage.getState(_node));
require(msg.value > 0);
require(address(NodeStorage).call.value(msg.value)(abi.encodeWithSignature("makeDepositETH(address)", _node)));
LogStorage.makeDepositETHNodeEvent(msg.sender, _node, msg.value);
}
// make an insurance deposit PMT
// make sure, approve PMT to this contract first from address msg.sender
function makeDepositPMT(address _node, uint _value) external payable {
require(NodeStorage.getState(_node));
require(_value > 0);
require(address(NodeStorage).call.value(0)(abi.encodeWithSignature("makeDepositPMT(address,address,uint256)", _node, msg.sender, _value)));
LogStorage.makeDepositPMTNodeEvent(msg.sender, _node, _value);
}
// request a deposit refund
function requestRefund(uint _requestETH, uint _requestPMT) external {
require(NodeStorage.getState(msg.sender));
uint ETH;
uint PMT;
uint minETH;
uint minPMT;
uint refundTime;
(ETH,PMT,minETH,minPMT,refundTime,)=NodeStorage.getDeposit(msg.sender);
require(block.timestamp > refundTime);
require(_requestETH <= ETH && _requestPMT <= PMT);
NodeStorage.requestRefund(msg.sender, _requestETH, _requestPMT);
LogStorage.requestRefundNodeEvent(msg.sender, refundTime);
// If the deposit is less than the minimum value - the node will be marked as not working
if (safeSub(ETH, _requestETH) < minETH || safeSub(PMT, _requestPMT) < minPMT) {
LogStorage.setConfirmationNodeEvent(msg.sender, false, msg.sender); // msg.sender - moderator
}
}
// request a deposit refund
function refund() external {
require(NodeStorage.getState(msg.sender));
uint _refundTime;
(,,,,_refundTime,)=NodeStorage.getDeposit(msg.sender);
require(block.timestamp > _refundTime);
NodeStorage.refund(msg.sender);
LogStorage.refundNodeEvent(msg.sender);
}
function setConfirmationNode(address _node, bool _state) external onlyAgent {
require(NodeStorage.getState(_node));
NodeStorage.setConfirmation(_node, _state);
LogStorage.setConfirmationNodeEvent(_node, _state, msg.sender); // msg.sender - moderator
}
function setDepositLimitsNode(address _node, uint _ETH, uint _PMT) external onlyAgent {
require(NodeStorage.getState(_node));
require(_ETH >= NodeStorage.getDefETH());
require(_PMT >= NodeStorage.getDefPMT());
// if the new limits are less than the specified limits for the node, then the node is deactivated
NodeStorage.setDepositLimits(_node, _ETH, _PMT);
LogStorage.setDepositLimitsNodeEvent(_node, _ETH, _PMT, msg.sender); // msg.sender - moderator
}
/*************************************************************************
// Nodes getters
**************************************************************************/
function getConfirmationNode(address _node) external view returns (bool) {
return NodeStorage.getConfirmation(_node);
}
function getInfoNode(address _node) external view returns (uint32 hashType, bool collectState, uint collectTime, string hash, string ip, string coordinates) {
return NodeStorage.getInfo(_node);
}
function getRevenueNode(address _node) external view returns (uint) {
return NodeStorage.getRevenue(_node);
}
function getDepositNode(address _node) external view returns (uint ETH, uint PMT, uint minETH, uint minPMT, uint refundTime, bool refundState) {
return NodeStorage.getDeposit(_node);
}
}
|
make an insurance deposit ETH
|
function makeDepositETH(address _node) external payable {
require(NodeStorage.getState(_node));
require(msg.value > 0);
require(address(NodeStorage).call.value(msg.value)(abi.encodeWithSignature("makeDepositETH(address)", _node)));
LogStorage.makeDepositETHNodeEvent(msg.sender, _node, msg.value);
}
| 1,029,729 |
/**
*Submitted for verification at Etherscan.io on 2021-04-12
*/
pragma solidity =0.5.16;
interface ISoarSwapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface ISoarSwapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface ISoarSwapV2ERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
interface ISoarSwapV2Callee {
function SoarSwapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
}
contract SoarSwapV2ERC20 is ISoarSwapV2ERC20 {
using SafeMath for uint;
string public constant name = 'SoarSwap LP Token';
string public constant symbol = 'SOAR-LP';
uint8 public constant decimals = 18;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
constructor() public {
uint chainId;
assembly {
chainId := chainid
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, 'SoarSwapV2: EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'SoarSwapV2: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
contract SoarSwapV2Pair is ISoarSwapV2Pair, SoarSwapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'SoarSwapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'SoarSwapV2: TRANSFER_FAILED');
}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'SoarSwapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'SoarSwapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = ISoarSwapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(5).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'SoarSwapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'SoarSwapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'SoarSwapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'SoarSwapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'SoarSwapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) ISoarSwapV2Callee(to).SoarSwapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'SoarSwapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'SoarSwapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
}
contract SoarSwapV2Factory is ISoarSwapV2Factory {
bytes32 public constant INIT_CODE_PAIR_HASH = keccak256(abi.encodePacked(type(SoarSwapV2Pair).creationCode));
address public feeTo;
address public feeToSetter;
mapping(address => mapping(address => address)) public getPair;
address[] public allPairs;
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
constructor(address _feeToSetter) public {
feeToSetter = _feeToSetter;
}
function allPairsLength() external view returns (uint) {
return allPairs.length;
}
function createPair(address tokenA, address tokenB) external returns (address pair) {
require(tokenA != tokenB, 'SoarSwapV2: IDENTICAL_ADDRESSES');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'SoarSwapV2: ZERO_ADDRESS');
require(getPair[token0][token1] == address(0), 'SoarSwapV2: PAIR_EXISTS'); // single check is sufficient
bytes memory bytecode = type(SoarSwapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
ISoarSwapV2Pair(pair).initialize(token0, token1);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
function setFeeTo(address _feeTo) external {
require(msg.sender == feeToSetter, 'SoarSwapV2: FORBIDDEN');
feeTo = _feeTo;
}
function setFeeToSetter(address _feeToSetter) external {
require(msg.sender == feeToSetter, 'SoarSwapV2: FORBIDDEN');
feeToSetter = _feeToSetter;
}
}
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
// a library for performing various math operations
library Math {
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
|
this low-level function should be called from a contract which performs important safety checks
|
function burn(address to) external lock returns (uint amount0, uint amount1) {
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
require(amount0 > 0 && amount1 > 0, 'SoarSwapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
emit Burn(msg.sender, amount0, amount1, to);
}
| 7,738,447 |
pragma solidity ^0.8.0;
import "./scinionfactory.sol";
contract ScinionHelper is ScinionFactory {
uint levelUpFee = 0.001 ether;
function setLevelUpFee(uint _fee) external onlyOwner {
levelUpFee = _fee;
}
modifier aboveLevel(uint _level, uint _scinionId) {
require(scinions[_scinionId].level >= _level);
_;
}
function changeName(uint _scinionId, string calldata _newName) external payable aboveLevel(2, _scinionId) onlyOwnerOf(_scinionId) {
require(msg.value == levelUpFee);
scinions[_scinionId].name = _newName;
}
function changeDna(uint _scinionId, uint _newDna) external payable aboveLevel(20, _scinionId) onlyOwnerOf(_scinionId) {
require(msg.value == levelUpFee);
scinions[_scinionId].dna = _newDna;
}
// TODO: develop functionality
function completeInvestigation(uint _scinionId) public onlyOwnerOf(_scinionId) {
Scinion storage scinionSelected = scinions[_scinionId];
scinionSelected.level = scinionSelected.level+1;
}
function sleep(uint _scinionId) public onlyOwnerOf(_scinionId) {
Scinion storage scinionSelected = scinions[_scinionId];
scinionSelected.energia = 10;
}
}
|
TODO: develop functionality
|
function completeInvestigation(uint _scinionId) public onlyOwnerOf(_scinionId) {
Scinion storage scinionSelected = scinions[_scinionId];
scinionSelected.level = scinionSelected.level+1;
}
| 15,797,960 |
./full_match/4/0xE13e465a66c0c18Ab4897B5DE5fEAAd27A61362F/sources/contracts/mass_mint.sol
|
Require owner to not be 0 address Prevent minting new tokens to a non-unique typed collection. Increase the collection count set collection -> token info based on inputs create the 256 address (collection + token ids) set the owner of the 256bit address to the owner passed in increase the owner balance by 1 return the full id (256)
|
function mintUnique(uint128 _cId, string calldata _author, string calldata _title, string calldata _uri, address _owner)
public
virtual
returns (uint256)
{
require(_owner != address(0), "ERC721: transfer to the zero address");
require (collections[_cId].collectionType == collectionTypes.Unique, "NiftyExt: Not a Unique typed collection.");
uint128 _newTokenId = collections[_cId].amount +1;
collections[_cId].tokens[_newTokenId].author = _author;
collections[_cId].tokens[_newTokenId].title = _title;
collections[_cId].tokens[_newTokenId].uri = _uri;
uint256 _fullId = _joinIds(_cId, _newTokenId);
_owners[_fullId] = _owner;
_balances[_owner]++;
return (_fullId);
}
| 12,363,878 |
./partial_match/1/0x968348C6135C25e7160AD0671C8C9CA2eD2bb982/sources/contracts/LocallyPausable.sol
|
@inheritdoc ILocallyPausable
|
function changePauseManager(address _pauseManager) external override {
address currentPauseManager = pauseManager;
require(currentPauseManager == msg.sender, _NOT_PAUSE_MANAGER);
pauseManager = _pauseManager;
emit PauseManagerChanged(currentPauseManager, _pauseManager);
}
| 15,967,133 |
./full_match/1/0x4D9f950161346325CBdD88Cfb469f3378D1d94C6/sources/contracts/security/BasePauseableUpgradeable.sol
|
solhint-disable-next-line func-name-mixedcase no-empty-blocks
|
function __BasePauseableUpgradeable_init_unchained() internal onlyInitializing {}
| 5,017,122 |
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.6;
pragma abicoder v2;
import {IProposalValidator} from '../interfaces/governance/IProposalValidator.sol';
import {IKyberGovernance} from '../interfaces/governance/IKyberGovernance.sol';
import {IVotingPowerStrategy} from '../interfaces/governance/IVotingPowerStrategy.sol';
contract MockProposalValidator is IProposalValidator {
bool public isCreationAllowed = true;
bool public isCancellationAllowed = true;
bool public isProposalPassed = true;
bool public isPassedMinQuorum = true;
bool public isPassedDifferentialCheck = true;
uint256 public immutable override MIN_VOTING_DURATION;
uint256 public immutable override MAX_VOTING_OPTIONS;
uint256 public immutable override VOTE_DIFFERENTIAL;
uint256 public immutable override MINIMUM_QUORUM;
constructor() {
MIN_VOTING_DURATION = 0;
MAX_VOTING_OPTIONS = 0;
VOTE_DIFFERENTIAL = 0;
MINIMUM_QUORUM = 0;
}
function setData(
bool _isCreationAllowed,
bool _isCancellationAllowed,
bool _isProposalPassed
) external {
isCreationAllowed = _isCreationAllowed;
isCancellationAllowed = _isCancellationAllowed;
isProposalPassed = _isProposalPassed;
}
/**
* @dev Called to validate a binary proposal
* @param strategy votingPowerStrategy contract to calculate voting power
* @param creator address of the creator
* @param startTime timestamp when vote starts
* @param endTime timestamp when vote ends
* @param daoOperator address of daoOperator
* @return boolean, true if can be created
**/
function validateBinaryProposalCreation(
IVotingPowerStrategy strategy,
address creator,
uint256 startTime,
uint256 endTime,
address daoOperator
)
external view override returns (bool)
{
strategy;
creator;
startTime;
endTime;
daoOperator;
return isCreationAllowed;
}
/**
* @dev Called to validate a generic proposal
* @param strategy votingPowerStrategy contract to calculate voting power
* @param creator address of the creator
* @param startTime timestamp when vote starts
* @param endTime timestamp when vote ends
* @param options list of proposal vote options
* @param daoOperator address of daoOperator
* @return boolean, true if can be created
**/
function validateGenericProposalCreation(
IVotingPowerStrategy strategy,
address creator,
uint256 startTime,
uint256 endTime,
string[] calldata options,
address daoOperator
)
external view override returns (bool)
{
strategy;
creator;
startTime;
endTime;
options;
daoOperator;
return isCreationAllowed;
}
/**
* @dev Called to validate the cancellation of a proposal
* @param governance governance contract to fetch proposals from
* @param proposalId Id of the generic proposal
* @param user entity initiating the cancellation
* @return boolean, true if can be cancelled
**/
function validateProposalCancellation(
IKyberGovernance governance,
uint256 proposalId,
address user
)
external view override returns (bool)
{
governance;
proposalId;
user;
return isCancellationAllowed;
}
/**
* @dev Returns whether a binary proposal passed or not
* @param governance governance contract to fetch proposals from
* @param proposalId Id of the proposal to set
* @return true if proposal passed
**/
function isBinaryProposalPassed(
IKyberGovernance governance,
uint256 proposalId
)
external view override returns (bool)
{
governance;
proposalId;
return isProposalPassed;
}
/**
* @dev Check whether a proposal has reached quorum
* @param governance governance contract to fetch proposals from
* @param proposalId Id of the proposal to verify
* @return voting power needed for a proposal to pass
**/
function isQuorumValid(
IKyberGovernance governance,
uint256 proposalId
)
external view override returns (bool)
{
governance;
proposalId;
return isPassedMinQuorum;
}
/**
* @dev Check whether a proposal has enough extra FOR-votes than AGAINST-votes
* @param governance governance contract to fetch proposals from
* @param proposalId Id of the proposal to verify
* @return true if enough For-Votes
**/
function isVoteDifferentialValid(
IKyberGovernance governance,
uint256 proposalId
)
external view override returns (bool)
{
governance;
proposalId;
return isPassedDifferentialCheck;
}
}
|
Check whether a proposal has reached quorum governance governance contract to fetch proposals from proposalId Id of the proposal to verify return voting power needed for a proposal to pass/
|
function isQuorumValid(
IKyberGovernance governance,
uint256 proposalId
)
external view override returns (bool)
{
governance;
proposalId;
return isPassedMinQuorum;
}
| 7,302,461 |
./full_match/80001/0xA1Fac4eAcAFEb2dd93FC99f9dF97057e950A2f29/sources/contracts/TokenVesting.sol
|
withdraw a specified amount from a lock. _amount is the ideal amount to be withdrawn. however, this amount might be slightly different in rebasing tokens due to the conversion to shares, then back into an amount _lockID the lockID of the lock to be withdrawn _amount amount of tokens to withdraw/ convert _amount to its representation in shares round _amount up to the nearest whole share if the amount of tokens specified does not translate to at least 1 share. dust clearance block, as mulDiv rounds down leaving one share stuck, clear all shares for dust amounts
|
function withdraw(uint256 _lockID, uint256 _amount) external nonReentrant {
TokenLock storage userLock = LOCKS[_lockID];
require(userLock.owner == msg.sender, "OWNER");
uint256 balance = IERC20(userLock.tokenAddress).balanceOf(address(this));
uint256 shareDebit = FullMath.mulDiv(
SHARES[userLock.tokenAddress],
_amount,
balance
);
if (shareDebit == 0 && _amount > 0) {
shareDebit++;
}
require(shareDebit > 0, "ZERO WITHDRAWL");
uint256 withdrawableShares = getWithdrawableShares(userLock.lockID);
if (shareDebit + 1 == withdrawableShares) {
if (
FullMath.mulDiv(
SHARES[userLock.tokenAddress],
balance / SHARES[userLock.tokenAddress],
balance
) == 0
) {
shareDebit++;
}
}
require(withdrawableShares >= shareDebit, "AMOUNT");
userLock.sharesWithdrawn += shareDebit;
shareDebit,
balance,
SHARES[userLock.tokenAddress]
);
SHARES[userLock.tokenAddress] -= shareDebit;
TransferHelper.safeTransfer(
userLock.tokenAddress,
msg.sender,
amountInTokens
);
emit onWithdraw(userLock.tokenAddress, amountInTokens);
}
| 859,817 |
./partial_match/13337/0x00000000000001ad428e4906aE43D8F9852d0dD6/sources/contracts/lib/ConsiderationDecoder.sol
|
Converts an offer item into a received item, applying a given recipient. offerItem The offer item. recipient The recipient. return receivedItem The received item./
|
function _fromOfferItemToReceivedItemWithRecipient(
OfferItem memory offerItem,
address recipient
) internal pure returns (ReceivedItem memory receivedItem) {
assembly {
receivedItem := offerItem
mstore(add(receivedItem, ReceivedItem_recipient_offset), recipient)
}
}
| 16,951,619 |
./full_match/4/0xCb444455b6b51CD1aa99681E09C430Ef14CAB2d7/sources/Scrambles.sol
|
returns the core numbers for the token. the palette index range:0-2 followed by the 9 colour indexes range: 0-5. tokenId the tokenId to return numbers for./
|
function getCoreNumbers(uint256 tokenId) public view virtual override returns (string memory){
string memory coreNumbers = "";
if(!revealed)
{
return coreNumbers;
}
coreNumbers = string(abi.encodePacked(coreNumbers,getPaletteIndex(getSeed(tokenId)).toString()," "));
for(uint8 i = 1; i < 10; i++)
{
coreNumbers = string(abi.encodePacked(coreNumbers,(expandRandom(getSeed(tokenId),i) % 6).toString()," "));
}
return coreNumbers;
}
| 773,340 |
./full_match/80001/0x7AE4b5b4Bd41b9a20F885205bc7b27358da4f784/sources/contracts/GetVotedToEarn.sol
|
1 1 2 6 pA 8 pA 10 [0,1],[1,2] len 2 [0,1] len 1 distribute into different ranking by an identical value log into min med max lists (bool paid,) = payable(participantWhoWon.winner).call{value:sharedOfPrize}(""); if (paid) { participantWhoWon.winedPriceAmount = sharedOfPrize; } (bool paid,) = payable(participantWhoWon.winner).call{value:evenShare}(""); if (paid) { participantWhoWon.winedPriceAmount = evenShare; } (bool paid,) = payable(ad).call{value:price/2}(""); wont be able to send in split here
|
for (uint u=0;u<countOfUniqueWinningVote;u++) {
for (uint kk=countOfUniqueWinningVote;kk<countOfUniqueWinningVote*100;kk++){
indexArr[kk] = 100000000000000000000000000000000;
}
if (indexArr.length >= 1 && participantAmount > 1) {
for (uint x=indexArr[indexArr.length-(indexArr.length-countOfUniqueWinningVote)-1]+1;x<participantAmount;x++) {
uint256 minValueIloc = 0;
uint256[] memory finalArr = new uint256[](countOfUniqueWinningVote*100);
if (indexArr.length > 1) {
for (uint y=1;y<indexArr.length;y++) {
if (allParticipants[indexArr[y]].collectedVote.length < allParticipants[indexArr[minValueIloc]].collectedVote.length) {
minValueIloc = y;
}
}
}
if (allParticipants[x].collectedVote.length>allParticipants[indexArr[minValueIloc]].collectedVote.length) {
uint256 counter = 0;
uint256[] memory otherwiseArrIndexList = new uint256[](countOfUniqueWinningVote*100);
uint256 otherwiseCounter = 0;
for (uint q=0;q<indexArr.length;q++){
if (allParticipants[x].collectedVote.length != allParticipants[indexArr[q]].collectedVote.length) {
newUniqueValue = 1;
}
}
for (uint g=0;g<indexArr.length;g++){
if (allParticipants[indexArr[g]].collectedVote.length==allParticipants[indexArr[minValueIloc]].collectedVote.length) {
counter++;
if (allParticipants[indexArr[g]].collectedVote.length != prevVoteVal) {
uniqueCounter++;
prevVoteVal = allParticipants[indexArr[g]].collectedVote.length;
}
if (otherwiseArrIndexList.length==1) {
otherwiseArrIndexList[0]=indexArr[g];
otherwiseArrIndexList[otherwiseArrIndexList.length]=indexArr[g];
}
otherwiseCounter++;
}
}
if (counter > 1) {
if (newUniqueValue + uniqueCounter > countOfUniqueWinningVote) {
uint256 leftCount = indexArr.length-counter;
uint256 start = 0;
while (start < leftCount) {
finalArr[start]=otherwiseArrIndexList[start];
start++;
}
finalArr=indexArr;
}
if (countOfUniqueWinningVote > 1) {
finalArr[finalArr.length]=x;
finalArr[0]=x;
}
if (minValueIloc+1 !=x) {
uint256 start = 0;
uint256 skip = 0;
while (start!=indexArr.length) {
if (newUniqueValue + uniqueCounter <= countOfUniqueWinningVote) {
finalArr[start]=indexArr[start];
start++;
if (skip < minValueIloc) {
finalArr[start]=indexArr[start];
start++;
finalArr[start]=indexArr[start+counter];
start++;
}
skip++;
if (start > indexArr.length-counter*2) {
break;
}
}
}
finalArr[finalArr.length]=x;
finalArr=indexArr;
finalArr[minValueIloc]=x;
}
}
}
else if (allParticipants[x].collectedVote.length==allParticipants[minValueIloc].collectedVote.length) {
uint256 counterElseIf = 0;
for (uint n=0;n<indexArr.length;n++){
if (allParticipants[indexArr[n]].collectedVote.length==allParticipants[indexArr[minValueIloc]].collectedVote.length) {
counterElseIf++;
}
}
if (indexArr.length+1>countOfUniqueWinningVote) {
if (counterElseIf >= 1) {
finalArr=indexArr;
finalArr[finalArr.length]=x;
}
}
}
indexArr=finalArr;
}
}
uint256[] memory minVoteValueIndexList = new uint256[](indexArr.length);
uint256[] memory medVoteValueIndexList = new uint256[](indexArr.length);
uint256[] memory maxVoteValueIndexList = new uint256[](indexArr.length);
if (indexArr.length > 1) {
uint256 prevMinVal = allParticipants[indexArr[0]].collectedVote.length;
uint256 prevMedVal = 0;
prevMedVal=allParticipants[indexArr[0]].collectedVote.length;
uint256 prevMaxVal = allParticipants[indexArr[indexArr.length-1]].collectedVote.length;
for (uint b=1;b<indexArr.length;b++){
if (allParticipants[indexArr[b]].collectedVote.length<prevMinVal) {
prevMinVal=allParticipants[indexArr[b]].collectedVote.length;
}
}
for (uint a=0;a<indexArr.length-1;a++){
if (allParticipants[indexArr[a]].collectedVote.length>prevMaxVal) {
prevMaxVal=allParticipants[indexArr[a]].collectedVote.length;
}
}
for (uint l=0;l<indexArr.length;l++){
if (allParticipants[indexArr[l]].collectedVote.length!=prevMaxVal) {
if (allParticipants[indexArr[l]].collectedVote.length!=prevMinVal) {
prevMedVal=allParticipants[indexArr[l]].collectedVote.length;
}
}
}
for (uint ef=0;ef<indexArr.length;ef++){
if (allParticipants[indexArr[ef]].collectedVote.length==prevMinVal) {
if (minVoteValueIndexList.length==0) {
minVoteValueIndexList[0]=indexArr[ef];
minVoteValueIndexList[minVoteValueIndexList.length]=indexArr[ef];
}
}
}
for (uint ac=0;ac<indexArr.length;ac++){
if (allParticipants[indexArr[ac]].collectedVote.length==prevMaxVal) {
if (maxVoteValueIndexList.length==0) {
maxVoteValueIndexList[0]=indexArr[ac];
maxVoteValueIndexList[maxVoteValueIndexList.length]=indexArr[ac];
}
}
}
if (countOfUniqueWinningVote == 3) {
for (uint hi=0;hi<indexArr.length;hi++){
if (allParticipants[indexArr[hi]].collectedVote.length!=prevMaxVal) {
if (allParticipants[indexArr[hi]].collectedVote.length!=prevMinVal) {
if (medVoteValueIndexList.length==1) {
medVoteValueIndexList[0]=indexArr[hi];
medVoteValueIndexList[medVoteValueIndexList.length]=indexArr[hi];
}
}
}
}
}
if (indexArr.length > 1) {
if (countOfUniqueWinningVote == 1) {
for (uint ui=0;ui<minVoteValueIndexList.length;ui++) {
Winner storage participantWhoWon = winners[winnerAmount];
participantWhoWon.winner = allParticipants[minVoteValueIndexList[ui]].workCreator;
winnerAmount++;
uint256 sharedOfPrize = totalPrize/indexArr.length;
participantWhoWon.winedPriceAmount = sharedOfPrize;
participantWhoWon.contestId = contest.contestId;
contest.winner.push(participantWhoWon);
}
for (uint st=0;st<minVoteValueIndexList.length;st++) {
Winner storage participantWhoWon = winners[winnerAmount];
participantWhoWon.winner = allParticipants[minVoteValueIndexList[st]].workCreator;
winnerAmount++;
participantWhoWon.contestId = contest.contestId;
uint256 sharedOfPrize = totalPrize*(indexArr.length-1)/(indexArr.length*countOfUniqueWinningVote);
uint256 evenShare = sharedOfPrize/minVoteValueIndexList.length;
participantWhoWon.winedPriceAmount = evenShare;
contest.winner.push(participantWhoWon);
}
for (uint xy=0;xy<maxVoteValueIndexList.length;xy++) {
Winner storage participantWhoWon = winners[winnerAmount];
participantWhoWon.winner = allParticipants[maxVoteValueIndexList[xy]].workCreator;
winnerAmount++;
participantWhoWon.contestId = contest.contestId;
uint256 sharedOfPrize = totalPrize*(indexArr.length+1)/(indexArr.length*countOfUniqueWinningVote);
uint256 evenShare = sharedOfPrize/maxVoteValueIndexList.length;
participantWhoWon.winedPriceAmount = evenShare;
contest.winner.push(participantWhoWon);
}
for (uint jk=0;jk<minVoteValueIndexList.length;jk++) {
Winner storage participantWhoWon = winners[winnerAmount];
participantWhoWon.winner = allParticipants[minVoteValueIndexList[jk]].workCreator;
winnerAmount++;
participantWhoWon.contestId = contest.contestId;
uint256 sharedOfPrize = totalPrize*(indexArr.length-1)/(indexArr.length*countOfUniqueWinningVote);
uint256 evenShare = sharedOfPrize/minVoteValueIndexList.length;
participantWhoWon.winedPriceAmount = evenShare;
contest.winner.push(participantWhoWon);
}
for (uint pq=0;pq<maxVoteValueIndexList.length;pq++) {
Winner storage participantWhoWon = winners[winnerAmount];
participantWhoWon.winner = allParticipants[maxVoteValueIndexList[pq]].workCreator;
winnerAmount++;
participantWhoWon.contestId = contest.contestId;
uint256 sharedOfPrize = totalPrize*(indexArr.length+1)/(indexArr.length*countOfUniqueWinningVote);
uint256 evenShare = sharedOfPrize/maxVoteValueIndexList.length;
participantWhoWon.winedPriceAmount = evenShare;
contest.winner.push(participantWhoWon);
}
for (uint cd=0;cd<medVoteValueIndexList.length;cd++) {
Winner storage participantWhoWon = winners[winnerAmount];
participantWhoWon.winner = allParticipants[medVoteValueIndexList[cd]].workCreator;
winnerAmount++;
participantWhoWon.contestId = contest.contestId;
uint256 sharedOfPrize = totalPrize*(indexArr.length)/(indexArr.length*countOfUniqueWinningVote);
uint256 evenShare = sharedOfPrize/medVoteValueIndexList.length;
participantWhoWon.winedPriceAmount = evenShare;
contest.winner.push(participantWhoWon);
}
}
Winner storage participantWhoWon = winners[winnerAmount];
participantWhoWon.winner = allParticipants[indexArr[0]].workCreator;
winnerAmount++;
participantWhoWon.contestId = contest.contestId;
participantWhoWon.winedPriceAmount = totalPrize;
contest.winner.push(participantWhoWon);
return winnerAmount-indexArr.length;
}
function sendMoneyToOneWinner(address _winnerAddress) public payable {
if (paid) {
}
}
function sendMOne(address ad) public payable {
uint256 price = msg.value;
if (paid) {
}
}
function getIndexArr() public pure returns (uint256[] memory) {
uint256[] memory indexArr = new uint256[](1*10);
for (uint u=0;u<3;u++) {
}
return indexArr;
}
function getAllContests() public view returns (Contest[] memory) {
Contest[] memory allContests = new Contest[](contestAmount);
for (uint k=0;k<contestAmount;k++){
Contest storage individualContest = contests[k];
allContests[k]=individualContest;
}
return allContests;
}
Contest storage contest = contests[_contestId];
require(tx.origin==msg.sender,"only the contest creator address can call this func");
return contest.contestCreator;
}
Contest storage contest = contests[_contestId];
| 5,627,031 |
./full_match/5/0x66b1C6CC589d5bA470F348bbe81613269e1EC9A7/sources/solidity/contracts/DataFeedKeeper.sol
|
@inheritdoc IDataFeedKeeper TODO: if (whitelistedPools[_chainId][_poolSalt])?
|
function workable(bytes32 _poolSalt) public view returns (bool _isWorkable) {
(, uint32 _lastBlockTimestampObserved, , ) = dataFeed.lastPoolStateObserved(_poolSalt);
return block.timestamp >= _lastBlockTimestampObserved + jobCooldown;
}
| 1,871,685 |
./partial_match/1/0x0A69f09Da7951A61688f1C1B8baef55817b8D27d/sources/LiquidityFarming.sol
|
View function to see pending Spdrs on frontend.
|
function pendingReward(uint256 _poolId, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_poolId];
UserInfo storage user = userInfo[_poolId][_user];
uint256 accSpdrPerShare = pool.accSpdrPerShare;
uint256 poolBalance = pool.token.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && poolBalance > 0) {
uint256 rewards = getPoolReward(pool.lastRewardBlock, block.number, pool.spdrPerBlock);
accSpdrPerShare = accSpdrPerShare.add(rewards.mul(UNITS).div(poolBalance));
}
uint256 pending = user.amount.mul(accSpdrPerShare).div(UNITS).sub(user.rewardDebt);
return pending;
}
| 9,230,492 |
pragma solidity ^0.4.18;
library StringUtils {
/**
* @dev Checks if the passed string is not empty.
*/
function isNotEmpty(
string memory _str)
pure
internal
returns (bool)
{
bytes memory strBytes = bytes(_str);
return strBytes.length > 0;
}
/**
* @dev Checks if the passed string is empty.
*/
function isEmpty(
string memory _str)
pure
internal
returns (bool)
{
bytes memory strBytes = bytes(_str);
return strBytes.length == 0;
}
/**
* @dev Gets the hash of the string.
*/
function getHash(
string storage _str)
pure
internal
returns (bytes32)
{
return keccak256(_str);
}
/**
* @dev Gets the hash of an empty string.
*/
function getEmptyStringHash()
pure
internal
returns (bytes32)
{
return keccak256("");
}
}
|
Checks if the passed string is empty./
|
function isEmpty(
string memory _str)
pure
internal
returns (bool)
{
bytes memory strBytes = bytes(_str);
return strBytes.length == 0;
}
| 12,639,695 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
interface IBrincGovToken is IERC20Upgradeable {
function mint(address _to, uint256 _amount) external;
function mintToTreasury(uint256 _amount) external;
function getTreasuryOwner() external view returns (address);
}
interface IStakedBrincGovToken {
function mint(address _to, uint256 _amount) external;
function burnFrom(address _to, uint256 _amount) external;
}
// BrincStaking is the contract in which the Brinc token can be staked to earn
// Brinc governance tokens as rewards.
//
// Note that it's ownable and the owner wields tremendous power. Staking will
// governable in the future with the Brinc Governance token.
contract BrincStaking is OwnableUpgradeable {
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
using SafeERC20Upgradeable for IBrincGovToken;
// Stake mode
enum StakeMode {MODE1, MODE2, MODE3, MODE4, MODE5, MODE6}
// Info of each user.
struct UserInfo {
uint256 brcStakedAmount; // Amount of BRC tokens the user will stake.
uint256 gBrcStakedAmount; // Amount of gBRC tokens the user will stake.
uint256 blockNumber; // Stake block number.
uint256 rewardDebt; // Receivable reward. See explanation below.
StakeMode mode; // Stake mode
// We do some fancy math here. Basically, any point in time, the amount of govBrinc tokens
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.brcStakedAmount * accGovBrincPerShare) - user.rewardDebt
// rewardDebt = staked rewards for a user
// Whenever a user deposits or withdraws LP tokens to a pool. The following happens:
// 1. The pool's `accGovBrincPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
uint256 supply; // Weighted balance of Brinc tokens in the pool
uint256 lockBlockCount; // Lock block count
uint256 weight; // Weight for the pool
uint256 accGovBrincPerShare; // Accumulated govBrinc tokens per share, times 1e12. See below.
bool brcOnly;
}
// Last block number that govBrinc token distribution occurs.
uint256 lastRewardBlock;
// The Brinc TOKEN!
IERC20Upgradeable public brincToken;
// The governance Brinc TOKEN!
IBrincGovToken public govBrincToken;
// The staked governance Brinc TOKEN!
IStakedBrincGovToken public stakedGovBrincToken;
// govBrinc tokens created per block.
uint256 public govBrincPerBlock;
// Info of each pool.
mapping(StakeMode => PoolInfo) public poolInfo;
// Info of each user that stakes LP tokens.
mapping(address => UserInfo[]) public userInfo;
// ratioBrcToGov is the ratio of Brinc to govBrinc tokens needed to stake
uint256 public ratioBrcToGov;
// gBrcStakeAmount = brc * ratio / 1e10
// treasuryRewardBalance is the number of tokens awarded to the treasury address
// this is implemented this way so that the treasury address will be responsible for paying for the minting of rewards.
uint256 public treasuryRewardBalance;
// paused indicates whether staking is paused.
// when paused, the staking pools will not update, nor will any gov tokens be minted.
bool public paused;
// pausedBlock is the block number that pause was started.
// 0 if not paused.
uint256 public pausedBlock;
event Deposit(address indexed user, uint256 amount, StakeMode mode);
event Withdraw(address indexed user, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 amount);
event TreasuryMint(uint256 amount);
event LockBlockCountChanged(
StakeMode mode,
uint256 oldLockBlockCount,
uint256 newLockBlockCount
);
event WeightChanged(
StakeMode mode,
uint256 oldWeight,
uint256 newWeight
);
event GovBrincPerBlockChanged(
uint256 oldGovBrincPerBlock,
uint256 newGovBrincPerBlock
);
event RatioBrcToGovChanged(
uint256 oldRatioBrcToGov,
uint256 newRatioBrcToGov
);
event Paused();
event Resumed();
function initialize(
IERC20Upgradeable _brincToken,
IBrincGovToken _brincGovToken,
IStakedBrincGovToken _stakedGovBrincToken,
uint256 _govBrincPerBlock,
uint256 _ratioBrcToGov
) initializer public {
brincToken = _brincToken;
govBrincToken = _brincGovToken;
stakedGovBrincToken = _stakedGovBrincToken;
govBrincPerBlock = _govBrincPerBlock;
lastRewardBlock = block.number;
ratioBrcToGov = _ratioBrcToGov;
paused = false;
pausedBlock = 0;
poolInfo[StakeMode.MODE1] = PoolInfo({
supply: 0,
lockBlockCount: uint256(199384), // 30 days in block count. 1 block = 13 seconds
weight: 10,
accGovBrincPerShare: 0,
// represents the reward amount for each brinc token in the pool
brcOnly: true
});
poolInfo[StakeMode.MODE2] = PoolInfo({
supply: 0,
lockBlockCount: uint256(398769), // 60 days in block count. 1 block = 13 seconds
weight: 15,
accGovBrincPerShare: 0,
brcOnly: true
});
poolInfo[StakeMode.MODE3] = PoolInfo({
supply: 0,
lockBlockCount: uint256(598153), // 90 days in block count. 1 block = 13 seconds
weight: 25,
accGovBrincPerShare: 0,
brcOnly: true
});
poolInfo[StakeMode.MODE4] = PoolInfo({
supply: 0,
lockBlockCount: uint256(199384), // 30 days in block count. 1 block = 13 seconds
weight: 80,
accGovBrincPerShare: 0,
brcOnly: false
});
poolInfo[StakeMode.MODE5] = PoolInfo({
supply: 0,
lockBlockCount: uint256(398769), // 60 days in block count. 1 block = 13 seconds
weight: 140,
accGovBrincPerShare: 0,
brcOnly: false
});
poolInfo[StakeMode.MODE6] = PoolInfo({
supply: 0,
lockBlockCount: uint256(598153), // 90 days in block count. 1 block = 13 seconds
weight: 256,
accGovBrincPerShare: 0,
brcOnly: false
});
__Ownable_init();
}
modifier isNotPaused {
require(paused == false, "paused: operations are paused by admin");
_;
}
/**
* @dev pause the staking contract
* paused features:
* - deposit
* - withdraw
* - updating pools
*/
/// #if_succeeds {:msg "pause: paused is true"}
/// paused == true;
function pause() public onlyOwner {
paused = true;
pausedBlock = block.number;
emit Paused();
}
/**
* @dev resume the staking contract
* resumed features:
* - deposit
* - withdraw
* - updating pools
*/
/// #if_succeeds {:msg "resume: paused is false"}
/// paused == false;
function resume() public onlyOwner {
paused = false;
pausedBlock = 0;
emit Resumed();
}
/**
* @dev if paused or not
*
* @return paused
*/
/// #if_succeeds {:msg "isPaused: returns paused"}
/// $result == paused;
function isPaused() public view returns(bool) {
return paused;
}
/**
* @dev block that pause was called.
*
* @return pausedBlock
*/
/// #if_succeeds {:msg "getPausedBlock: returns PausedBlock"}
/// $result == pausedBlock;
function getPausedBlock() public view returns(uint256) {
return pausedBlock;
}
/**
* @dev last reward block that has been recorded
*
* @return lastRewardBlock
*/
/// #if_succeeds {:msg "getLastRewardBlock: returns lastRewardBlock"}
/// $result == lastRewardBlock;
function getLastRewardBlock() public view returns(uint256) {
return lastRewardBlock;
}
/**
* @dev address of the Brinc token contract
*
* @return Brinc token address
*/
/// #if_succeeds {:msg "getBrincTokenAddress: returns Brinc Token address"}
/// $result == address(brincToken);
function getBrincTokenAddress() public view returns(address) {
return address(brincToken);
}
/**
* @dev address of the Brinc Governance token contract
*
* @return Brinc Gov token address
*/
/// #if_succeeds {:msg "getGovTokenAddress: returns Brinc Gov token address"}
/// $result == address(govBrincToken);
function getGovTokenAddress() public view returns(address) {
return address(govBrincToken);
}
/**
* @dev the number of Gov tokens that can be issued per block
*
* @return Brinc Gov reward tokens per block
*/
/// #if_succeeds {:msg "getGovBrincPerBlock: returns Brinc Gov reward tokens per block"}
/// $result == govBrincPerBlock;
function getGovBrincPerBlock() public view returns(uint256) {
return govBrincPerBlock;
}
/**
* @dev The ratio of BRC to gBRC tokens
* The ratio dictates the amount of tokens of BRC and gBRC required for staking
*
* @return BRC to gBRC ratio required for staking
*/
/// #if_succeeds {:msg "getRatioBtoG: returns BRC to gBRC ratio required for staking"}
/// $result == ratioBrcToGov;
function getRatioBtoG() public view returns(uint256) {
return ratioBrcToGov;
}
/**
* @dev get specified pool supply
*
* @return pool's supply
*/
/// #if_succeeds {:msg "getPoolSupply: returns pool's supply"}
/// $result == poolInfo[_mode].supply;
function getPoolSupply(StakeMode _mode) public view returns(uint256) {
return poolInfo[_mode].supply;
}
/**
* @dev get specified pool lockBlockCount
*
* @return pool's lockBlockCount
*/
/// #if_succeeds {:msg "getPoolLockBlockCount: returns pool's lockBlockCount"}
/// $result == poolInfo[_mode].lockBlockCount;
function getPoolLockBlockCount(StakeMode _mode) public view returns(uint256) {
return poolInfo[_mode].lockBlockCount;
}
/**
* @dev get specified pool weight
*
* @return pool's weight
*/
/// #if_succeeds {:msg "getPoolWeight: returns pool's weight"}
/// $result == poolInfo[_mode].weight;
function getPoolWeight(StakeMode _mode) public view returns(uint256) {
return poolInfo[_mode].weight;
}
/**
* @dev get specified pool accGovBrincPerShare
*
* @return pool's accGovBrincPerShare
*/
/// #if_succeeds {:msg "getPoolAccGovBrincPerShare: returns pool's accGovBrincPerShare"}
/// $result == poolInfo[_mode].accGovBrincPerShare;
function getPoolAccGovBrincPerShare(StakeMode _mode) public view returns(uint256) {
return poolInfo[_mode].accGovBrincPerShare;
}
/**
* @dev get specified user information with correlating index
* _address will be required to have an active staking deposit.
*
* @return UserInfo
*/
function getUserInfo(address _address, uint256 _index) public view returns(UserInfo memory) {
require(userInfo[_address].length > 0, "getUserInfo: user has not made any stakes");
return userInfo[_address][_index];
}
/**
* @dev gets the number of stakes the user has made.
*
* @return UserStakeCount
*/
/// #if_succeeds {:msg "getStakeCount: returns user's active stakes"}
/// $result == userInfo[_msgSender()].length;
function getStakeCount() public view returns (uint256) {
return userInfo[_msgSender()].length;
}
/**
* @dev gets the total supply of all the rewards that .
* totalSupply = ( poolSupply1 * poolWeight1 ) + ( poolSupply2 * poolWeight2 ) + ( poolSupply3 * poolWeight3 )
*
* @return total supply of all pools
*/
/*
// there is an error: `throw e;`
// seems to be an issue with the scribble compiler
/// #if_succeeds {:msg "getTotalSupplyOfAllPools: returns total supply of all pool tokens"}
/// let pool1 := poolInfo[StakeMode.MODE1].supply.mul(poolInfo[StakeMode.MODE1].weight) in
/// let pool2 := poolInfo[StakeMode.MODE2].supply.mul(poolInfo[StakeMode.MODE2].weight) in
/// let pool3 := poolInfo[StakeMode.MODE3].supply.mul(poolInfo[StakeMode.MODE3].weight) in
/// let pool4 := poolInfo[StakeMode.MODE4].supply.mul(poolInfo[StakeMode.MODE4].weight) in
/// let pool5 := poolInfo[StakeMode.MODE5].supply.mul(poolInfo[StakeMode.MODE5].weight) in
/// let pool6 := poolInfo[StakeMode.MODE6].supply.mul(poolInfo[StakeMode.MODE6].weight) in
/// $result == pool1.add(pool2).add(pool3).add(pool4).add(pool5).add(pool6);
*/
function getTotalSupplyOfAllPools() private view returns (uint256) {
uint256 totalSupply;
totalSupply = totalSupply.add(
poolInfo[StakeMode.MODE1].supply.mul(poolInfo[StakeMode.MODE1].weight)
)
.add(
poolInfo[StakeMode.MODE2].supply.mul(poolInfo[StakeMode.MODE2].weight)
)
.add(
poolInfo[StakeMode.MODE3].supply.mul(poolInfo[StakeMode.MODE3].weight)
)
.add(
poolInfo[StakeMode.MODE4].supply.mul(poolInfo[StakeMode.MODE4].weight)
)
.add(
poolInfo[StakeMode.MODE5].supply.mul(poolInfo[StakeMode.MODE5].weight)
)
.add(
poolInfo[StakeMode.MODE6].supply.mul(poolInfo[StakeMode.MODE6].weight)
);
return totalSupply;
}
/**
* @dev gets the pending rewards of a user.]
* View function to see pending govBrinc on frontend.
*
* formula:
* reward = multiplier * govBrincPerBlock * pool.supply * pool.weight / totalSupply
*
* @return pending reward of a user
*/
/// #if_succeeds {:msg "pendingRewards: the pending rewards of a given user should be correct - case: maturity has not passed"}
/// let pendingReward, complete := $result in
/// userInfo[_user][_id].blockNumber > block.number ==>
/// pendingReward == 0 && complete == false;
/// #if_succeeds {:msg "pendingRewards: the pending rewards of a given user should be correct - case: maturity has passed with no pending rewards"}
/// let accGovBrincPerShare := old(poolInfo[userInfo[_user][_id].mode].accGovBrincPerShare) in
/// let totalSupply := old(getTotalSupplyOfAllPools()) in
/// let multiplier := old(block.number.sub(lastRewardBlock)) in
/// let govBrincReward := multiplier.mul(govBrincPerBlock).mul(poolInfo[userInfo[_user][_id].mode].supply).mul(poolInfo[userInfo[_user][_id].mode].weight).div(totalSupply) in
/// let scaled := govBrincReward.mul(1e12).div(poolInfo[userInfo[_user][_id].mode].supply) in
/// let updatedAccGovBrincPerShare := accGovBrincPerShare.add(scaled) in
/// let pendingReward, complete := $result in
/// (block.number > lastRewardBlock) && (poolInfo[userInfo[_user][_id].mode].supply != 0) ==> pendingReward == userInfo[_user][_id].brcStakedAmount.mul(updatedAccGovBrincPerShare).div(1e12).sub(userInfo[_user][_id].rewardDebt) && complete == true;
/// #if_succeeds {:msg "pendingRewards: the pending rewards of a given user should be correct - case: maturity has passed with pending rewards"}
/// let accGovBrincPerShare := poolInfo[userInfo[_user][_id].mode].accGovBrincPerShare in
/// let pendingReward, complete := $result in
/// (userInfo[_user][_id].blockNumber <= block.number) || (poolInfo[userInfo[_user][_id].mode].supply == 0) ==> pendingReward == userInfo[_user][_id].brcStakedAmount.mul(accGovBrincPerShare).div(1e12).sub(userInfo[_user][_id].rewardDebt) && complete == true;
function pendingRewards(address _user, uint256 _id) public view returns (uint256, bool) {
require(_id < userInfo[_user].length, "pendingRewards: invalid stake id");
UserInfo storage user = userInfo[_user][_id];
bool withdrawable; // false
// only withdrawable after the user's stake has passed maturity
if (block.number >= user.blockNumber) {
withdrawable = true;
}
PoolInfo storage pool = poolInfo[user.mode];
uint256 accGovBrincPerShare = pool.accGovBrincPerShare;
uint256 totalSupply = getTotalSupplyOfAllPools();
if (block.number > lastRewardBlock && pool.supply != 0) {
uint256 multiplier;
if (paused) {
multiplier = pausedBlock.sub(lastRewardBlock);
} else {
multiplier = block.number.sub(lastRewardBlock);
}
uint256 govBrincReward =
multiplier
.mul(govBrincPerBlock)
.mul(pool.supply) // supply is the number of staked Brinc tokens
.mul(pool.weight)
.div(totalSupply);
accGovBrincPerShare = accGovBrincPerShare.add(
govBrincReward.mul(1e12).div(pool.supply)
);
}
return
(user.brcStakedAmount.mul(accGovBrincPerShare).div(1e12).sub(user.rewardDebt), withdrawable);
}
function totalRewards(address _user) external view returns (uint256) {
UserInfo[] storage stakes = userInfo[_user];
uint256 total;
for (uint256 i = 0; i < stakes.length; i++) {
(uint256 reward, bool withdrawable) = pendingRewards(_user, i);
if (withdrawable) {
total = total.add(reward);
}
}
return total;
}
/**
* @dev updates the lockBlockCount required for stakers to lock up their stakes for.
* This will be taken as seconds but will be converted to blocks by multiplying by the average block time.
* This can only be called by the owner of the contract.
*
* lock up blocks = lock up time * 13 [avg. block time]
*
* @param _updatedLockBlockCount new lock up time
*/
/// #if_succeeds {:msg "updateLockBlockCount: the sender must be Owner"}
/// old(msg.sender == this.owner());
/// #if_succeeds {:msg "updateLockBlockCount: sets lockBlockCount correctly"}
/// poolInfo[_mode].lockBlockCount == _updatedLockBlockCount;
function updateLockBlockCount(StakeMode _mode, uint256 _updatedLockBlockCount) public onlyOwner {
PoolInfo storage pool = poolInfo[_mode];
uint256 oldLockBlockCount = pool.lockBlockCount;
pool.lockBlockCount = _updatedLockBlockCount;
emit LockBlockCountChanged(_mode, oldLockBlockCount, _updatedLockBlockCount);
}
/**
* @dev updates the weight of a specified pool. The mode specified will map to the period
*
* @param _mode period of the pool you wish to update
* @param _weight new weight
*/
/// #if_succeeds {:msg "updateWeight: the sender must be Owner"}
/// old(msg.sender == this.owner());
/// #if_succeeds {:msg "updateWeight: sets weight correctly"}
/// poolInfo[_mode].weight == _weight;
function updateWeight(StakeMode _mode, uint256 _weight) public onlyOwner {
massUpdatePools();
PoolInfo storage pool = poolInfo[_mode];
uint256 oldWeight = pool.weight;
pool.weight = _weight;
emit WeightChanged(_mode, oldWeight, _weight);
}
/**
* @dev updates the govBrincPerBlock reward amount that will be issued to the stakers. This can only be called by the owner of the contract.
*
* @param _updatedGovBrincPerBlock new reward amount
*/
/// #if_succeeds {:msg "updateGovBrincPerBlock: the sender must be Owner"}
/// old(msg.sender == this.owner());
/// #if_succeeds {:msg "updateGovBrincPerBlock: sets govBrincPerBlock correctly"}
/// govBrincPerBlock == _updatedGovBrincPerBlock;
function updateGovBrincPerBlock(uint256 _updatedGovBrincPerBlock) public onlyOwner {
massUpdatePools();
uint256 oldGovBrincPerBlock = govBrincPerBlock;
govBrincPerBlock = _updatedGovBrincPerBlock;
emit GovBrincPerBlockChanged(oldGovBrincPerBlock, govBrincPerBlock);
}
/**
* @dev updates the ratio of BRC to gBRC tokens required for staking.
*
* @param _updatedRatioBrcToGov new ratio of BRC to gBRC for staking
*/
/// #if_succeeds {:msg "updateRatioBrcToGov: the sender must be Owner"}
/// old(msg.sender == this.owner());
/// #if_succeeds {:msg "updateRatioBrcToGov: sets ratioBrcToGov correctly"}
/// ratioBrcToGov == _updatedRatioBrcToGov;
function updateRatioBrcToGov(uint256 _updatedRatioBrcToGov) public onlyOwner {
uint256 oldRatioBrcToGov = ratioBrcToGov;
ratioBrcToGov = _updatedRatioBrcToGov;
emit RatioBrcToGovChanged(oldRatioBrcToGov, ratioBrcToGov);
}
/**
* @dev staking owner will call to mint treasury tokens
* implemented this way so that users will not have to pay for the minting of the treasury tokens
* when pools are updated
* the `treasuryBalance` variable is used to keep track of the total number of tokens that the
* the treasury address will be able to mint at any given time.
*/
/// #if_succeeds {:msg "treasuryMint: the sender must be Owner"}
/// old(msg.sender == this.owner());
function treasuryMint() public onlyOwner {
require(treasuryRewardBalance > 0, "treasuryMint: not enough balance to mint");
uint256 balanceToMint;
balanceToMint = treasuryRewardBalance;
treasuryRewardBalance = 0;
govBrincToken.mintToTreasury(balanceToMint);
emit TreasuryMint(balanceToMint);
}
/**
* @dev updates all pool information.
*
* Note Update reward vairables for all pools. Be careful of gas spending!
*/
/// #if_succeeds {:msg "massUpdatePools: case totalSupply == 0"}
/// let multiplier := block.number - lastRewardBlock in
/// let unusedReward := multiplier.mul(govBrincPerBlock) in
/// getTotalSupplyOfAllPools() > 0 ==> treasuryRewardBalance == old(treasuryRewardBalance) + unusedReward;
/// #if_succeeds {:msg "massUpdatePools: updates lastRewardBlock"}
/// lastRewardBlock == block.number;
function massUpdatePools() internal isNotPaused {
uint256 totalSupply = getTotalSupplyOfAllPools();
if (totalSupply == 0) {
if (block.number > lastRewardBlock) {
uint256 multiplier = block.number.sub(lastRewardBlock);
uint256 unusedReward = multiplier.mul(govBrincPerBlock);
treasuryRewardBalance = treasuryRewardBalance.add(unusedReward);
}
} else {
updatePool(StakeMode.MODE1);
updatePool(StakeMode.MODE2);
updatePool(StakeMode.MODE3);
updatePool(StakeMode.MODE4);
updatePool(StakeMode.MODE5);
updatePool(StakeMode.MODE6);
}
lastRewardBlock = block.number;
}
/**
* @dev update a given pool. This should be done every time a deposit or withdraw is made.
*
* Note Update reward variables of the given pool to be up-to-date.
*/
/// #if_succeeds {:msg "updatePool: updates pool's information and mint's reward"}
/// let totalSupply := getTotalSupplyOfAllPools() in
/// let multiplier := block.number.sub(lastRewardBlock) in
/// let govBrincReward := multiplier.mul(govBrincPerBlock).mul(poolInfo[mode].supply).mul(poolInfo[mode].weight).div(totalSupply) in
/// (block.number > lastRewardBlock) && (poolInfo[mode].supply != 0) ==>
/// govBrincToken.balanceOf(address(this)) == govBrincReward && poolInfo[mode].accGovBrincPerShare == poolInfo[mode].accGovBrincPerShare.add(govBrincReward.mul(1e12).div(poolInfo[mode].supply));
function updatePool(StakeMode mode) internal isNotPaused {
PoolInfo storage pool = poolInfo[mode];
if (block.number <= lastRewardBlock) {
return;
}
if (pool.supply == 0) {
return;
}
uint256 totalSupply = getTotalSupplyOfAllPools();
uint256 multiplier = block.number.sub(lastRewardBlock);
uint256 govBrincReward =
multiplier
.mul(govBrincPerBlock)
.mul(pool.supply)
.mul(pool.weight)
.div(totalSupply);
govBrincToken.mint(address(this), govBrincReward);
pool.accGovBrincPerShare = pool.accGovBrincPerShare.add(
govBrincReward.mul(1e12).div(pool.supply)
);
}
/**
* @dev a user deposits some Brinc token for a given period. The period will be determined based on the pools.
* Every time a user deposits any stake, the pool will be updated.
* The user will only be allowed to deposit Brinc tokens to stake if they deposit the equivalent amount in governance tokens.
*
* Note Deposit Brinc tokens to BrincStaking for govBrinc token allocation.
*/
/// #if_succeeds {:msg "deposit: deposit Brinc token amount is correct"}
/// poolInfo[_mode].brcOnly == true ==> brincToken.balanceOf(address(this)) == _amount && govBrincToken.balanceOf(address(this)) == old(govBrincToken.balanceOf(address(this)));
/// #if_succeeds {:msg "deposit: deposit Brinc Gov token amount is correct"}
/// poolInfo[_mode].brcOnly == false ==> brincToken.balanceOf(address(this)) == _amount && govBrincToken.balanceOf(address(this)) == _amount.mul(ratioBrcToGov).div(1e10);
/// #if_succeeds {:msg "deposit: successful deposit should update user information correctly"}
/// let depositNumber := getStakeCount().sub(1) in
/// depositNumber > 0 ==>
/// userInfo[msg.sender][depositNumber].brcStakedAmount == _amount && userInfo[msg.sender][depositNumber].blockNumber == block.number.add(poolInfo[_mode].lockBlockCount) && userInfo[msg.sender][depositNumber].rewardDebt == userInfo[msg.sender][depositNumber].brcStakedAmount.mul(poolInfo[_mode].accGovBrincPerShare).div(1e12) && userInfo[msg.sender][depositNumber].mode == _mode;
/// #if_succeeds {:msg "deposit: pool supply is updated correctly"}
/// let depositNumber := getStakeCount().sub(1) in
/// depositNumber > 0 ==>
/// poolInfo[_mode].supply == old(poolInfo[_mode].supply) + userInfo[msg.sender][depositNumber].brcStakedAmount;
/// #if_succeeds {:msg "deposit: userInfo array should increment by one"}
/// userInfo[msg.sender].length == old(userInfo[msg.sender].length) + 1;
function deposit(uint256 _amount, StakeMode _mode) public {
require(_amount > 0, "deposit: invalid amount");
UserInfo memory user;
massUpdatePools();
PoolInfo storage pool = poolInfo[_mode];
brincToken.safeTransferFrom(msg.sender, address(this), _amount);
user.brcStakedAmount = _amount;
if (!pool.brcOnly) {
govBrincToken.safeTransferFrom(
msg.sender,
address(this),
_amount.mul(ratioBrcToGov).div(1e10)
);
user.gBrcStakedAmount = _amount.mul(ratioBrcToGov).div(1e10);
stakedGovBrincToken.mint(msg.sender, user.gBrcStakedAmount);
}
user.blockNumber = block.number.add(pool.lockBlockCount);
user.rewardDebt = user.brcStakedAmount.mul(pool.accGovBrincPerShare).div(1e12);
user.mode = _mode;
pool.supply = pool.supply.add(user.brcStakedAmount);
emit Deposit(msg.sender, _amount, _mode);
userInfo[msg.sender].push(user);
}
/**
* @dev a user withdraws their Brinc token that they have staked, including their rewards.
* Every time a user withdraws their stake, the pool will be updated.
*
* Note Withdraw Brinc tokens from BrincStaking.
*/
/// #if_succeeds {:msg "withdraw: token deducted from staking contract correctly"}
/// let depositNumber := getStakeCount().sub(1) in
/// let _amount := userInfo[msg.sender][depositNumber].brcStakedAmount in
/// depositNumber > 0 ==>
/// old(brincToken.balanceOf(address(this))) == brincToken.balanceOf(address(this)) - _amount;
/// #if_succeeds {:msg "withdraw: user's withdrawn Brinc token amount is correct"}
/// let depositNumber := getStakeCount().sub(1) in
/// let _amount := userInfo[msg.sender][depositNumber].brcStakedAmount in
/// depositNumber > 0 ==>
/// brincToken.balanceOf(msg.sender) == old(brincToken.balanceOf(msg.sender)) + _amount;
/// #if_succeeds {:msg "withdraw: user's withdrawn Brinc Gov reward amount is correct"}
/// let reward, complete := old(pendingRewards(msg.sender, userInfo[msg.sender].length - 1)) in
/// govBrincToken.balanceOf(msg.sender) == reward && complete == true;
/// #if_succeeds {:msg "withdraw: user information is updated correctly"}
/// let depositNumber := getStakeCount().sub(1) in
/// let _amount := userInfo[msg.sender][depositNumber].brcStakedAmount in
/// depositNumber > 0 ==>
/// userInfo[msg.sender][depositNumber].rewardDebt == userInfo[msg.sender][depositNumber].brcStakedAmount.mul(poolInfo[userInfo[msg.sender][depositNumber].mode].accGovBrincPerShare).div(1e12) && userInfo[msg.sender][depositNumber].mode == userInfo[msg.sender][depositNumber].mode;
/// #if_succeeds {:msg "withdraw: pool supply is updated correctly"}
/// let depositNumber := getStakeCount().sub(1) in
/// depositNumber > 0 ==>
/// poolInfo[userInfo[msg.sender][depositNumber].mode].supply == old(poolInfo[userInfo[msg.sender][depositNumber].mode].supply).sub(userInfo[msg.sender][depositNumber].brcStakedAmount);
function withdraw(uint256 _id) public {
require(_id < userInfo[msg.sender].length, "withdraw: invalid stake id");
UserInfo memory user = userInfo[msg.sender][_id];
require(user.brcStakedAmount > 0, "withdraw: nothing to withdraw");
require(user.blockNumber <= block.number, "withdraw: stake is still locked");
massUpdatePools();
PoolInfo storage pool = poolInfo[user.mode];
uint256 pending =
user.brcStakedAmount.mul(pool.accGovBrincPerShare).div(1e12).sub(user.rewardDebt);
safeGovBrincTransfer(msg.sender, pending + user.gBrcStakedAmount);
stakedGovBrincToken.burnFrom(msg.sender, user.gBrcStakedAmount);
uint256 _amount = user.brcStakedAmount;
brincToken.safeTransfer(msg.sender, _amount);
pool.supply = pool.supply.sub(_amount);
emit Withdraw(msg.sender, _amount);
_removeStake(msg.sender, _id);
}
/**
* @dev a user withdraws their Brinc token that they have staked, without caring their rewards.
* Only pool's supply will be updated.
*
* Note EmergencyWithdraw Brinc tokens from BrincStaking.
*/
function emergencyWithdraw(uint256 _id) public {
require(_id < userInfo[msg.sender].length, "emergencyWithdraw: invalid stake id");
UserInfo storage user = userInfo[msg.sender][_id];
require(user.brcStakedAmount > 0, "emergencyWithdraw: nothing to withdraw");
PoolInfo storage pool = poolInfo[user.mode];
safeGovBrincTransfer(msg.sender, user.gBrcStakedAmount);
stakedGovBrincToken.burnFrom(msg.sender, user.gBrcStakedAmount);
delete user.gBrcStakedAmount;
uint256 _amount = user.brcStakedAmount;
delete user.brcStakedAmount;
brincToken.safeTransfer(msg.sender, _amount);
pool.supply = pool.supply.sub(_amount);
emit EmergencyWithdraw(msg.sender, _amount);
_removeStake(msg.sender, _id);
}
function _removeStake(address _user, uint256 _id) internal {
userInfo[_user][_id] = userInfo[_user][userInfo[_user].length - 1];
userInfo[_user].pop();
}
/**
* @dev the safe transfer of the governance token rewards to the designated adress with the specified reward.
* Safe govBrinc transfer function, just in case if rounding error causes pool to not have enough govBrinc tokens.
*
* @param _to address to send Brinc Gov token rewards to
* @param _amount amount of Brinc Gov token rewards to send
*
* Note this will be only used internally inside the contract.
*/
/// #if_succeeds {:msg "safeGovBrincTransfer: transfer of Brinc Gov token is correct - case _amount > govBrincBal"}
/// let initGovBrincBal := old(govBrincToken.balanceOf(_to)) in
/// let govBrincBal := old(govBrincToken.balanceOf(address(this))) in
/// _amount > govBrincBal ==> govBrincToken.balanceOf(_to) == initGovBrincBal + govBrincBal;
/// #if_succeeds {:msg "safeGovBrincTransfer: transfer of Brinc Gov token is correct - case _amount < govBrincBal"}
/// let initGovBrincBal := old(govBrincToken.balanceOf(_to)) in
/// let govBrincBal := old(govBrincToken.balanceOf(address(this))) in
/// _amount <= govBrincBal ==> govBrincToken.balanceOf(_to) == initGovBrincBal + _amount;
function safeGovBrincTransfer(address _to, uint256 _amount) internal {
uint256 govBrincBal = govBrincToken.balanceOf(address(this));
if (_amount > govBrincBal) {
govBrincToken.transfer(_to, govBrincBal);
} else {
govBrincToken.transfer(_to, _amount);
}
}
}
// 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: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @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;
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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.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 SafeMathUpgradeable {
/**
* @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 "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
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.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: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
|
resume the staking contract resumed features: - deposit - withdraw - updating pools/ if_succeeds {:msg "resume: paused is false"} paused == false;
|
function resume() public onlyOwner {
paused = false;
pausedBlock = 0;
emit Resumed();
}
| 445,596 |
./full_match/3/0x632CfaE918Bb346252ee2e7995addFf429AA5D4c/sources/browser/TRDToken.sol
|
----------------- Now convert TRD and pay out in ETH-----------------enable/disable50000000000000000000.049500000000000000
|
function sellTRD(uint256 amountTRD) public returns (bool) {
if (!TRD2ETHRedemptionEnabled) {
revert("TRD2ETHRedemption not Enabled");
}
if (!tradingOpen) {
revert("Trading not Open");
}
if (ETHUSDrate == 0) {
revert("ETHUSDrate eq 0");
}
if (block.timestamp > ETHUSDgoodtilblock) {
revert("block timestamp gt ETHUSDgoodtilblock");
}
if (amountTRD > balanceOf(msg.sender) ) {
revert("more than you have or ever know");
}
if (ETHpendingCashoutA[msg.sender] != 0) {
revert("eth cashout pending.");
}
uint256 amountUSD = amountTRD * growthRate / GROWTH_FACTOR;
uint256 amountETH = amountUSD / ETHUSDrate * 100 ;
results = amountTRD;
address to = address(uint160(owner));
transfer(to, amountTRD);
ETHpendingCashoutA[msg.sender] = amountETH;
addressETHpendingCashoutA.push(msg.sender);
return true;
}
| 8,153,488 |
pragma solidity ^0.6.0;
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b != 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library ZeroCopySink {
/* @notice Convert boolean value into bytes
* @param b The boolean value
* @return Converted bytes array
*/
function WriteBool(bool b) internal pure returns (bytes memory) {
bytes memory buff;
assembly{
buff := mload(0x40)
mstore(buff, 1)
switch iszero(b)
case 1 {
mstore(add(buff, 0x20), shl(248, 0x00))
// mstore8(add(buff, 0x20), 0x00)
}
default {
mstore(add(buff, 0x20), shl(248, 0x01))
// mstore8(add(buff, 0x20), 0x01)
}
mstore(0x40, add(buff, 0x21))
}
return buff;
}
/* @notice Convert byte value into bytes
* @param b The byte value
* @return Converted bytes array
*/
function WriteByte(byte b) internal pure returns (bytes memory) {
return WriteUint8(uint8(b));
}
/* @notice Convert uint8 value into bytes
* @param v The uint8 value
* @return Converted bytes array
*/
function WriteUint8(uint8 v) internal pure returns (bytes memory) {
bytes memory buff;
assembly{
buff := mload(0x40)
mstore(buff, 1)
mstore(add(buff, 0x20), shl(248, v))
// mstore(add(buff, 0x20), byte(0x1f, v))
mstore(0x40, add(buff, 0x21))
}
return buff;
}
/* @notice Convert uint16 value into bytes
* @param v The uint16 value
* @return Converted bytes array
*/
function WriteUint16(uint16 v) internal pure returns (bytes memory) {
bytes memory buff;
assembly{
buff := mload(0x40)
let byteLen := 0x02
mstore(buff, byteLen)
for {
let mindex := 0x00
let vindex := 0x1f
} lt(mindex, byteLen) {
mindex := add(mindex, 0x01)
vindex := sub(vindex, 0x01)
}{
mstore8(add(add(buff, 0x20), mindex), byte(vindex, v))
}
mstore(0x40, add(buff, 0x22))
}
return buff;
}
/* @notice Convert uint32 value into bytes
* @param v The uint32 value
* @return Converted bytes array
*/
function WriteUint32(uint32 v) internal pure returns(bytes memory) {
bytes memory buff;
assembly{
buff := mload(0x40)
let byteLen := 0x04
mstore(buff, byteLen)
for {
let mindex := 0x00
let vindex := 0x1f
} lt(mindex, byteLen) {
mindex := add(mindex, 0x01)
vindex := sub(vindex, 0x01)
}{
mstore8(add(add(buff, 0x20), mindex), byte(vindex, v))
}
mstore(0x40, add(buff, 0x24))
}
return buff;
}
/* @notice Convert uint64 value into bytes
* @param v The uint64 value
* @return Converted bytes array
*/
function WriteUint64(uint64 v) internal pure returns(bytes memory) {
bytes memory buff;
assembly{
buff := mload(0x40)
let byteLen := 0x08
mstore(buff, byteLen)
for {
let mindex := 0x00
let vindex := 0x1f
} lt(mindex, byteLen) {
mindex := add(mindex, 0x01)
vindex := sub(vindex, 0x01)
}{
mstore8(add(add(buff, 0x20), mindex), byte(vindex, v))
}
mstore(0x40, add(buff, 0x28))
}
return buff;
}
/* @notice Convert limited uint256 value into bytes
* @param v The uint256 value
* @return Converted bytes array
*/
function WriteUint255(uint256 v) internal pure returns (bytes memory) {
require(v <= 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, "Value exceeds uint255 range");
bytes memory buff;
assembly{
buff := mload(0x40)
let byteLen := 0x20
mstore(buff, byteLen)
for {
let mindex := 0x00
let vindex := 0x1f
} lt(mindex, byteLen) {
mindex := add(mindex, 0x01)
vindex := sub(vindex, 0x01)
}{
mstore8(add(add(buff, 0x20), mindex), byte(vindex, v))
}
mstore(0x40, add(buff, 0x40))
}
return buff;
}
/* @notice Encode bytes format data into bytes
* @param data The bytes array data
* @return Encoded bytes array
*/
function WriteVarBytes(bytes memory data) internal pure returns (bytes memory) {
uint64 l = uint64(data.length);
return abi.encodePacked(WriteVarUint(l), data);
}
function WriteVarUint(uint64 v) internal pure returns (bytes memory) {
if (v < 0xFD){
return WriteUint8(uint8(v));
} else if (v <= 0xFFFF) {
return abi.encodePacked(WriteByte(0xFD), WriteUint16(uint16(v)));
} else if (v <= 0xFFFFFFFF) {
return abi.encodePacked(WriteByte(0xFE), WriteUint32(uint32(v)));
} else {
return abi.encodePacked(WriteByte(0xFF), WriteUint64(uint64(v)));
}
}
}
library ZeroCopySource {
/* @notice Read next byte as boolean type starting at offset from buff
* @param buff Source bytes array
* @param offset The position from where we read the boolean value
* @return The the read boolean value and new offset
*/
function NextBool(bytes memory buff, uint256 offset) internal pure returns(bool, uint256) {
require(offset + 1 <= buff.length && offset < offset + 1, "Offset exceeds limit");
// byte === bytes1
byte v;
assembly{
v := mload(add(add(buff, 0x20), offset))
}
bool value;
if (v == 0x01) {
value = true;
} else if (v == 0x00) {
value = false;
} else {
revert("NextBool value error");
}
return (value, offset + 1);
}
/* @notice Read next byte starting at offset from buff
* @param buff Source bytes array
* @param offset The position from where we read the byte value
* @return The read byte value and new offset
*/
function NextByte(bytes memory buff, uint256 offset) internal pure returns (byte, uint256) {
require(offset + 1 <= buff.length && offset < offset + 1, "NextByte, Offset exceeds maximum");
byte v;
assembly{
v := mload(add(add(buff, 0x20), offset))
}
return (v, offset + 1);
}
/* @notice Read next byte as uint8 starting at offset from buff
* @param buff Source bytes array
* @param offset The position from where we read the byte value
* @return The read uint8 value and new offset
*/
function NextUint8(bytes memory buff, uint256 offset) internal pure returns (uint8, uint256) {
require(offset + 1 <= buff.length && offset < offset + 1, "NextUint8, Offset exceeds maximum");
uint8 v;
assembly{
let tmpbytes := mload(0x40)
let bvalue := mload(add(add(buff, 0x20), offset))
mstore8(tmpbytes, byte(0, bvalue))
mstore(0x40, add(tmpbytes, 0x01))
v := mload(sub(tmpbytes, 0x1f))
}
return (v, offset + 1);
}
/* @notice Read next two bytes as uint16 type starting from offset
* @param buff Source bytes array
* @param offset The position from where we read the uint16 value
* @return The read uint16 value and updated offset
*/
function NextUint16(bytes memory buff, uint256 offset) internal pure returns (uint16, uint256) {
require(offset + 2 <= buff.length && offset < offset + 2, "NextUint16, offset exceeds maximum");
uint16 v;
assembly {
let tmpbytes := mload(0x40)
let bvalue := mload(add(add(buff, 0x20), offset))
mstore8(tmpbytes, byte(0x01, bvalue))
mstore8(add(tmpbytes, 0x01), byte(0, bvalue))
mstore(0x40, add(tmpbytes, 0x02))
v := mload(sub(tmpbytes, 0x1e))
}
return (v, offset + 2);
}
/* @notice Read next four bytes as uint32 type starting from offset
* @param buff Source bytes array
* @param offset The position from where we read the uint32 value
* @return The read uint32 value and updated offset
*/
function NextUint32(bytes memory buff, uint256 offset) internal pure returns (uint32, uint256) {
require(offset + 4 <= buff.length && offset < offset + 4, "NextUint32, offset exceeds maximum");
uint32 v;
assembly {
let tmpbytes := mload(0x40)
let byteLen := 0x04
for {
let tindex := 0x00
let bindex := sub(byteLen, 0x01)
let bvalue := mload(add(add(buff, 0x20), offset))
} lt(tindex, byteLen) {
tindex := add(tindex, 0x01)
bindex := sub(bindex, 0x01)
}{
mstore8(add(tmpbytes, tindex), byte(bindex, bvalue))
}
mstore(0x40, add(tmpbytes, byteLen))
v := mload(sub(tmpbytes, sub(0x20, byteLen)))
}
return (v, offset + 4);
}
/* @notice Read next eight bytes as uint64 type starting from offset
* @param buff Source bytes array
* @param offset The position from where we read the uint64 value
* @return The read uint64 value and updated offset
*/
function NextUint64(bytes memory buff, uint256 offset) internal pure returns (uint64, uint256) {
require(offset + 8 <= buff.length && offset < offset + 8, "NextUint64, offset exceeds maximum");
uint64 v;
assembly {
let tmpbytes := mload(0x40)
let byteLen := 0x08
for {
let tindex := 0x00
let bindex := sub(byteLen, 0x01)
let bvalue := mload(add(add(buff, 0x20), offset))
} lt(tindex, byteLen) {
tindex := add(tindex, 0x01)
bindex := sub(bindex, 0x01)
}{
mstore8(add(tmpbytes, tindex), byte(bindex, bvalue))
}
mstore(0x40, add(tmpbytes, byteLen))
v := mload(sub(tmpbytes, sub(0x20, byteLen)))
}
return (v, offset + 8);
}
/* @notice Read next 32 bytes as uint256 type starting from offset,
there are limits considering the numerical limits in multi-chain
* @param buff Source bytes array
* @param offset The position from where we read the uint256 value
* @return The read uint256 value and updated offset
*/
function NextUint255(bytes memory buff, uint256 offset) internal pure returns (uint256, uint256) {
require(offset + 32 <= buff.length && offset < offset + 32, "NextUint255, offset exceeds maximum");
uint256 v;
assembly {
let tmpbytes := mload(0x40)
let byteLen := 0x20
for {
let tindex := 0x00
let bindex := sub(byteLen, 0x01)
let bvalue := mload(add(add(buff, 0x20), offset))
} lt(tindex, byteLen) {
tindex := add(tindex, 0x01)
bindex := sub(bindex, 0x01)
}{
mstore8(add(tmpbytes, tindex), byte(bindex, bvalue))
}
mstore(0x40, add(tmpbytes, byteLen))
v := mload(tmpbytes)
}
require(v <= 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, "Value exceeds the range");
return (v, offset + 32);
}
/* @notice Read next variable bytes starting from offset,
the decoding rule coming from multi-chain
* @param buff Source bytes array
* @param offset The position from where we read the bytes value
* @return The read variable bytes array value and updated offset
*/
function NextVarBytes(bytes memory buff, uint256 offset) internal pure returns(bytes memory, uint256) {
uint len;
(len, offset) = NextVarUint(buff, offset);
require(offset + len <= buff.length && offset < offset + len, "NextVarBytes, offset exceeds maximum");
bytes memory tempBytes;
assembly{
switch iszero(len)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(len, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, len)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(buff, lengthmod), mul(0x20, iszero(lengthmod))), offset)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, len)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
mstore(0x40, add(tempBytes, 0x20))
}
}
return (tempBytes, offset + len);
}
/* @notice Read next 32 bytes starting from offset,
* @param buff Source bytes array
* @param offset The position from where we read the bytes value
* @return The read bytes32 value and updated offset
*/
function NextHash(bytes memory buff, uint256 offset) internal pure returns (bytes32 , uint256) {
require(offset + 32 <= buff.length && offset < offset + 32, "NextHash, offset exceeds maximum");
bytes32 v;
assembly {
v := mload(add(buff, add(offset, 0x20)))
}
return (v, offset + 32);
}
/* @notice Read next 20 bytes starting from offset,
* @param buff Source bytes array
* @param offset The position from where we read the bytes value
* @return The read bytes20 value and updated offset
*/
function NextBytes20(bytes memory buff, uint256 offset) internal pure returns (bytes20 , uint256) {
require(offset + 20 <= buff.length && offset < offset + 20, "NextBytes20, offset exceeds maximum");
bytes20 v;
assembly {
v := mload(add(buff, add(offset, 0x20)))
}
return (v, offset + 20);
}
function NextVarUint(bytes memory buff, uint256 offset) internal pure returns(uint, uint256) {
byte v;
(v, offset) = NextByte(buff, offset);
uint value;
if (v == 0xFD) {
// return NextUint16(buff, offset);
(value, offset) = NextUint16(buff, offset);
require(value >= 0xFD && value <= 0xFFFF, "NextUint16, value outside range");
return (value, offset);
} else if (v == 0xFE) {
// return NextUint32(buff, offset);
(value, offset) = NextUint32(buff, offset);
require(value > 0xFFFF && value <= 0xFFFFFFFF, "NextVarUint, value outside range");
return (value, offset);
} else if (v == 0xFF) {
// return NextUint64(buff, offset);
(value, offset) = NextUint64(buff, offset);
require(value > 0xFFFFFFFF, "NextVarUint, value outside range");
return (value, offset);
} else{
// return (uint8(v), offset);
value = uint8(v);
require(value < 0xFD, "NextVarUint, value outside range");
return (value, offset);
}
}
}
library Utils {
/* @notice Convert the bytes array to bytes32 type, the bytes array length must be 32
* @param _bs Source bytes array
* @return bytes32
*/
function bytesToBytes32(bytes memory _bs) internal pure returns (bytes32 value) {
require(_bs.length == 32, "bytes length is not 32.");
assembly {
// load 32 bytes from memory starting from position _bs + 0x20 since the first 0x20 bytes stores _bs length
value := mload(add(_bs, 0x20))
}
}
/* @notice Convert bytes to uint256
* @param _b Source bytes should have length of 32
* @return uint256
*/
function bytesToUint256(bytes memory _bs) internal pure returns (uint256 value) {
require(_bs.length == 32, "bytes length is not 32.");
assembly {
// load 32 bytes from memory starting from position _bs + 32
value := mload(add(_bs, 0x20))
}
require(value <= 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, "Value exceeds the range");
}
/* @notice Convert uint256 to bytes
* @param _b uint256 that needs to be converted
* @return bytes
*/
function uint256ToBytes(uint256 _value) internal pure returns (bytes memory bs) {
require(_value <= 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, "Value exceeds the range");
assembly {
// Get a location of some free memory and store it in result as
// Solidity does for memory variables.
bs := mload(0x40)
// Put 0x20 at the first word, the length of bytes for uint256 value
mstore(bs, 0x20)
//In the next word, put value in bytes format to the next 32 bytes
mstore(add(bs, 0x20), _value)
// Update the free-memory pointer by padding our last write location to 32 bytes
mstore(0x40, add(bs, 0x40))
}
}
/* @notice Convert bytes to address
* @param _bs Source bytes: bytes length must be 20
* @return Converted address from source bytes
*/
function bytesToAddress(bytes memory _bs) internal pure returns (address addr)
{
require(_bs.length == 20, "bytes length does not match address");
assembly {
// for _bs, first word store _bs.length, second word store _bs.value
// load 32 bytes from mem[_bs+20], convert it into Uint160, meaning we take last 20 bytes as addr (address).
addr := mload(add(_bs, 0x14))
}
}
/* @notice Convert address to bytes
* @param _addr Address need to be converted
* @return Converted bytes from address
*/
function addressToBytes(address _addr) internal pure returns (bytes memory bs){
assembly {
// Get a location of some free memory and store it in result as
// Solidity does for memory variables.
bs := mload(0x40)
// Put 20 (address byte length) at the first word, the length of bytes for uint256 value
mstore(bs, 0x14)
// logical shift left _a by 12 bytes, change _a from right-aligned to left-aligned
mstore(add(bs, 0x20), shl(96, _addr))
// Update the free-memory pointer by padding our last write location to 32 bytes
mstore(0x40, add(bs, 0x40))
}
}
/* @notice Do hash leaf as the multi-chain does
* @param _data Data in bytes format
* @return Hashed value in bytes32 format
*/
function hashLeaf(bytes memory _data) internal pure returns (bytes32 result) {
result = sha256(abi.encodePacked(byte(0x0), _data));
}
/* @notice Do hash children as the multi-chain does
* @param _l Left node
* @param _r Right node
* @return Hashed value in bytes32 format
*/
function hashChildren(bytes32 _l, bytes32 _r) internal pure returns (bytes32 result) {
result = sha256(abi.encodePacked(bytes1(0x01), _l, _r));
}
/* @notice Compare if two bytes are equal, which are in storage and memory, seperately
Refer from https://github.com/summa-tx/bitcoin-spv/blob/master/solidity/contracts/BytesLib.sol#L368
* @param _preBytes The bytes stored in storage
* @param _postBytes The bytes stored in memory
* @return Bool type indicating if they are equal
*/
function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) {
bool success = true;
assembly {
// we know _preBytes_offset is 0
let fslot := sload(_preBytes_slot)
// Arrays of 31 bytes or less have an even value in their slot,
// while longer arrays have an odd value. The actual length is
// the slot divided by two for odd values, and the lowest order
// byte divided by two for even values.
// If the slot is even, bitwise and the slot with 255 and divide by
// two to get the length. If the slot is odd, bitwise and the slot
// with -1 and divide by two.
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
// if lengths don't match the arrays are not equal
switch eq(slength, mlength)
case 1 {
// fslot can contain both the length and contents of the array
// if slength < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
// slength != 0
if iszero(iszero(slength)) {
switch lt(slength, 32)
case 1 {
// blank the last byte which is the length
fslot := mul(div(fslot, 0x100), 0x100)
if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
// unsuccess:
success := 0
}
}
default {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
let sc := keccak256(0x0, 0x20)
let mc := add(_postBytes, 0x20)
let end := add(mc, mlength)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
for {} eq(add(lt(mc, end), cb), 2) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
if iszero(eq(sload(sc), mload(mc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
/* @notice Slice the _bytes from _start index till the result has length of _length
Refer from https://github.com/summa-tx/bitcoin-spv/blob/master/solidity/contracts/BytesLib.sol#L246
* @param _bytes The original bytes needs to be sliced
* @param _start The index of _bytes for the start of sliced bytes
* @param _length The index of _bytes for the end of sliced bytes
* @return The sliced bytes
*/
function slice(
bytes memory _bytes,
uint _start,
uint _length
)
internal
pure
returns (bytes memory)
{
require(_bytes.length >= (_start + _length));
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
// lengthmod <= _length % 32
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
/* @notice Check if the elements number of _signers within _keepers array is no less than _m
* @param _keepers The array consists of serveral address
* @param _signers Some specific addresses to be looked into
* @param _m The number requirement paramter
* @return True means containment, false meansdo do not contain.
*/
function containMAddresses(address[] memory _keepers, address[] memory _signers, uint _m) internal pure returns (bool){
uint m = 0;
for(uint i = 0; i < _signers.length; i++){
for (uint j = 0; j < _keepers.length; j++) {
if (_signers[i] == _keepers[j]) {
m++;
delete _keepers[j];
}
}
}
return m >= _m;
}
/* @notice TODO
* @param key
* @return
*/
function compressMCPubKey(bytes memory key) internal pure returns (bytes memory newkey) {
require(key.length >= 67, "key lenggh is too short");
newkey = slice(key, 0, 35);
if (uint8(key[66]) % 2 == 0){
newkey[2] = byte(0x02);
} else {
newkey[2] = byte(0x03);
}
return newkey;
}
/**
* @dev Returns true if `account` is a contract.
* Refer from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol#L18
*
* 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);
}
}
library SafeERC20 {
using SafeMath for uint256;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(Utils.isContract(address(token)), "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");
}
}
}
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Called to pause, triggers stopped state.
*/
function _pause() internal whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Called to unpause, returns to normal state.
*/
function _unpause() internal whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract ReentrancyGuard {
bool private _notEntered;
constructor () internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
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);
}
interface IEthCrossChainManager {
function crossChain(uint64 _toChainId, bytes calldata _toContract, bytes calldata _method, bytes calldata _txData) external returns (bool);
}
interface IEthCrossChainManagerProxy {
function getEthCrossChainManager() external view returns (address);
}
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
contract Swapper is Ownable, Pausable, ReentrancyGuard {
using SafeMath for uint;
using SafeERC20 for IERC20;
struct TxArgs {
uint amount;
uint minOut;
uint64 toPoolId;
uint64 toChainId;
bytes fromAssetHash;
bytes fromAddress;
bytes toAssetHash;
bytes toAddress;
}
address public WETH;
address public feeCollector;
address public lockProxyAddress;
address public managerProxyContract;
bytes public swapProxyHash;
uint64 public swapChainId;
uint64 public chainId;
mapping(bytes => mapping(uint64 => bool)) public assetInPool;
mapping(uint64 => address) public poolTokenMap;
event LockEvent(address fromAssetHash, address fromAddress, uint64 toChainId, bytes toAssetHash, bytes toAddress, uint256 amount);
event SwapEvent(address fromAssetHash, address fromAddress, uint64 toPoolId, uint64 toChainId, bytes toAssetHash, bytes toAddress, uint amount,uint fee, uint id);
event AddLiquidityEvent(address fromAssetHash, address fromAddress, uint64 toPoolId, uint64 toChainId, bytes toAssetHash, bytes toAddress, uint amount, uint fee, uint id);
event RemoveLiquidityEvent(address fromAssetHash, address fromAddress, uint64 toPoolId, uint64 toChainId, bytes toAssetHash, bytes toAddress, uint amount, uint fee, uint id);
constructor(address _owner, uint64 _chainId, uint64 _swapChianId, address _lockProxy, address _CCMP, address _weth, bytes memory _swapProxyHash) public {
require(_chainId != 0, "!legal");
transferOwnership(_owner);
chainId = _chainId;
lockProxyAddress = _lockProxy;
managerProxyContract = _CCMP;
WETH = _weth;
swapProxyHash = _swapProxyHash;
swapChainId = _swapChianId;
}
modifier onlyManagerContract() {
IEthCrossChainManagerProxy ieccmp = IEthCrossChainManagerProxy(managerProxyContract);
require(_msgSender() == ieccmp.getEthCrossChainManager(), "msgSender is not EthCrossChainManagerContract");
_;
}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
function setFeeCollector(address collector) external onlyOwner {
require(collector != address(0), "emtpy address");
feeCollector = collector;
}
function setLockProxy(address _lockProxy) external onlyOwner {
require(_lockProxy != address(0), "emtpy address");
lockProxyAddress = _lockProxy;
}
function setManagerProxy(address ethCCMProxyAddr) onlyOwner public {
managerProxyContract = ethCCMProxyAddr;
}
function setSwapProxyHash(bytes memory swapProxyAddr) onlyOwner public {
swapProxyHash = swapProxyAddr;
}
function setSwapChainId(uint64 _swapChianId) onlyOwner public {
swapChainId = _swapChianId;
}
function setWETH(address _weth) external onlyOwner {
WETH = _weth;
}
function bindAssetAndPool(bytes memory fromAssetHash, uint64 poolId) onlyOwner public returns (bool) {
assetInPool[fromAssetHash][poolId] = true;
return true;
}
function bind3Asset(bytes memory asset1, bytes memory asset2, bytes memory asset3, uint64 poolId) onlyOwner public {
assetInPool[asset1][poolId] = true;
assetInPool[asset2][poolId] = true;
assetInPool[asset3][poolId] = true;
}
function registerPoolWith3Assets(uint64 poolId, address poolTokenAddress, bytes memory asset1, bytes memory asset2, bytes memory asset3) onlyOwner public {
poolTokenMap[poolId] = poolTokenAddress;
assetInPool[asset1][poolId] = true;
assetInPool[asset2][poolId] = true;
assetInPool[asset3][poolId] = true;
}
function registerPool(uint64 poolId, address poolTokenAddress) onlyOwner public returns (bool) {
poolTokenMap[poolId] = poolTokenAddress;
return true;
}
function extractFee(address token) external {
require(msg.sender == feeCollector, "!feeCollector");
if (token == address(0)) {
msg.sender.transfer(address(this).balance);
} else {
IERC20(token).safeTransfer(feeCollector, IERC20(token).balanceOf(address(this)));
}
}
function swap(address fromAssetHash, uint64 toPoolId, uint64 toChainId, bytes memory toAssetHash, bytes memory toAddress, uint amount, uint minOutAmount, uint fee, uint id) public payable nonReentrant whenNotPaused returns (bool) {
_pull(fromAssetHash, amount);
amount = _checkoutFee(fromAssetHash, amount, fee);
_push(fromAssetHash, amount);
fromAssetHash = fromAssetHash==address(0) ? WETH : fromAssetHash ;
require(poolTokenMap[toPoolId] != address(0), "given pool do not exsit");
require(assetInPool[Utils.addressToBytes(fromAssetHash)][toPoolId],"input token not in given pool");
require(assetInPool[toAssetHash][toPoolId],"output token not in given pool");
require(toAddress.length !=0, "empty toAddress");
address addr;
assembly { addr := mload(add(toAddress,0x14)) }
require(addr != address(0),"zero toAddress");
{
TxArgs memory txArgs = TxArgs({
amount: amount,
minOut: minOutAmount,
toPoolId: toPoolId,
toChainId: toChainId,
fromAssetHash: Utils.addressToBytes(fromAssetHash),
fromAddress: Utils.addressToBytes(_msgSender()),
toAssetHash: toAssetHash,
toAddress: toAddress
});
bytes memory txData = _serializeTxArgs(txArgs);
address eccmAddr = IEthCrossChainManagerProxy(managerProxyContract).getEthCrossChainManager();
IEthCrossChainManager eccm = IEthCrossChainManager(eccmAddr);
require(eccm.crossChain(swapChainId, swapProxyHash, "swap", txData), "EthCrossChainManager crossChain executed error!");
}
emit LockEvent(fromAssetHash, _msgSender(), swapChainId, Utils.addressToBytes(address(0)), swapProxyHash, amount);
emit SwapEvent(fromAssetHash, _msgSender(), toPoolId, toChainId, toAssetHash, toAddress, amount, fee, id);
return true;
}
function add_liquidity(address fromAssetHash, uint64 toPoolId, uint64 toChainId, bytes memory toAddress, uint amount, uint minOutAmount, uint fee, uint id) public payable nonReentrant whenNotPaused returns (bool) {
_pull(fromAssetHash, amount);
amount = _checkoutFee(fromAssetHash, amount, fee);
_push(fromAssetHash, amount);
fromAssetHash = fromAssetHash==address(0) ? WETH : fromAssetHash ;
require(poolTokenMap[toPoolId] != address(0), "given pool do not exsit");
require(assetInPool[Utils.addressToBytes(fromAssetHash)][toPoolId],"input token not in given pool");
require(toAddress.length !=0, "empty toAddress");
address addr;
assembly { addr := mload(add(toAddress,0x14)) }
require(addr != address(0),"zero toAddress");
{
TxArgs memory txArgs = TxArgs({
amount: amount,
minOut: minOutAmount,
toPoolId: toPoolId,
toChainId: toChainId,
fromAssetHash: Utils.addressToBytes(fromAssetHash),
fromAddress: Utils.addressToBytes(_msgSender()),
toAssetHash: Utils.addressToBytes(address(0)),
toAddress: toAddress
});
bytes memory txData = _serializeTxArgs(txArgs);
address eccmAddr = IEthCrossChainManagerProxy(managerProxyContract).getEthCrossChainManager();
IEthCrossChainManager eccm = IEthCrossChainManager(eccmAddr);
require(eccm.crossChain(swapChainId, swapProxyHash, "add", txData), "EthCrossChainManager crossChain executed error!");
}
emit LockEvent(fromAssetHash, _msgSender(), swapChainId, Utils.addressToBytes(address(0)), swapProxyHash, amount);
emit AddLiquidityEvent(fromAssetHash, _msgSender(), toPoolId, toChainId, Utils.addressToBytes(address(0)), toAddress, amount, fee, id);
return true;
}
function remove_liquidity(address fromAssetHash, uint64 toPoolId, uint64 toChainId, bytes memory toAssetHash, bytes memory toAddress, uint amount, uint minOutAmount, uint fee, uint id) public payable nonReentrant whenNotPaused returns (bool) {
_pull(fromAssetHash, amount);
amount = _checkoutFee(fromAssetHash, amount, fee);
_push(fromAssetHash, amount);
fromAssetHash = fromAssetHash==address(0) ? WETH : fromAssetHash ;
require(poolTokenMap[toPoolId] != address(0), "given pool do not exsit");
require(poolTokenMap[toPoolId] == fromAssetHash,"input token is not pool LP token");
require(assetInPool[toAssetHash][toPoolId],"output token not in given pool");
require(toAddress.length !=0, "empty toAddress");
address addr;
assembly { addr := mload(add(toAddress,0x14)) }
require(addr != address(0),"zero toAddress");
{
TxArgs memory txArgs = TxArgs({
amount: amount,
minOut: minOutAmount,
toPoolId: toPoolId,
toChainId: toChainId,
fromAssetHash: Utils.addressToBytes(fromAssetHash),
fromAddress: Utils.addressToBytes(_msgSender()),
toAssetHash: toAssetHash,
toAddress: toAddress
});
bytes memory txData = _serializeTxArgs(txArgs);
address eccmAddr = IEthCrossChainManagerProxy(managerProxyContract).getEthCrossChainManager();
IEthCrossChainManager eccm = IEthCrossChainManager(eccmAddr);
require(eccm.crossChain(swapChainId, swapProxyHash, "remove", txData), "EthCrossChainManager crossChain executed error!");
}
emit LockEvent(fromAssetHash, _msgSender(), swapChainId, Utils.addressToBytes(address(0)), swapProxyHash, amount);
emit RemoveLiquidityEvent(fromAssetHash, _msgSender(), toPoolId, toChainId, toAssetHash, toAddress, amount, fee, id);
return true;
}
function getBalanceFor(address fromAssetHash) public view returns (uint256) {
if (fromAssetHash == address(0)) {
// return address(this).balance; // this expression would result in error: Failed to decode output: Error: insufficient data for uint256 type
address selfAddr = address(this);
return selfAddr.balance;
} else {
IERC20 erc20Token = IERC20(fromAssetHash);
return erc20Token.balanceOf(address(this));
}
}
// take input
function _pull(address fromAsset, uint amount) internal {
if (fromAsset == address(0)) {
require(msg.value == amount, "insufficient ether");
} else {
IERC20(fromAsset).safeTransferFrom(msg.sender, address(this), amount);
}
}
// take fee in the form of ether
function _checkoutFee(address fromAsset, uint amount, uint fee) internal view returns (uint) {
if (fromAsset == address(0)) {
require(msg.value == amount, "insufficient ether");
require(amount > fee, "amount less than fee");
return amount.sub(fee);
} else {
require(msg.value == fee, "insufficient ether");
return amount;
}
}
// lock money in LockProxy, ether store in swapper
function _push(address fromAsset, uint amount) internal {
if (fromAsset == address(0)) {
// TODO: send ether to LockProxy, ** LockProxy do not have receive(),cannot send ether now
IWETH(WETH).deposit{value: amount}();
IWETH(WETH).transfer(lockProxyAddress, amount);
} else {
IERC20(fromAsset).safeTransfer(lockProxyAddress, amount);
}
}
function _serializeTxArgs(TxArgs memory args) internal pure returns (bytes memory) {
bytes memory buff;
buff = abi.encodePacked(
ZeroCopySink.WriteUint255(args.amount),
ZeroCopySink.WriteUint255(args.minOut),
ZeroCopySink.WriteUint64(args.toPoolId),
ZeroCopySink.WriteUint64(args.toChainId),
ZeroCopySink.WriteVarBytes(args.fromAssetHash),
ZeroCopySink.WriteVarBytes(args.fromAddress),
ZeroCopySink.WriteVarBytes(args.toAssetHash),
ZeroCopySink.WriteVarBytes(args.toAddress)
);
return buff;
}
}
|
Read next eight bytes as uint64 type starting from offset buff Source bytes array offset The position from where we read the uint64 value return The read uint64 value and updated offset/
|
function NextUint64(bytes memory buff, uint256 offset) internal pure returns (uint64, uint256) {
require(offset + 8 <= buff.length && offset < offset + 8, "NextUint64, offset exceeds maximum");
uint64 v;
assembly {
let tmpbytes := mload(0x40)
let byteLen := 0x08
for {
let tindex := 0x00
let bindex := sub(byteLen, 0x01)
let bvalue := mload(add(add(buff, 0x20), offset))
tindex := add(tindex, 0x01)
bindex := sub(bindex, 0x01)
mstore8(add(tmpbytes, tindex), byte(bindex, bvalue))
}
mstore(0x40, add(tmpbytes, byteLen))
v := mload(sub(tmpbytes, sub(0x20, byteLen)))
}
return (v, offset + 8);
}
| 238,372 |
pragma solidity ^0.4.18;
// zeppelin-solidity: 1.8.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 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;
}
}
/**
* @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 Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ChampionSimple is Ownable {
using SafeMath for uint;
event LogDistributeReward(address addr, uint reward);
event LogParticipant(address addr, uint choice, uint betAmount);
event LogModifyChoice(address addr, uint oldChoice, uint newChoice);
event LogRefund(address addr, uint betAmount);
event LogWithdraw(address addr, uint amount);
event LogWinChoice(uint choice, uint reward);
uint public minimumBet = 5 * 10 ** 16;
uint public deposit = 0;
uint public totalBetAmount = 0;
uint public startTime;
uint public winChoice;
uint public winReward;
uint public numberOfBet;
bool public betClosed = false;
struct Player {
uint betAmount;
uint choice;
}
address [] public players;
mapping(address => Player) public playerInfo;
mapping(uint => uint) public numberOfChoice;
mapping(uint => mapping(address => bool)) public addressOfChoice;
mapping(address => bool) public withdrawRecord;
modifier beforeTimestamp(uint timestamp) {
require(now < timestamp);
_;
}
modifier afterTimestamp(uint timestamp) {
require(now >= timestamp);
_;
}
/**
* @dev the construct function
* @param _startTime the deadline of betting
* @param _minimumBet the minimum bet amount
*/
function ChampionSimple(uint _startTime, uint _minimumBet) payable public {
require(_startTime > now);
deposit = msg.value;
startTime = _startTime;
minimumBet = _minimumBet;
}
/**
* @dev find a player has participanted or not
* @param player the address of the participant
*/
function checkPlayerExists(address player) public view returns (bool) {
if (playerInfo[player].choice == 0) {
return false;
}
return true;
}
/**
* @dev to bet which team will be the champion
* @param choice the choice of the participant(actually team id)
*/
function placeBet(uint choice) payable beforeTimestamp(startTime) public {
require(choice > 0);
require(!checkPlayerExists(msg.sender));
require(msg.value >= minimumBet);
playerInfo[msg.sender].betAmount = msg.value;
playerInfo[msg.sender].choice = choice;
totalBetAmount = totalBetAmount.add(msg.value);
numberOfBet = numberOfBet.add(1);
players.push(msg.sender);
numberOfChoice[choice] = numberOfChoice[choice].add(1);
addressOfChoice[choice][msg.sender] = true;
LogParticipant(msg.sender, choice, msg.value);
}
/**
* @dev allow user to change their choice before a timestamp
* @param choice the choice of the participant(actually team id)
*/
function modifyChoice(uint choice) beforeTimestamp(startTime) public {
require(choice > 0);
require(checkPlayerExists(msg.sender));
uint oldChoice = playerInfo[msg.sender].choice;
numberOfChoice[oldChoice] = numberOfChoice[oldChoice].sub(1);
numberOfChoice[choice] = numberOfChoice[choice].add(1);
playerInfo[msg.sender].choice = choice;
addressOfChoice[oldChoice][msg.sender] = false;
addressOfChoice[choice][msg.sender] = true;
LogModifyChoice(msg.sender, oldChoice, choice);
}
/**
* @dev close who is champion bet with the champion id
*/
function saveResult(uint teamId) onlyOwner public {
winChoice = teamId;
betClosed = true;
winReward = deposit.add(totalBetAmount).div(numberOfChoice[winChoice]);
LogWinChoice(winChoice, winReward);
}
/**
* @dev every user can withdraw his reward
*/
function withdrawReward() public {
require(betClosed);
require(!withdrawRecord[msg.sender]);
require(winChoice > 0);
require(winReward > 0);
require(addressOfChoice[winChoice][msg.sender]);
msg.sender.transfer(winReward);
withdrawRecord[msg.sender] = true;
LogDistributeReward(msg.sender, winReward);
}
/**
* @dev anyone could recharge deposit
*/
function rechargeDeposit() payable public {
deposit = deposit.add(msg.value);
}
/**
* @dev get player bet information
* @param addr indicate the bet address
*/
function getPlayerBetInfo(address addr) view public returns (uint, uint) {
return (playerInfo[addr].choice, playerInfo[addr].betAmount);
}
/**
* @dev get the bet numbers of a specific choice
* @param choice indicate the choice
*/
function getNumberByChoice(uint choice) view public returns (uint) {
return numberOfChoice[choice];
}
/**
* @dev if there are some reasons lead game postpone or cancel
* the bet will also cancel and refund every bet
*/
function refund() onlyOwner public {
for (uint i = 0; i < players.length; i++) {
players[i].transfer(playerInfo[players[i]].betAmount);
LogRefund(players[i], playerInfo[players[i]].betAmount);
}
}
/**
* @dev get the players
*/
function getPlayers() view public returns (address[]) {
return players;
}
/**
* @dev dealer can withdraw the remain ether if distribute exceeds max length
*/
function withdraw() onlyOwner public {
uint _balance = address(this).balance;
owner.transfer(_balance);
LogWithdraw(owner, _balance);
}
}
|
get player bet information addr indicate the bet address/
|
function getPlayerBetInfo(address addr) view public returns (uint, uint) {
return (playerInfo[addr].choice, playerInfo[addr].betAmount);
}
| 7,243,818 |
./partial_match/1/0x238058874fcAA923d19F906BE039350BAFe00bDe/sources/IdentityRegistry.sol
|
Updates the country corresponding to a user address. Requires that the user should have an identity contract already deployed that will be replaced. Only owner can call. _user The address of the user _country The new country of the user/
|
function updateCountry(address _user, uint16 _country) public override onlyAgent {
require(address(identity[_user]) != address(0));
investorCountry[_user] = _country;
emit CountryUpdated(_user, _country);
}
| 3,878,632 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title IPFSStorage
* @author originally written by Forest Fang (@saurfang) - modified by Chris Ball
* original: https://github.com/saurfang/ipfs-multihash-on-solidity
* @dev Stores IPFS (multihash) hash by index (original was by address)
* A multihash entry is in the format of
* <varint hash function code><varint digest size in bytes><hash function output>
* See https://github.com/multiformats/multihash
*
* Currently IPFS hash is 34 bytes long with first two segments represented as a single byte (uint8)
* The digest is 32 bytes long and can be stored using bytes32 efficiently.
*/
contract IPFSStorage {
/** @dev matches IPFS Multihash layout mentioned in comments at top */
struct Multihash {
bytes32 digest;
uint8 hashFunction;
uint8 size;
}
mapping (uint => Multihash) private entries; /** @dev nftIndex => IPFS addr hash content */
uint private numberOfMultihashes; /** @dev total number of IPFS address hash entries */
event EntrySet (uint indexed key, bytes32 digest, uint8 hashFunction, uint8 size);
/**
* @dev for this implmentation which stores a mapping by nftIndex, we're not allowing entries
* to be deleted from the system because NFTs will never be deleted, only added to.
event EntryDeleted (uint indexed key);
*/
/**
* @dev associate a multihash entry with an NFT index. The index can be used across contracts
* @param _nftIndex index is used as a key across contracts
* @param _digest hash digest produced by hashing content using hash function
* @param _hashFunction hashFunction code for the hash function used
* @param _size length of the digest
*/
function setEntry(uint _nftIndex, bytes32 _digest, uint8 _hashFunction, uint8 _size) public {
/**
* @dev IMP: the incoming IPFS address could actually point to the same address as another
* _nftIndex is pointing to. This may or may not be wanted in the final version. Also, I
* wonder if it's possible to have an 'index' of sorts for doing quick searches on the
* _digest as a tool to quickly accomplish this? That may need to be offchain (js, etc).
*/
(Multihash storage entry) = (entries[_nftIndex]);
entry.digest = _digest;
entry.hashFunction = _hashFunction;
entry.size = _size;
numberOfMultihashes++;
emit EntrySet(_nftIndex, _digest, _hashFunction, _size);
}
/**
* @dev retrieve multihash entry associated with an nftIndex
* @param _nftIndex used as key
*/
function getEntry(uint _nftIndex) public view returns(bytes32 digest, uint8 hashfunction, uint8 size) {
(Multihash storage entry) = (entries[_nftIndex]);
return (entry.digest, entry.hashFunction, entry.size);
}
/**
* @dev returns the current number of IPFS hash entries in the system
*/
function numberOfEntries() public view returns(uint numOfEntries) {
return numberOfMultihashes;
}
/**
* @dev for this implmentation, which stores a mapping by _nftIndex, we're not allowing entries
* to be deleted because the _nfts will not be deleted, only added to.
*
* @dev deassociate any multihash entry with the sender address
function clearEntry(uint _nftIndex) public {
require(entries[_nftIndex].digest != 0);
delete entries[_nftIndex];
emit EntryDeleted(_nftIndex);
}
*/
}
|
for this implmentation, which stores a mapping by _nftIndex, we're not allowing entries to be deleted because the _nfts will not be deleted, only added to. deassociate any multihash entry with the sender address
|
function clearEntry(uint _nftIndex) public {
require(entries[_nftIndex].digest != 0);
delete entries[_nftIndex];
emit EntryDeleted(_nftIndex);
}
| 12,912,366 |
./partial_match/1/0xfc4913214444aF5c715cc9F7b52655e788A569ed/sources/Icosa.sol
|
Adds more ICSA to an existing stake. amount Amount of ICSA to add to the stake. return Number of stake points allocated to the stake./ load stake into memory get the HEX share rate and calculate additional stake points lock in payout from previous stake points update stake entry add additional points to the pool (following day) increase staked supply metric temporarily burn stakers ICSA
|
function icsaStakeAddCapital (
uint256 amount
)
external
nonReentrant
returns (uint256)
{
_stakeDailyUpdate();
StakeCache memory stake;
_stakeLoad(icsaStakes[msg.sender], stake);
require(stake._isActive == true,
"ICSA: NO STAKE");
require(balanceOf(msg.sender) >= amount,
"ICSA: LOW BALANCE");
HEXGlobals memory hexGlobals = _hexGlobalsLoad();
uint256 stakePoints = amount / hexGlobals.shareRate;
uint256 stakerClass = ((stake._stakeAmount + amount) * _decimalResolution) / totalSupply();
require(stakePoints > 0,
"ICSA: TOO SMALL");
uint256 payoutPerPointIcsa = icsaPoolPayoutIcsa[currentDay] - icsaPoolPayoutIcsa[stake._capitalAdded];
uint256 payoutIcsa = (stake._stakePoints * payoutPerPointIcsa) / _decimalResolution;
uint256 payoutPerPointHdrn = icsaPoolPayoutHdrn[currentDay] - icsaPoolPayoutHdrn[stake._capitalAdded];
uint256 payoutHdrn = (stake._stakePoints * payoutPerPointHdrn) / _decimalResolution;
uint256 minStakeLength = _calcMinStakeLength(stakerClass);
stake._capitalAdded = currentDay;
stake._stakePoints += stakePoints;
stake._payoutPreCapitalAddIcsa += payoutIcsa;
stake._payoutPreCapitalAddHdrn += payoutHdrn;
stake._stakeAmount += amount;
stake._minStakeLength = minStakeLength;
_stakeUpdate(icsaStakes[msg.sender], stake);
icsaPoolPoints[currentDay + 1] += stakePoints;
icsaStakedSupply += amount;
_burn(msg.sender, amount);
emit ICSAStakeAddCapital(
uint256(uint40 (block.timestamp))
| (uint256(uint120(stakePoints)) << 40)
| (uint256(uint80 (amount)) << 160)
| (uint256(uint16 (minStakeLength)) << 240),
msg.sender
);
return stake._stakePoints;
}
| 15,721,957 |
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
// Inheritance
import "./BaseSynthetixBridge.sol";
import "./interfaces/ISynthetixBridgeToOptimism.sol";
import "./optimistic-ethereum/iOVM/bridge/tokens/iOVM_L1TokenGateway.sol";
// Internal references
import "./lib/SafeERC20.sol";
import "./interfaces/IIssuer.sol";
import "./interfaces/ISynthetixBridgeToBase.sol";
import "./optimistic-ethereum/iOVM/bridge/tokens/iOVM_L2DepositedToken.sol";
contract SynthetixBridgeToOptimism is BaseSynthetixBridge, ISynthetixBridgeToOptimism, iOVM_L1TokenGateway {
using SafeERC20 for IERC20;
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_ISSUER = "Issuer";
bytes32 private constant CONTRACT_REWARDSDISTRIBUTION = "RewardsDistribution";
bytes32 private constant CONTRACT_OVM_SYNTHETIXBRIDGETOBASE = "ovm:SynthetixBridgeToBase";
bytes32 private constant CONTRACT_SYNTHETIXBRIDGEESCROW = "SynthetixBridgeEscrow";
uint8 private constant MAX_ENTRIES_MIGRATED_PER_MESSAGE = 26;
// ========== CONSTRUCTOR ==========
constructor(address _owner, address _resolver) public BaseSynthetixBridge(_owner, _resolver) {}
// ========== INTERNALS ============
function synthetixERC20() internal view returns (IERC20) {
return IERC20(requireAndGetAddress(CONTRACT_SYNTHETIX));
}
function issuer() internal view returns (IIssuer) {
return IIssuer(requireAndGetAddress(CONTRACT_ISSUER));
}
function rewardsDistribution() internal view returns (address) {
return requireAndGetAddress(CONTRACT_REWARDSDISTRIBUTION);
}
function synthetixBridgeToBase() internal view returns (address) {
return requireAndGetAddress(CONTRACT_OVM_SYNTHETIXBRIDGETOBASE);
}
function synthetixBridgeEscrow() internal view returns (address) {
return requireAndGetAddress(CONTRACT_SYNTHETIXBRIDGEESCROW);
}
function hasZeroDebt() internal view {
require(issuer().debtBalanceOf(msg.sender, "sUSD") == 0, "Cannot deposit or migrate with debt");
}
/* ========== VIEWS ========== */
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = BaseSynthetixBridge.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](4);
newAddresses[0] = CONTRACT_ISSUER;
newAddresses[1] = CONTRACT_REWARDSDISTRIBUTION;
newAddresses[2] = CONTRACT_OVM_SYNTHETIXBRIDGETOBASE;
newAddresses[3] = CONTRACT_SYNTHETIXBRIDGEESCROW;
addresses = combineArrays(existingAddresses, newAddresses);
}
// ========== MODIFIERS ============
modifier requireZeroDebt() {
hasZeroDebt();
_;
}
// ========== PUBLIC FUNCTIONS =========
function deposit(uint256 amount) external requireInitiationActive requireZeroDebt {
_initiateDeposit(msg.sender, amount);
}
function depositTo(address to, uint amount) external requireInitiationActive requireZeroDebt {
_initiateDeposit(to, amount);
}
function migrateEscrow(uint256[][] memory entryIDs) public requireInitiationActive requireZeroDebt {
_migrateEscrow(entryIDs);
}
// invoked by a generous user on L1
function depositReward(uint amount) external requireInitiationActive {
// move the SNX into the deposit escrow
synthetixERC20().transferFrom(msg.sender, synthetixBridgeEscrow(), amount);
_depositReward(msg.sender, amount);
}
// forward any accidental tokens sent here to the escrow
function forwardTokensToEscrow(address token) external {
IERC20 erc20 = IERC20(token);
erc20.safeTransfer(synthetixBridgeEscrow(), erc20.balanceOf(address(this)));
}
// ========= RESTRICTED FUNCTIONS ==============
// invoked by Messenger on L1 after L2 waiting period elapses
function finalizeWithdrawal(address to, uint256 amount) external {
// ensure function only callable from L2 Bridge via messenger (aka relayer)
require(msg.sender == address(messenger()), "Only the relayer can call this");
require(messenger().xDomainMessageSender() == synthetixBridgeToBase(), "Only the L2 bridge can invoke");
// transfer amount back to user
synthetixERC20().transferFrom(synthetixBridgeEscrow(), to, amount);
// no escrow actions - escrow remains on L2
emit iOVM_L1TokenGateway.WithdrawalFinalized(to, amount);
}
// invoked by RewardsDistribution on L1 (takes SNX)
function notifyRewardAmount(uint256 amount) external {
require(msg.sender == address(rewardsDistribution()), "Caller is not RewardsDistribution contract");
// NOTE: transfer SNX to synthetixBridgeEscrow because RewardsDistribution transfers them initially to this contract.
synthetixERC20().transfer(synthetixBridgeEscrow(), amount);
// to be here means I've been given an amount of SNX to distribute onto L2
_depositReward(msg.sender, amount);
}
function depositAndMigrateEscrow(uint256 depositAmount, uint256[][] memory entryIDs)
public
requireInitiationActive
requireZeroDebt
{
if (entryIDs.length > 0) {
_migrateEscrow(entryIDs);
}
if (depositAmount > 0) {
_initiateDeposit(msg.sender, depositAmount);
}
}
// ========== PRIVATE/INTERNAL FUNCTIONS =========
function _depositReward(address _from, uint256 _amount) internal {
// create message payload for L2
ISynthetixBridgeToBase bridgeToBase;
bytes memory messageData = abi.encodeWithSelector(bridgeToBase.finalizeRewardDeposit.selector, _from, _amount);
// relay the message to this contract on L2 via L1 Messenger
messenger().sendMessage(
synthetixBridgeToBase(),
messageData,
uint32(getCrossDomainMessageGasLimit(CrossDomainMessageGasLimits.Reward))
);
emit RewardDepositInitiated(_from, _amount);
}
function _initiateDeposit(address _to, uint256 _depositAmount) private {
// Transfer SNX to L2
// First, move the SNX into the deposit escrow
synthetixERC20().transferFrom(msg.sender, synthetixBridgeEscrow(), _depositAmount);
// create message payload for L2
iOVM_L2DepositedToken bridgeToBase;
bytes memory messageData = abi.encodeWithSelector(bridgeToBase.finalizeDeposit.selector, _to, _depositAmount);
// relay the message to this contract on L2 via L1 Messenger
messenger().sendMessage(
synthetixBridgeToBase(),
messageData,
uint32(getCrossDomainMessageGasLimit(CrossDomainMessageGasLimits.Deposit))
);
emit iOVM_L1TokenGateway.DepositInitiated(msg.sender, _to, _depositAmount);
}
function _migrateEscrow(uint256[][] memory _entryIDs) private {
// loop through the entryID array
for (uint256 i = 0; i < _entryIDs.length; i++) {
// Cannot send more than MAX_ENTRIES_MIGRATED_PER_MESSAGE entries due to ovm gas restrictions
require(_entryIDs[i].length <= MAX_ENTRIES_MIGRATED_PER_MESSAGE, "Exceeds max entries per migration");
// Burn their reward escrow first
// Note: escrowSummary would lose the fidelity of the weekly escrows, so this may not be sufficient
uint256 escrowedAccountBalance;
VestingEntries.VestingEntry[] memory vestingEntries;
(escrowedAccountBalance, vestingEntries) = rewardEscrowV2().burnForMigration(msg.sender, _entryIDs[i]);
// if there is an escrow amount to be migrated
if (escrowedAccountBalance > 0) {
// NOTE: transfer SNX to synthetixBridgeEscrow because burnForMigration() transfers them to this contract.
synthetixERC20().transfer(synthetixBridgeEscrow(), escrowedAccountBalance);
// create message payload for L2
ISynthetixBridgeToBase bridgeToBase;
bytes memory messageData =
abi.encodeWithSelector(
bridgeToBase.finalizeEscrowMigration.selector,
msg.sender,
escrowedAccountBalance,
vestingEntries
);
// relay the message to this contract on L2 via L1 Messenger
messenger().sendMessage(
synthetixBridgeToBase(),
messageData,
uint32(getCrossDomainMessageGasLimit(CrossDomainMessageGasLimits.Escrow))
);
emit ExportedVestingEntries(msg.sender, escrowedAccountBalance, vestingEntries);
}
}
}
// ========== EVENTS ==========
event ExportedVestingEntries(
address indexed account,
uint256 escrowedAccountBalance,
VestingEntries.VestingEntry[] vestingEntries
);
event RewardDepositInitiated(address indexed account, uint256 amount);
}
|
forward any accidental tokens sent here to the escrow
|
function forwardTokensToEscrow(address token) external {
IERC20 erc20 = IERC20(token);
erc20.safeTransfer(synthetixBridgeEscrow(), erc20.balanceOf(address(this)));
}
| 1,048,571 |
pragma solidity ^0.4.25;
// Original gameplay and contract by Spielley
// Spielley is not liable for any bugs or exploits the contract may contain
// This game is purely intended for fun purposes
// Gameplay:
// Send in 0.1 eth to get a soldier in the field and 1 bullet
// Wait till you reach the waiting time needed to shoot
// Each time someone is killed divs are given to the survivors
// 2 ways to shoot:
// semi random, available first
// Chose target
// there is only a 1 time self kill prevention when semi is used
// if you send in multiple soldiers friendly kills are possible
// => use target instead
// Social gameplay: Chat with people and Coordinate your shots
// if you want to risk not getting shot by semi bullets first
// you keep your bullets when you send in new soldiers
// if your soldier dies your address is added to the back of the refund line
// to get back your initial eth
// payout structure per 0.1 eth:
// 0.005 eth buy P3D
// 0.005 eth goes to the refund line
// 0.001 eth goes dev cut shared across SPASM(Spielleys profit share aloocation module)
// 0.089 eth is given to survivors upon kill
// P3D divs:
// 1% to SPASM
// 99% to refund line
// SPASM: get a part of the dev fee payouts and funds Spielley to go fulltime dev
// https://etherscan.io/address/0xfaae60f2ce6491886c9f7c9356bd92f688ca66a1#writeContract
// => buyshares function , send in eth to get shares
// P3D MN payouts for UI devs
// payout per 0.1 eth sent in the sendInSoldier function
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = 0x0B0eFad4aE088a88fFDC50BCe5Fb63c6936b9220;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// Snip3d contract
contract Snip3D is Owned {
using SafeMath for uint;
uint public _totalSupply;
mapping(address => uint256)public balances;// soldiers on field
mapping(address => uint256)public bullets;// amount of bullets Owned
mapping(uint256 => address)public formation;// the playing field
uint256 public nextFormation;// next spot in formation
mapping(address => uint256)public lastMove;//blocknumber lastMove
mapping(uint256 => address) public RefundWaitingLine;
uint256 public NextInLine;//next person to be refunded
uint256 public NextAtLineEnd;//next spot to add loser
uint256 public Refundpot;
uint256 public blocksBeforeSemiRandomShoot = 10;
uint256 public blocksBeforeTargetShoot = 40;
//constructor
constructor()
public
{
}
//mods
modifier isAlive()
{
require(balances[msg.sender] > 0);
_;
}
// divfunctions
HourglassInterface constant P3Dcontract_ = HourglassInterface(0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe);
SPASMInterface constant SPASM_ = SPASMInterface(0xfaAe60F2CE6491886C9f7C9356bd92F688cA66a1);
// view functions
function harvestabledivs()
view
public
returns(uint256)
{
return ( P3Dcontract_.dividendsOf(address(this))) ;
}
function amountofp3d() external view returns(uint256){
return ( P3Dcontract_.balanceOf(address(this))) ;
}
//divsection
uint256 public pointMultiplier = 10e18;
struct Account {
uint balance;
uint lastDividendPoints;
}
mapping(address=>Account) accounts;
mapping(address => string) public Vanity;
uint public ethtotalSupply;
uint public totalDividendPoints;
uint public unclaimedDividends;
function dividendsOwing(address account) public view returns(uint256) {
uint256 newDividendPoints = totalDividendPoints.sub(accounts[account].lastDividendPoints);
return (balances[account] * newDividendPoints) / pointMultiplier;
}
modifier updateAccount(address account) {
uint256 owing = dividendsOwing(account);
if(owing > 0) {
unclaimedDividends = unclaimedDividends.sub(owing);
account.transfer(owing);
}
accounts[account].lastDividendPoints = totalDividendPoints;
_;
}
function () external payable{}
function fetchdivs(address toupdate) public updateAccount(toupdate){}
// Gamefunctions
function sendInSoldier(address masternode) public updateAccount(msg.sender) payable{
uint256 value = msg.value;
require(value >= 100 finney);// sending in sol costs 0.1 eth
address sender = msg.sender;
// add life
balances[sender]++;
// update totalSupply
_totalSupply++;
// add bullet
bullets[sender]++;
// add to playing field
formation[nextFormation] = sender;
nextFormation++;
// reset lastMove to prevent people from adding bullets and start shooting
lastMove[sender] = block.number;
// buy P3D
P3Dcontract_.buy.value(5 wei)(masternode);
// check excess of payed
if(value > 100 finney){uint256 toRefund = value.sub(100 finney);Refundpot.add(toRefund);}
// progress refundline
Refundpot += 5 finney;
// take SPASM cut
SPASM_.disburse.value(1 wei)();
}
function shootSemiRandom() public isAlive() {
address sender = msg.sender;
require(block.number > lastMove[sender] + blocksBeforeSemiRandomShoot);
require(bullets[sender] > 0);
uint256 semiRNG = (block.number.sub(lastMove[sender])) % 200;
uint256 shot = uint256 (blockhash(block.number.sub(semiRNG))) % nextFormation;
address killed = formation[shot];
// solo soldiers self kill prevention - shoots next in line instead
if(sender == killed)
{
shot = uint256 (blockhash(block.number.sub(semiRNG).add(1))) % nextFormation;
killed = formation[shot];
}
// remove life
balances[killed]--;
// update totalSupply
_totalSupply--;
// remove bullet
bullets[sender]--;
// remove from playing field
uint256 lastEntry = nextFormation.sub(1);
formation[shot] = formation[lastEntry];
nextFormation--;
// reset lastMove to prevent people from adding bullets and start shooting
lastMove[sender] = block.number;
// update divs loser
fetchdivs(killed);
// add loser to refundline
RefundWaitingLine[NextAtLineEnd] = killed;
NextAtLineEnd++;
// disburse eth to survivors
uint256 amount = 89 finney;
totalDividendPoints = totalDividendPoints.add(amount.mul(pointMultiplier).div(_totalSupply));
unclaimedDividends = unclaimedDividends.add(amount);
}
function shootTarget(uint256 target) public isAlive() {
address sender = msg.sender;
require(target < nextFormation && target > 0);
require(block.number > lastMove[sender] + blocksBeforeTargetShoot);
require(bullets[sender] > 0);
address killed = formation[target];
// solo soldiers self kill prevention - shoots next in line instead
// remove life
balances[killed]--;
// update totalSupply
_totalSupply--;
// remove bullet
bullets[sender]--;
// remove from playing field
uint256 lastEntry = nextFormation.sub(1);
formation[target] = formation[lastEntry];
nextFormation--;
// reset lastMove to prevent people from adding bullets and start shooting
lastMove[sender] = block.number;
// update divs loser
fetchdivs(killed);
// add loser to refundline
RefundWaitingLine[NextAtLineEnd] = killed;
NextAtLineEnd++;
// fetch contracts divs
//allocate p3d dividends to contract
uint256 dividends = harvestabledivs();
require(dividends > 0);
uint256 base = dividends.div(100);
P3Dcontract_.withdraw();
SPASM_.disburse.value(base)();// to dev fee sharing contract SPASM
// disburse eth to survivors
uint256 amount = 89 finney;
amount = amount.add(dividends.sub(base));
totalDividendPoints = totalDividendPoints.add(amount.mul(pointMultiplier).div(_totalSupply));
unclaimedDividends = unclaimedDividends.add(amount);
}
function Payoutnextrefund ()public
{
//allocate p3d dividends to sacrifice if existing
uint256 Pot = Refundpot;
require(Pot > 0.1 ether);
Refundpot -= 0.1 ether;
RefundWaitingLine[NextInLine].transfer(0.1 ether);
NextInLine++;
//
}
function disburse() public payable {
uint256 amount = msg.value;
uint256 base = amount.div(100);
uint256 amt2 = amount.sub(base);
totalDividendPoints = totalDividendPoints.add(amt2.mul(pointMultiplier).div(_totalSupply));
unclaimedDividends = unclaimedDividends.add(amt2);
}
function changevanity(string van) public payable{
require(msg.value >= 1 finney);
Vanity[msg.sender] = van;
Refundpot += msg.value;
}
function P3DDivstocontract() public payable{
uint256 divs = harvestabledivs();
require(divs > 0);
P3Dcontract_.withdraw();
//1% to owner
uint256 base = divs.div(100);
uint256 amt2 = divs.sub(base);
SPASM_.disburse.value(base)();// to dev fee sharing contract
totalDividendPoints = totalDividendPoints.add(amt2.mul(pointMultiplier).div(_totalSupply));
unclaimedDividends = unclaimedDividends.add(amt2);
}
function die () public onlyOwner {
selfdestruct(msg.sender);
}
}
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);
}
interface SPASMInterface {
function() payable external;
function disburse() external payable;
}
|
solo soldiers self kill prevention - shoots next in line instead
|
function shootSemiRandom() public isAlive() {
address sender = msg.sender;
require(block.number > lastMove[sender] + blocksBeforeSemiRandomShoot);
require(bullets[sender] > 0);
uint256 semiRNG = (block.number.sub(lastMove[sender])) % 200;
uint256 shot = uint256 (blockhash(block.number.sub(semiRNG))) % nextFormation;
address killed = formation[shot];
if(sender == killed)
{
shot = uint256 (blockhash(block.number.sub(semiRNG).add(1))) % nextFormation;
killed = formation[shot];
}
formation[shot] = formation[lastEntry];
nextFormation--;
NextAtLineEnd++;
totalDividendPoints = totalDividendPoints.add(amount.mul(pointMultiplier).div(_totalSupply));
unclaimedDividends = unclaimedDividends.add(amount);
}
| 7,307,177 |
./full_match/4/0xCa0538FE4ED6B483F92D14aD2767dfD8A0D21453/sources/contracts/FundMe.sol
|
here we have to wrap uint356 around answer because the return type is uint256 so we have to cast answer...to be a uint256 type, not a int256 type
|
function getPrice() public view returns(uint256) {
AggregatorV3Interface priceFeed = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e);
(,int256 answer,,,) = priceFeed.latestRoundData();
return uint256(answer * 10000000000);
}
| 800,012 |
./full_match/5/0x7C2491601E9D96F468f5f64740903c06B749beFB/sources/contracts/Gift.sol
|
allow the contract owner to mark tokens as redeemed
|
function redeem(uint256 tokenId) external onlyOwner {
require(!_redeemed[tokenId], "Gift: already redeemed");
_redeemed[tokenId] = true;
}
| 1,935,165 |
pragma solidity >=0.5.0;
//Interfaces
import './interfaces/IUniswapV2Router02.sol';
import './interfaces/IERC20.sol';
import './interfaces/ISettings.sol';
import './interfaces/IAddressResolver.sol';
import './interfaces/IBaseUbeswapAdapter.sol';
//Libraries
import './libraries/SafeMath.sol';
contract BaseUbeswapAdapter is IBaseUbeswapAdapter {
using SafeMath for uint;
// Max slippage percent allowed
uint public constant override MAX_SLIPPAGE_PERCENT = 10; //10% slippage
IAddressResolver public immutable ADDRESS_RESOLVER;
constructor(IAddressResolver addressResolver) public {
ADDRESS_RESOLVER = addressResolver;
}
/* ========== VIEWS ========== */
/**
* @dev Given an input asset address, returns the price of the asset in cUSD
* @param currencyKey Address of the asset
* @return uint Price of the asset
*/
function getPrice(address currencyKey) public view override returns(uint) {
address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings");
address ubeswapRouterAddress = ADDRESS_RESOLVER.getContractAddress("UbeswapRouter");
address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress();
//Check if currency key is cUSD
if (currencyKey == stableCoinAddress)
{
return 10 ** _getDecimals(currencyKey);
}
require(currencyKey != address(0), "Invalid currency key");
require(ISettings(settingsAddress).checkIfCurrencyIsAvailable(currencyKey), "Currency is not available");
address[] memory path = new address[](2);
path[0] = currencyKey;
path[1] = stableCoinAddress;
uint[] memory amounts = IUniswapV2Router02(ubeswapRouterAddress).getAmountsOut(10 ** _getDecimals(currencyKey), path); // 1 token -> cUSD
return amounts[1];
}
/**
* @dev Given an input asset amount, returns the maximum output amount of the other asset
* @notice Assumes numberOfTokens is multiplied by currency's decimals before function call
* @param numberOfTokens Number of tokens
* @param currencyKeyIn Address of the asset to be swap from
* @param currencyKeyOut Address of the asset to be swap to
* @return uint Amount out of the asset
*/
function getAmountsOut(uint numberOfTokens, address currencyKeyIn, address currencyKeyOut) public view override returns (uint) {
address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings");
address ubeswapRouterAddress = ADDRESS_RESOLVER.getContractAddress("UbeswapRouter");
address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress();
require(currencyKeyIn != address(0), "Invalid currency key in");
require(currencyKeyOut != address(0), "Invalid currency key out");
require(ISettings(settingsAddress).checkIfCurrencyIsAvailable(currencyKeyIn) || currencyKeyIn == stableCoinAddress, "Currency is not available");
require(ISettings(settingsAddress).checkIfCurrencyIsAvailable(currencyKeyOut) || currencyKeyOut == stableCoinAddress, "Currency is not available");
require(numberOfTokens > 0, "Number of tokens must be greater than 0");
address[] memory path = new address[](2);
path[0] = currencyKeyIn;
path[1] = currencyKeyOut;
uint[] memory amounts = IUniswapV2Router02(ubeswapRouterAddress).getAmountsOut(numberOfTokens, path);
return amounts[1];
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @dev Swaps an exact `amountToSwap` of an asset to another; meant to be called from a user pool
* @notice Pool needs to transfer assetToSwapFrom to BaseUbeswapAdapter before calling this function
* @param assetToSwapFrom Origin asset
* @param assetToSwapTo Destination asset
* @param amountToSwap Exact amount of `assetToSwapFrom` to be swapped
* @param minAmountOut the min amount of `assetToSwapTo` to be received from the swap
* @return the number of tokens received
*/
function swapFromPool(address assetToSwapFrom, address assetToSwapTo, uint amountToSwap, uint minAmountOut) public override returns (uint) {
require(ADDRESS_RESOLVER.checkIfPoolAddressIsValid(msg.sender), "Only the pool can call this function");
return _swapExactTokensForTokens(msg.sender, assetToSwapFrom, assetToSwapTo, amountToSwap, minAmountOut);
}
/**
* @dev Swaps an exact `amountToSwap` of an asset to another; meant to be called from a trading bot
* @notice Bot needs to transfer assetToSwapFrom to BaseUbeswapAdapter before calling this function
* @param assetToSwapFrom Origin asset
* @param assetToSwapTo Destination asset
* @param amountToSwap Exact amount of `assetToSwapFrom` to be swapped
* @param minAmountOut the min amount of `assetToSwapTo` to be received from the swap
* @return the number of tokens received
*/
function swapFromBot(address assetToSwapFrom, address assetToSwapTo, uint amountToSwap, uint minAmountOut) public override returns (uint) {
require(ADDRESS_RESOLVER.checkIfTradingBotAddressIsValid(msg.sender), "Only the trading bot can call this function");
return _swapExactTokensForTokens(msg.sender, assetToSwapFrom, assetToSwapTo, amountToSwap, minAmountOut);
}
/* ========== INTERNAL FUNCTIONS ========== */
/**
* @dev Swaps an exact `amountToSwap` of an asset to another
* @notice Assumes amountToSwap is multiplied by currency's decimals before function call
* @param addressToSwapFrom the pool or bot that is making the swap
* @param assetToSwapFrom Origin asset
* @param assetToSwapTo Destination asset
* @param amountToSwap Exact amount of `assetToSwapFrom` to be swapped
* @param minAmountOut the min amount of `assetToSwapTo` to be received from the swap
* @return the amount of tokens received
*/
function _swapExactTokensForTokens(address addressToSwapFrom, address assetToSwapFrom, address assetToSwapTo, uint amountToSwap, uint minAmountOut) internal returns (uint) {
uint amountOut = getAmountsOut(amountToSwap, assetToSwapFrom, assetToSwapTo);
uint expectedMinAmountOut = amountOut.mul(100 - MAX_SLIPPAGE_PERCENT).div(100);
require(expectedMinAmountOut < minAmountOut, 'BaseUbeswapAdapter: minAmountOut exceeds max slippage');
address ubeswapRouterAddress = ADDRESS_RESOLVER.getContractAddress("UbeswapRouter");
// Approves the transfer for the swap. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix.
IERC20(assetToSwapFrom).approve(ubeswapRouterAddress, 0);
IERC20(assetToSwapFrom).approve(ubeswapRouterAddress, amountToSwap);
address[] memory path;
path = new address[](2);
path[0] = assetToSwapFrom;
path[1] = assetToSwapTo;
uint[] memory amounts = IUniswapV2Router02(ubeswapRouterAddress).swapExactTokensForTokens(amountToSwap, minAmountOut, path, addressToSwapFrom, block.timestamp);
emit Swapped(assetToSwapFrom, assetToSwapTo, amounts[0], amounts[amounts.length - 1], block.timestamp);
return amounts[amounts.length - 1];
}
/**
* @dev Get the decimals of an asset
* @return number of decimals of the asset
*/
function _getDecimals(address asset) internal view returns (uint) {
return IERC20(asset).decimals();
}
/* ========== EVENTS ========== */
event Swapped(address fromAsset, address toAsset, uint fromAmount, uint receivedAmount, uint timestamp);
}
|
Swaps an exact `amountToSwap` of an asset to another; meant to be called from a trading bot Bot needs to transfer assetToSwapFrom to BaseUbeswapAdapter before calling this function assetToSwapFrom Origin asset assetToSwapTo Destination asset amountToSwap Exact amount of `assetToSwapFrom` to be swapped minAmountOut the min amount of `assetToSwapTo` to be received from the swap return the number of tokens received/
|
function swapFromBot(address assetToSwapFrom, address assetToSwapTo, uint amountToSwap, uint minAmountOut) public override returns (uint) {
require(ADDRESS_RESOLVER.checkIfTradingBotAddressIsValid(msg.sender), "Only the trading bot can call this function");
return _swapExactTokensForTokens(msg.sender, assetToSwapFrom, assetToSwapTo, amountToSwap, minAmountOut);
}
| 5,447,193 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./GetLastPrice.sol";
contract OBdefiStaking {
// Constants
uint public constant STAKING_RATE = 6;
// define here what the rate refers to. Usually it would be a year = 52 weeks in solidity
// but for test purpose it can be easier to use shorter period like one day
uint public constant STAKING_PERIODICITY = 1 days;
// will store an entry information
// - stakedAmount = sum of staked amount less sum of withdrawn amounts
// - previousStakedAmountPerSecond = necessary to calculate reward without the need to keep a sub-array per token
// - lastTransactionDate: last date to use for calculation
struct Token {
address tokenAddress;
uint stakedAmount;
uint previousStakedAmountPerSecond;
uint lastTransactionDate;
}
Token[] public tokens;
mapping(address => uint) public tokenMap;
//GetLastPrice - il est recommandé de faire le calcul de prix à l'extérieur car pas fiable dans le SC
// vu dans la doc :)
GetLastPrice private priceLatest = new GetLastPrice();
/// @notice calculate staked amount per second
/// @param token struct containing the necessary information
/// @return uint
function getNewStakedAmountPerSecond (Token memory token) private view returns (uint){
return token.previousStakedAmountPerSecond + ((block.timestamp - token.lastTransactionDate) * token.stakedAmount);
}
/// @notice calculate reward based on token parameter
/// @param token struct containing the necessary information
/// @return an uint
function calculateReward (Token memory token) private view returns (uint){
return ((getNewStakedAmountPerSecond(token) * STAKING_RATE) / STAKING_PERIODICITY) / 100;
}
function GetStakingRate () public view returns (uint) {
return STAKING_RATE;
}
function GetStakingPeriodicity () public view returns (uint) {
return STAKING_PERIODICITY;
}
function GetStakedTokens () public view returns (Token[] memory) {
return tokens;
}
/// @notice Stake an amount of a specific ERC20 token
/// @param tokenAddress address of the staked token
/// @param amount staked amount
function stakeToken (address tokenAddress, uint amount) public {
require(amount > 0, "You cannot stake 0 token");
int arrayIndex = int(tokenMap[tokenAddress]) - 1;
if (arrayIndex == -1) {
tokens.push(Token(tokenAddress, amount, 0, block.timestamp));
tokenMap[tokenAddress] = tokens.length;
}
else {
Token storage currentToken = tokens[uint(arrayIndex)];
currentToken.previousStakedAmountPerSecond = getNewStakedAmountPerSecond(currentToken);
currentToken.stakedAmount += amount;
currentToken.lastTransactionDate = block.timestamp;
}
// transfer amount from stakeholder to the contract
// attn : approuve du contrat avant :
// stakeholder will have first approved (minimum = amount) the contract to transfer tokens from its address
IERC20(tokenAddress).transferFrom(msg.sender, address(this), amount);
}
/// @notice Withdraw an amount of a specific ERC20 token
/// @param tokenAddress address of the staked token
/// @param amount amount to be withdrawn
function unstakeToken (address tokenAddress, uint amount) public {
require(amount > 0, "You cannot withdraw 0 token");
int arrayIndex = int(tokenMap[tokenAddress]) - 1;
require(arrayIndex > -1, "No staked token on this contract");
Token storage currentToken = tokens[uint(arrayIndex)];
require(currentToken.stakedAmount >= amount, "Not enough staked tokens.");
currentToken.previousStakedAmountPerSecond = getNewStakedAmountPerSecond(currentToken);
currentToken.lastTransactionDate = block.timestamp;
currentToken.stakedAmount -= amount;
// transfer amount back to stakeholder
IERC20(tokenAddress).transfer(msg.sender, amount);
}
/// @notice indicate the total staked amount of a given token
/// @param tokenAddress address of the staked token
/// @return uint
function getTokenStakedAmount (address tokenAddress) public view returns (uint) {
int arrayIndex = int(tokenMap[tokenAddress]) - 1;
if (arrayIndex == -1) {
return 0;
}
else {
return tokens[uint(arrayIndex)].stakedAmount;
}
}
/// @notice calculate reward amount for a given token
/// @param tokenAddress address of the staked token
/// @return uint
function getTokenReward (address tokenAddress) public view returns (uint) {
int arrayIndex = int(tokenMap[tokenAddress]) - 1;
if (arrayIndex == -1) {
return 0;
}
else {
return calculateReward(tokens[uint(arrayIndex)]);
}
}
// voir si besoin de cette fct ... pas de rinkeby
/// @notice factory to give chainlink data feed address for Rinkeby testnet
/// @param sourceTokenSymbol symbol of the token
/// @return an address
function getDataFeedAddressToETH (string memory sourceTokenSymbol) private pure returns (address) {
if(keccak256(bytes(sourceTokenSymbol)) == keccak256(bytes("BTC"))) {
return address(0xc751E86208F0F8aF2d5CD0e29716cA7AD98B5eF5);
}
else if(keccak256(bytes(sourceTokenSymbol)) == keccak256(bytes("DAI"))) {
return address(0x74825DbC8BF76CC4e9494d0ecB210f676Efa001D);
}
else if(keccak256(bytes(sourceTokenSymbol)) == keccak256(bytes("USDC"))) {
return address(0xdCA36F27cbC4E38aE16C4E9f99D39b42337F6dcf);
}
else {
return address(0);
}
}
/// @notice returns the corresponding Rinkeby chainlink price for a token
/// @dev note: for test purpose it also returns 30 for "OBS" - 40 for "MCTO"
/// @param tokenAddress address of the staked token
/// @return uint
function getTokenPrice (address tokenAddress) public view returns (int) {
try ERC20(tokenAddress).symbol() returns (string memory tokenSymbol) {
address datafeedAddress = getDataFeedAddressToETH(tokenSymbol);
if (datafeedAddress == address(0)) {
if (keccak256(bytes(tokenSymbol)) == keccak256(bytes("OBS"))) {
return 30;
}
else if (keccak256(bytes(tokenSymbol)) == keccak256(bytes("MCTO"))) {
return 40;
}
else {
return 0;
}
}
else {
// calcul externe du dernier prix -
try priceLatest.getLatestPrice(tokenAddress) returns (int price) {
return price;
} catch {
return 0;
}
}
}
catch {
return 0;
}
}
/// @notice returns the total stake reward price in ETH
/// @return uint
function getAllTokensRewardsInETH () public view returns (uint) {
uint totalRewardsInETH;
for (uint tokenCounter=0; tokenCounter<tokens.length; tokenCounter++) {
Token storage currentToken = tokens[tokenCounter];
totalRewardsInETH += calculateReward(currentToken) * uint(getTokenPrice(currentToken.tokenAddress));
}
return totalRewardsInETH;
}
}
|
Stake an amount of a specific ERC20 token tokenAddress address of the staked token amount staked amount
|
function stakeToken (address tokenAddress, uint amount) public {
require(amount > 0, "You cannot stake 0 token");
int arrayIndex = int(tokenMap[tokenAddress]) - 1;
if (arrayIndex == -1) {
tokens.push(Token(tokenAddress, amount, 0, block.timestamp));
tokenMap[tokenAddress] = tokens.length;
}
else {
Token storage currentToken = tokens[uint(arrayIndex)];
currentToken.previousStakedAmountPerSecond = getNewStakedAmountPerSecond(currentToken);
currentToken.stakedAmount += amount;
currentToken.lastTransactionDate = block.timestamp;
}
}
| 6,347,111 |
pragma solidity 0.5.17;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol";
import "../libraries/ERC20WithFees.sol";
import "../DarknodeRegistry/DarknodeRegistry.sol";
import "./DarknodePaymentStore.sol";
/// @notice DarknodePayment is responsible for paying off darknodes for their
/// computation.
contract DarknodePayment is Claimable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
using ERC20WithFees for ERC20;
string public VERSION; // Passed in as a constructor parameter.
/// @notice The special address for Ether.
address public constant ETHEREUM =
0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
DarknodeRegistryLogicV1 public darknodeRegistry; // Passed in as a constructor parameter.
/// @notice DarknodePaymentStore is the storage contract for darknode
/// payments.
DarknodePaymentStore public store; // Passed in as a constructor parameter.
/// @notice The address that can call changeCycle()
// This defaults to the owner but should be changed to the DarknodeRegistry.
address public cycleChanger;
uint256 public currentCycle;
uint256 public previousCycle;
/// @notice The list of tokens that will be registered next cycle.
/// We only update the shareCount at the change of cycle to
/// prevent the number of shares from changing.
address[] public pendingTokens;
/// @notice The list of tokens which are already registered and rewards can
/// be claimed for.
address[] public registeredTokens;
/// @notice Mapping from token -> index. Index starts from 1. 0 means not in
/// list.
mapping(address => uint256) public registeredTokenIndex;
/// @notice Mapping from token -> amount.
/// The amount of rewards allocated for all darknodes to claim into
/// their account.
mapping(address => uint256) public unclaimedRewards;
/// @notice Mapping from token -> amount.
/// The amount of rewards allocated for each darknode.
mapping(address => uint256) public previousCycleRewardShare;
/// @notice The time that the current cycle started.
uint256 public cycleStartTime;
/// @notice The staged payout percentage to the darknodes per cycle.
uint256 public nextCyclePayoutPercent;
/// @notice The current cycle payout percentage to the darknodes.
uint256 public currentCyclePayoutPercent;
/// @notice Mapping of darknode -> cycle -> already_claimed.
/// Used to keep track of which darknodes have already claimed their
/// rewards.
mapping(address => mapping(uint256 => bool)) public rewardClaimed;
/// @notice Emitted when a darknode claims their share of reward.
/// @param _darknode The darknode which claimed.
/// @param _cycle The cycle that the darknode claimed for.
event LogDarknodeClaim(address indexed _darknode, uint256 _cycle);
/// @notice Emitted when someone pays the DarknodePayment contract.
/// @param _payer The darknode which claimed.
/// @param _amount The cycle that the darknode claimed for.
/// @param _token The address of the token that was transferred.
event LogPaymentReceived(
address indexed _payer,
address indexed _token,
uint256 _amount
);
/// @notice Emitted when a darknode calls withdraw.
/// @param _darknodeOperator The address of the darknode's operator.
/// @param _darknodeID The address of the darknode which withdrew.
/// @param _value The amount of DAI withdrawn.
/// @param _token The address of the token that was withdrawn.
event LogDarknodeWithdrew(
address indexed _darknodeOperator,
address indexed _darknodeID,
address indexed _token,
uint256 _value
);
/// @notice Emitted when the payout percent changes.
/// @param _newPercent The new percent.
/// @param _oldPercent The old percent.
event LogPayoutPercentChanged(uint256 _newPercent, uint256 _oldPercent);
/// @notice Emitted when the CycleChanger address changes.
/// @param _newCycleChanger The new CycleChanger.
/// @param _oldCycleChanger The old CycleChanger.
event LogCycleChangerChanged(
address indexed _newCycleChanger,
address indexed _oldCycleChanger
);
/// @notice Emitted when a new token is registered.
/// @param _token The token that was registered.
event LogTokenRegistered(address indexed _token);
/// @notice Emitted when a token is deregistered.
/// @param _token The token that was deregistered.
event LogTokenDeregistered(address indexed _token);
/// @notice Emitted when the DarknodeRegistry is updated.
/// @param _previousDarknodeRegistry The address of the old registry.
/// @param _nextDarknodeRegistry The address of the new registry.
event LogDarknodeRegistryUpdated(
DarknodeRegistryLogicV1 indexed _previousDarknodeRegistry,
DarknodeRegistryLogicV1 indexed _nextDarknodeRegistry
);
/// @notice Restrict a function registered dark nodes to call a function.
modifier onlyDarknode(address _darknode) {
require(
darknodeRegistry.isRegistered(_darknode),
"DarknodePayment: darknode is not registered"
);
_;
}
/// @notice Restrict a function to have a valid percentage.
modifier validPercent(uint256 _percent) {
require(_percent <= 100, "DarknodePayment: invalid percentage");
_;
}
/// @notice Restrict a function to be called by cycleChanger.
modifier onlyCycleChanger {
require(
msg.sender == cycleChanger,
"DarknodePayment: not cycle changer"
);
_;
}
/// @notice The contract constructor. Starts the current cycle using the
/// time of deploy.
///
/// @param _VERSION A string defining the contract version.
/// @param _darknodeRegistry The address of the DarknodeRegistry contract.
/// @param _darknodePaymentStore The address of the DarknodePaymentStore
/// contract.
constructor(
string memory _VERSION,
DarknodeRegistryLogicV1 _darknodeRegistry,
DarknodePaymentStore _darknodePaymentStore,
uint256 _cyclePayoutPercent
) public validPercent(_cyclePayoutPercent) {
Claimable.initialize(msg.sender);
VERSION = _VERSION;
darknodeRegistry = _darknodeRegistry;
store = _darknodePaymentStore;
nextCyclePayoutPercent = _cyclePayoutPercent;
// Default the cycleChanger to owner.
cycleChanger = msg.sender;
// Start the current cycle
(currentCycle, cycleStartTime) = darknodeRegistry.currentEpoch();
currentCyclePayoutPercent = nextCyclePayoutPercent;
}
/// @notice Allows the contract owner to update the address of the
/// darknode registry contract.
/// @param _darknodeRegistry The address of the Darknode Registry
/// contract.
function updateDarknodeRegistry(DarknodeRegistryLogicV1 _darknodeRegistry)
external
onlyOwner
{
require(
address(_darknodeRegistry) != address(0x0),
"DarknodePayment: invalid Darknode Registry address"
);
DarknodeRegistryLogicV1 previousDarknodeRegistry = darknodeRegistry;
darknodeRegistry = _darknodeRegistry;
emit LogDarknodeRegistryUpdated(
previousDarknodeRegistry,
darknodeRegistry
);
}
/// @notice Transfers the funds allocated to the darknode to the darknode
/// owner.
///
/// @param _darknode The address of the darknode.
/// @param _token Which token to transfer.
function withdraw(address _darknode, address _token) public {
address payable darknodeOperator =
darknodeRegistry.getDarknodeOperator(_darknode);
require(
darknodeOperator != address(0x0),
"DarknodePayment: invalid darknode owner"
);
uint256 amount = store.darknodeBalances(_darknode, _token);
// Skip if amount is zero.
if (amount > 0) {
store.transfer(_darknode, _token, amount, darknodeOperator);
emit LogDarknodeWithdrew(
darknodeOperator,
_darknode,
_token,
amount
);
}
}
function withdrawMultiple(
address[] calldata _darknodes,
address[] calldata _tokens
) external {
for (uint256 i = 0; i < _darknodes.length; i++) {
for (uint256 j = 0; j < _tokens.length; j++) {
withdraw(_darknodes[i], _tokens[j]);
}
}
}
/// @notice Forward all payments to the DarknodePaymentStore.
function() external payable {
address(store).transfer(msg.value);
emit LogPaymentReceived(msg.sender, ETHEREUM, msg.value);
}
/// @notice The current balance of the contract available as reward for the
/// current cycle.
function currentCycleRewardPool(address _token)
external
view
returns (uint256)
{
uint256 total =
store.availableBalance(_token).sub(
unclaimedRewards[_token],
"DarknodePayment: unclaimed rewards exceed total rewards"
);
return total.div(100).mul(currentCyclePayoutPercent);
}
function darknodeBalances(address _darknodeID, address _token)
external
view
returns (uint256)
{
return store.darknodeBalances(_darknodeID, _token);
}
/// @notice Changes the current cycle.
function changeCycle() external onlyCycleChanger returns (uint256) {
// Snapshot balances for the past cycle.
uint256 arrayLength = registeredTokens.length;
for (uint256 i = 0; i < arrayLength; i++) {
_snapshotBalance(registeredTokens[i]);
}
// Start a new cycle.
previousCycle = currentCycle;
(currentCycle, cycleStartTime) = darknodeRegistry.currentEpoch();
currentCyclePayoutPercent = nextCyclePayoutPercent;
// Update the list of registeredTokens.
_updateTokenList();
return currentCycle;
}
/// @notice Deposits token into the contract to be paid to the Darknodes.
///
/// @param _value The amount of token deposit in the token's smallest unit.
/// @param _token The token address.
function deposit(uint256 _value, address _token) external payable {
uint256 receivedValue;
if (_token == ETHEREUM) {
require(
_value == msg.value,
"DarknodePayment: mismatched deposit value"
);
receivedValue = msg.value;
address(store).transfer(msg.value);
} else {
require(
msg.value == 0,
"DarknodePayment: unexpected ether transfer"
);
require(
registeredTokenIndex[_token] != 0,
"DarknodePayment: token not registered"
);
// Forward the funds to the store.
receivedValue = ERC20(_token).safeTransferFromWithFees(
msg.sender,
address(store),
_value
);
}
emit LogPaymentReceived(msg.sender, _token, receivedValue);
}
/// @notice Forwards any tokens that have been sent to the DarknodePayment contract
/// probably by mistake, to the DarknodePaymentStore.
///
/// @param _token The token address.
function forward(address _token) external {
if (_token == ETHEREUM) {
// Its unlikely that ETH will need to be forwarded, but it is
// possible. For example - if ETH had already been sent to the
// contract's address before it was deployed, or if funds are sent
// to it as part of a contract's self-destruct.
address(store).transfer(address(this).balance);
} else {
ERC20(_token).safeTransfer(
address(store),
ERC20(_token).balanceOf(address(this))
);
}
}
/// @notice Claims the rewards allocated to the darknode last epoch.
/// @param _darknode The address of the darknode to claim.
function claim(address _darknode) external onlyDarknode(_darknode) {
require(
darknodeRegistry.isRegisteredInPreviousEpoch(_darknode),
"DarknodePayment: cannot claim for this epoch"
);
// Claim share of rewards allocated for last cycle.
_claimDarknodeReward(_darknode);
emit LogDarknodeClaim(_darknode, previousCycle);
}
/// @notice Adds tokens to be payable. Registration is pending until next
/// cycle.
///
/// @param _token The address of the token to be registered.
function registerToken(address _token) external onlyOwner {
require(
registeredTokenIndex[_token] == 0,
"DarknodePayment: token already registered"
);
require(
!tokenPendingRegistration(_token),
"DarknodePayment: token already pending registration"
);
pendingTokens.push(_token);
}
function tokenPendingRegistration(address _token)
public
view
returns (bool)
{
uint256 arrayLength = pendingTokens.length;
for (uint256 i = 0; i < arrayLength; i++) {
if (pendingTokens[i] == _token) {
return true;
}
}
return false;
}
/// @notice Removes a token from the list of supported tokens.
/// Deregistration is pending until next cycle.
///
/// @param _token The address of the token to be deregistered.
function deregisterToken(address _token) external onlyOwner {
require(
registeredTokenIndex[_token] > 0,
"DarknodePayment: token not registered"
);
_deregisterToken(_token);
}
/// @notice Updates the CycleChanger contract address.
///
/// @param _addr The new CycleChanger contract address.
function updateCycleChanger(address _addr) external onlyOwner {
require(
_addr != address(0),
"DarknodePayment: invalid contract address"
);
emit LogCycleChangerChanged(_addr, cycleChanger);
cycleChanger = _addr;
}
/// @notice Updates payout percentage.
///
/// @param _percent The percentage of payout for darknodes.
function updatePayoutPercentage(uint256 _percent)
external
onlyOwner
validPercent(_percent)
{
uint256 oldPayoutPercent = nextCyclePayoutPercent;
nextCyclePayoutPercent = _percent;
emit LogPayoutPercentChanged(nextCyclePayoutPercent, oldPayoutPercent);
}
/// @notice Allows the contract owner to initiate an ownership transfer of
/// the DarknodePaymentStore.
///
/// @param _newOwner The address to transfer the ownership to.
function transferStoreOwnership(DarknodePayment _newOwner)
external
onlyOwner
{
store.transferOwnership(address(_newOwner));
_newOwner.claimStoreOwnership();
}
/// @notice Claims ownership of the store passed in to the constructor.
/// `transferStoreOwnership` must have previously been called when
/// transferring from another DarknodePaymentStore.
function claimStoreOwnership() external {
store.claimOwnership();
}
/// @notice Claims the darknode reward for all registered tokens into
/// darknodeBalances in the DarknodePaymentStore.
/// Rewards can only be claimed once per cycle.
///
/// @param _darknode The address to the darknode to claim rewards for.
function _claimDarknodeReward(address _darknode) private {
require(
!rewardClaimed[_darknode][previousCycle],
"DarknodePayment: reward already claimed"
);
rewardClaimed[_darknode][previousCycle] = true;
uint256 arrayLength = registeredTokens.length;
for (uint256 i = 0; i < arrayLength; i++) {
address token = registeredTokens[i];
// Only increment balance if shares were allocated last cycle
if (previousCycleRewardShare[token] > 0) {
unclaimedRewards[token] = unclaimedRewards[token].sub(
previousCycleRewardShare[token],
"DarknodePayment: share exceeds unclaimed rewards"
);
store.incrementDarknodeBalance(
_darknode,
token,
previousCycleRewardShare[token]
);
}
}
}
/// @notice Snapshots the current balance of the tokens, for all registered
/// tokens.
///
/// @param _token The address the token to snapshot.
function _snapshotBalance(address _token) private {
uint256 shareCount = darknodeRegistry.numDarknodesPreviousEpoch();
if (shareCount == 0) {
unclaimedRewards[_token] = 0;
previousCycleRewardShare[_token] = 0;
} else {
// Lock up the current balance for darknode reward allocation
uint256 total = store.availableBalance(_token);
unclaimedRewards[_token] = total.div(100).mul(
currentCyclePayoutPercent
);
previousCycleRewardShare[_token] = unclaimedRewards[_token].div(
shareCount
);
}
}
/// @notice Deregisters a token, removing it from the list of
/// registeredTokens.
///
/// @param _token The address of the token to deregister.
function _deregisterToken(address _token) private {
address lastToken =
registeredTokens[
registeredTokens.length.sub(
1,
"DarknodePayment: no tokens registered"
)
];
uint256 deletedTokenIndex = registeredTokenIndex[_token].sub(1);
// Move the last token to _token's position and update it's index
registeredTokens[deletedTokenIndex] = lastToken;
registeredTokenIndex[lastToken] = registeredTokenIndex[_token];
// Decreasing the length will clean up the storage for us
// So we don't need to manually delete the element
registeredTokens.pop();
registeredTokenIndex[_token] = 0;
emit LogTokenDeregistered(_token);
}
/// @notice Updates the list of registeredTokens adding tokens that are to be registered.
/// The list of tokens that are pending registration are emptied afterwards.
function _updateTokenList() private {
// Register tokens
uint256 arrayLength = pendingTokens.length;
for (uint256 i = 0; i < arrayLength; i++) {
address token = pendingTokens[i];
registeredTokens.push(token);
registeredTokenIndex[token] = registeredTokens.length;
emit LogTokenRegistered(token);
}
pendingTokens.length = 0;
}
}
|
Forward all payments to the DarknodePaymentStore.
|
function() external payable {
address(store).transfer(msg.value);
emit LogPaymentReceived(msg.sender, ETHEREUM, msg.value);
}
| 2,493,865 |
./full_match/56/0x4d2FA1E81661ecaF1FABdB9FF08c582F1ACEf003/sources/contracts/Token.sol
|
Get total supply excluding burned amount/
|
function totalSupplyIncludingBurnAmount() public view returns (uint256) {
return _totalSupply;
}
| 3,254,995 |
./partial_match/1/0xB690fC16279C096999264e3C049fA133024b4d69/sources/contracts/broadcast/DynamicBlueprintsBroadcast.sol
|
Lets user emit signed intents to apply expansion items to their Dynamic Blueprint NFTs intentFile File of signed intent/
|
function applyItems(string memory intentFile) external {
emit Intent(intentFile, msg.sender);
}
| 3,599,341 |
pragma solidity 0.5.7;
/* required for transpiler */
#define TRANSPILE
/* data constants */
#define WORD_0 0 /* 32*0 = 0 */
#define WORD_1 32 /* 32*1 = 32 */
#define WORD_2 64 /* 32*2 = 64 */
#define WORD_3 96 /* 32*3 = 96 */
#define WORD_4 128 /* 32*4 = 128 */
#define WORD_5 160 /* 32*5 = 160 */
#define WORD_6 192 /* 32*6 = 192 */
#define WORD_7 224 /* 32*7 = 224 */
#define WORD_8 256 /* 32*8 = 256 */
#define WORD_9 288 /* 32*9 = 288 */
#define WORD_10 320 /* 32*10 = 320 */
#define WORD_11 352 /* 32*11 = 352 */
#define WORD_12 384 /* 32*12 = 384 */
#define WORD_13 416 /* 32*13 = 416 */
#define WORD_14 448 /* 32*14 = 448 */
#define U64_MASK 0xFFFFFFFFFFFFFFFF
#define U64_MAX 0xFFFFFFFFFFFFFFFF
#define I64_MAX 0x7FFFFFFFFFFFFFFF
#define I64_MIN 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8000000000000000
#define U256_MAX 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
#define MIN_UNLOCK_AT 28800 /* 8 hours in seconds */
#define MAX_UNLOCK_AT 1209600 /* 14 days in seconds */
#define TWO_HOURS 7200 /* 2 hours in seconds */
#define TWO_DAYS 172800 /* 2 days in seconds */
#define PRICE_UNITS 100000000
/*
* Resolves to 1 if number cannot fit in i64.
*
* Valid range for i64 [-2^63, 2^64-1]
* = [ -9,223,372,036,854,775,808, 9,223,372,036,854,775,807 ]
* = (64 bit) [ 0x8000000000000000, 0x7fffffffffffffff ]
* = (256 bit) = [ 0xffffffffffffffffffffffffffffffffffffffffffffffff8000000000000000, 0x7fffffffffffffff ]
*/
contract DCN {
event UserCreated(address indexed creator, uint64 user_id);
event UserTradeAddressUpdated(uint64 user_id);
event SessionUpdated(uint64 user_id, uint64 exchange_id);
event ExchangeDeposit(uint64 user_id, uint64 exchange_id, uint32 asset_id);
/* address allowed to update self and add assets and exchanges */
uint256 creator;
uint256 creator_recovery;
uint256 creator_recovery_proposed;
/* number of users */
uint256 user_count;
/* number of exchanges registered */
uint256 exchange_count;
/* number of assets registered */
uint256 asset_count;
/* used to disable features in case of bug */
uint256 security_locked_features;
uint256 security_locked_features_proposed;
uint256 security_proposed_unlock_timestamp;
/* maximum values */
#define EXCHANGE_COUNT 4294967296 /* 2^32 */
#define ASSET_COUNT 4294967296 /* 2^32 */
#define USER_COUNT 18446744073709551616 /* 2^64 */
#define MARKET_COUNT 18446744073709551616 /* 2^64 (2^32 * 2^32 every asset combination) */
struct Exchange {
/* 11 byte name of the exchange */
uint88 name;
/* prevents exchange from applying settlement groups */
uint8 locked;
/* address used to manage exchange */
address owner;
/* address to withdraw funds */
uint256 withdraw_address;
/* recovery address to change the owner and withdraw address */
uint256 recovery_address;
/* a proposed address to change recovery_address */
uint256 recovery_address_proposed;
/* asset balances (in session balance units) */
uint256[ASSET_COUNT] balances;
}
struct Asset {
/* 8 byte symbol of the asset */
uint64 symbol;
/* used to scale between wallet and state balances */
uint192 unit_scale;
/* address of the ERC-20 Token */
uint256 contract_address;
}
struct MarketState {
/* net quote balance change due to settlements */
int64 quote_qty;
/* net base balance change due to settlements */
int64 base_qty;
/* total fees used */
uint64 fee_used;
/* max value for fee_used */
uint64 fee_limit;
/* min allowed value for min_quote_qty after settlement */
int64 min_quote_qty;
/* min allowed value for min_base_qty after settlement */
int64 min_base_qty;
/* max scaled quote/base ratio when long after settlement */
uint64 long_max_price;
/* min scaled quote/base ratio when short after settlement */
uint64 short_min_price;
/* version to prevent old limits from being set */
uint64 limit_version;
/* how much quote_qty has been shifted by */
int96 quote_shift;
/* how much base_qty has been shifted by */
int96 base_shift;
}
struct SessionBalance {
/* used for exchange to sync balances with DCN (scaled) */
uint128 total_deposit;
/* amount given to user that will be repaid in settlement (scaled) */
uint64 unsettled_withdraw_total;
/* current balance of asset (scaled) */
uint64 asset_balance;
}
struct ExchangeSession {
/* timestamp used to prevent user withdraws and allow settlements */
uint256 unlock_at;
/* address used to interact with session */
uint256 trade_address;
/* user balances locked with the exchange */
SessionBalance[ASSET_COUNT] balances;
/* market states to protect locked balances */
MarketState[MARKET_COUNT] market_states;
}
struct User {
/* address used to sign trading limits */
uint256 trade_address;
/* address used to withdraw funds */
uint256 withdraw_address;
/* address used to update trade_address / withdraw_address */
uint256 recovery_address;
/* proposed address to update recovery_address */
uint256 recovery_address_proposed;
/* balances under the user's control */
uint256[ASSET_COUNT] balances;
/* exchange sessions */
ExchangeSession[EXCHANGE_COUNT] exchange_sessions;
}
User[USER_COUNT] users;
Asset[ASSET_COUNT] assets;
Exchange[EXCHANGE_COUNT] exchanges;
constructor() public {
assembly {
sstore(creator_slot, caller)
sstore(creator_recovery_slot, caller)
}
}
/* utility macros */
#define REVERT(code) \
mstore(WORD_1, code) revert(const_add(WORD_1, 31), 1)
#define DEBUG_REVERT(data) \
mstore(WORD_1, data) revert(WORD_1, WORD_1)
#define INVALID_I64(variable) \
or(slt(variable, I64_MIN), sgt(variable, I64_MAX))
#define MSTORE_STR(MSTORE_VAR, STR_OFFSET, STR_LEN, STR_DATA) \
mstore(MSTORE_VAR, STR_OFFSET) \
mstore(add(MSTORE_VAR, STR_OFFSET), STR_LEN) \
mstore(add(MSTORE_VAR, const_add(STR_OFFSET, WORD_1)), STR_DATA)
#define RETURN_0(VALUE) \
mstore(return_value_mem, VALUE)
#define RETURN(WORD, VALUE) \
mstore(add(return_value_mem, WORD), VALUE)
#define VALID_USER_ID(USER_ID, REVERT_1) \
{ \
let user_count := sload(user_count_slot) \
if iszero(lt(USER_ID, user_count)) { \
REVERT(REVERT_1) \
} \
}
#define VALID_ASSET_ID(asset_id, REVERT_1) \
{ \
let asset_count := sload(asset_count_slot) \
if iszero(lt(asset_id, asset_count)) { \
REVERT(REVERT_1) \
} \
} \
#define VALID_EXCHANGE_ID(EXCHANGE_ID, REVERT_1) \
{ \
let exchange_count := sload(exchange_count_slot) \
if iszero(lt(EXCHANGE_ID, exchange_count)) { \
REVERT(REVERT_1) \
} \
}
/* math macros */
#define CAST_64_NEG(variable) \
variable := signextend(7, variable)
#define CAST_96_NEG(variable) \
variable := signextend(11, variable)
#define U64_OVERFLOW(NUMBER) \
gt(NUMBER, U64_MAX)
/* pointer macros */
#define ASSET_PTR_(ASSET_ID) \
pointer(Asset, assets_slot, ASSET_ID)
#define EXCHANGE_PTR_(EXCHANGE_ID) \
pointer(Exchange, exchanges_slot, EXCHANGE_ID)
#define EXCHANGE_BALANCE_PTR_(EXCHANGE_PTR, ASSET_ID) \
pointer(u256, pointer_attr(Exchange, EXCHANGE_PTR, balances), ASSET_ID)
#define USER_PTR_(USER_ID) \
pointer(User, users_slot, USER_ID)
#define USER_BALANCE_PTR_(USER_PTR, ASSET_ID) \
pointer(u256, pointer_attr(User, USER_PTR, balances), ASSET_ID)
#define SESSION_PTR_(USER_PTR, EXCHANGE_ID) \
pointer(ExchangeSession, pointer_attr(User, USER_PTR, exchange_sessions), EXCHANGE_ID)
#define SESSION_BALANCE_PTR_(SESSION_PTR, ASSET_ID) \
pointer(SessionBalance, pointer_attr(ExchangeSession, SESSION_PTR, balances), ASSET_ID)
#define MARKET_IDX(QUOTE_ASSET_ID, BASE_ASSET_ID) \
or(mul(QUOTE_ASSET_ID, ASSET_COUNT), BASE_ASSET_ID)
#define MARKET_STATE_PTR_(SESSION_PTR, QUOTE_ASSET_ID, BASE_ASSET_ID) \
pointer(MarketState, pointer_attr(ExchangeSession, SESSION_PTR, market_states), MARKET_IDX(QUOTE_ASSET_ID, BASE_ASSET_ID))
/* feature flags to disable functions */
#define FEATURE_ADD_ASSET 0x1
#define FEATURE_ADD_EXCHANGE 0x2
#define FEATURE_CREATE_USER 0x4
#define FEATURE_EXCHANGE_DEPOSIT 0x8
#define FEATURE_USER_DEPOSIT 0x10
#define FEATURE_TRANSFER_TO_SESSION 0x20
#define FEATURE_DEPOSIT_ASSET_TO_SESSION 0x40
#define FEATURE_EXCHANGE_TRANSFER_FROM 0x80
#define FEATURE_EXCHANGE_SET_LIMITS 0x100
#define FEATURE_APPLY_SETTLEMENT_GROUPS 0x200
#define FEATURE_USER_MARKET_RESET 0x400
#define FEATURE_RECOVER_UNSETTLED_WITHDRAWS 0x800
#define FEATURE_ALL U256_MAX
#define SECURITY_FEATURE_CHECK(FEATURE, REVERT_1) \
{ \
let locked_features := sload(security_locked_features_slot) \
if and(locked_features, FEATURE) { REVERT(REVERT_1) } \
}
/* ERC_20 */
#define ERC_20_SEND(TOKEN_ADDRESS, TO_ADDRESS, AMOUNT, REVERT_1, REVERT_2) \
mstore(transfer_in_mem, fn_hash("transfer(address,uint256)")) \
mstore(add(transfer_in_mem, 4), TO_ADDRESS) \
mstore(add(transfer_in_mem, 36), AMOUNT) \
/* call external contract */ \
{ \
let success := call( \
gas, \
TOKEN_ADDRESS, \
/* don't send any ether */ 0, \
transfer_in_mem, \
/* transfer_in_mem size (bytes) */ 68, \
transfer_out_mem, \
/* transfer_out_mem size (bytes) */ 32 \
) \
\
if iszero(success) { \
REVERT(REVERT_1) \
} \
\
switch returndatasize() \
/* invalid ERC-20 Token, doesn't return anything and didn't revert: success */ \
case 0 { } \
/* valid ERC-20 Token, has return value */ \
case 32 { \
let result := mload(transfer_out_mem) \
if iszero(result) { \
REVERT(REVERT_2) \
} \
} \
/* returned a non standard amount of data: fail */ \
default { \
REVERT(REVERT_2) \
} \
}
#define ERC_20_DEPOSIT(TOKEN_ADDRESS, FROM_ADDRESS, TO_ADDRESS, AMOUNT, REVERT_1, REVERT_2) \
mstore(transfer_in_mem, /* transferFrom(address,address,uint256) */ fn_hash("transferFrom(address,address,uint256)")) \
mstore(add(transfer_in_mem, 4), FROM_ADDRESS) \
mstore(add(transfer_in_mem, 36), TO_ADDRESS) \
mstore(add(transfer_in_mem, 68), AMOUNT) \
/* call external contract */ \
{ \
let success := call( \
gas, \
TOKEN_ADDRESS, \
/* don't send any ether */ 0, \
transfer_in_mem, \
/* transfer_in_mem size (bytes) */ 100, \
transfer_out_mem, \
/* transfer_out_mem size (bytes) */ 32 \
) \
if iszero(success) { \
REVERT(REVERT_1) \
} \
switch returndatasize() \
/* invalid ERC-20 Token, doesn't return anything and didn't revert: success */ \
case 0 { } \
/* valid ERC-20 Token, has return value */ \
case 32 { \
let result := mload(transfer_out_mem) \
if iszero(result) { \
REVERT(REVERT_2) \
} \
} \
/* returned a non standard amount of data: fail */ \
default { \
REVERT(REVERT_2) \
} \
}
function get_security_state() public view
returns (uint256 locked_features, uint256 locked_features_proposed, uint256 proposed_unlock_timestamp) {
uint256[3] memory return_value_mem;
assembly {
RETURN_0(sload(security_locked_features_slot))
RETURN(WORD_1, sload(security_locked_features_proposed_slot))
RETURN(WORD_2, sload(security_proposed_unlock_timestamp_slot))
return(return_value_mem, WORD_3)
}
}
function get_creator() public view
returns (address dcn_creator, address dcn_creator_recovery, address dcn_creator_recovery_proposed) {
uint256[3] memory return_value_mem;
assembly {
RETURN_0(sload(creator_slot))
RETURN(WORD_1, sload(creator_recovery_slot))
RETURN(WORD_2, sload(creator_recovery_proposed_slot))
return(return_value_mem, WORD_3)
}
}
function get_asset(uint32 asset_id) public view
returns (string memory symbol, uint192 unit_scale, address contract_address) {
uint256[5] memory return_value_mem;
assembly {
let asset_count := sload(asset_count_slot)
if iszero(lt(asset_id, asset_count)) {
REVERT(1)
}
let asset_ptr := ASSET_PTR_(asset_id)
let asset_0 := sload(asset_ptr)
let asset_1 := sload(add(asset_ptr, 1))
MSTORE_STR(return_value_mem, WORD_3, 8, asset_0)
RETURN(WORD_1, attr(Asset, 0, asset_0, unit_scale))
RETURN(WORD_2, attr(Asset, 1, asset_1, contract_address))
return(return_value_mem, const_add(WORD_3, /* string header */ WORD_1 , /* string data */ 8))
}
}
function get_exchange(uint32 exchange_id) public view
returns (
string memory name, bool locked, address owner,
address withdraw_address, address recovery_address, address recovery_address_proposed
) {
/* [ name_offset, owner, withdraw_address, recovery_address, recovery_address_proposed, name_len, name_data(12) ] */
uint256[8] memory return_value_mem;
assembly {
let exchange_count := sload(exchange_count_slot)
if iszero(lt(exchange_id, exchange_count)) {
REVERT(1)
}
let exchange_ptr := EXCHANGE_PTR_(exchange_id)
let exchange_0 := sload(exchange_ptr)
let exchange_1 := sload(add(exchange_ptr, 1))
let exchange_2 := sload(add(exchange_ptr, 2))
let exchange_3 := sload(add(exchange_ptr, 3))
MSTORE_STR(return_value_mem, WORD_6, 11, exchange_0)
RETURN(WORD_1, attr(Exchange, 0, exchange_0, locked))
RETURN(WORD_2, attr(Exchange, 0, exchange_0, owner))
RETURN(WORD_3, attr(Exchange, 1, exchange_1, withdraw_address))
RETURN(WORD_4, attr(Exchange, 2, exchange_2, recovery_address))
RETURN(WORD_5, attr(Exchange, 3, exchange_3, recovery_address_proposed))
return(return_value_mem, const_add(WORD_6, /* string header */ WORD_1, /* string data */ 12))
}
}
function get_exchange_balance(uint32 exchange_id, uint32 asset_id) public view returns (uint256 exchange_balance) {
uint256[1] memory return_value_mem;
assembly {
let exchange_ptr := EXCHANGE_PTR_(exchange_id)
let exchange_balance_ptr := EXCHANGE_BALANCE_PTR_(exchange_ptr, asset_id)
RETURN_0(sload(exchange_balance_ptr))
return(return_value_mem, WORD_1)
}
}
function get_exchange_count() public view returns (uint32 count) {
uint256[1] memory return_value_mem;
assembly {
RETURN_0(sload(exchange_count_slot))
return(return_value_mem, WORD_1)
}
}
function get_asset_count() public view returns (uint32 count) {
uint256[1] memory return_value_mem;
assembly {
RETURN_0(sload(asset_count_slot))
return(return_value_mem, WORD_1)
}
}
function get_user_count() public view returns (uint32 count) {
uint256[1] memory return_value_mem;
assembly {
RETURN_0(sload(user_count_slot))
return(return_value_mem, WORD_1)
}
}
function get_user(uint64 user_id) public view
returns (
address trade_address,
address withdraw_address, address recovery_address, address recovery_address_proposed
) {
uint256[4] memory return_value_mem;
assembly {
let user_count := sload(user_count_slot)
if iszero(lt(user_id, user_count)) {
REVERT(1)
}
let user_ptr := USER_PTR_(user_id)
RETURN_0( sload(pointer_attr(User, user_ptr, trade_address)))
RETURN(WORD_1, sload(pointer_attr(User, user_ptr, withdraw_address)))
RETURN(WORD_2, sload(pointer_attr(User, user_ptr, recovery_address)))
RETURN(WORD_3, sload(pointer_attr(User, user_ptr, recovery_address_proposed)))
return(return_value_mem, WORD_4)
}
}
function get_balance(uint64 user_id, uint32 asset_id) public view returns (uint256 return_balance) {
uint256[1] memory return_value_mem;
assembly {
let user_ptr := USER_PTR_(user_id)
let user_balance_ptr := USER_BALANCE_PTR_(user_ptr, asset_id)
RETURN_0(sload(user_balance_ptr))
return(return_value_mem, WORD_1)
}
}
function get_session(uint64 user_id, uint32 exchange_id) public view
returns (uint256 unlock_at, address trade_address) {
uint256[2] memory return_value_mem;
assembly {
let user_ptr := USER_PTR_(user_id)
let session_ptr := SESSION_PTR_(user_ptr, exchange_id)
RETURN_0(sload(pointer_attr(ExchangeSession, session_ptr, unlock_at)))
RETURN(WORD_1, sload(pointer_attr(ExchangeSession, session_ptr, trade_address)))
return(return_value_mem, WORD_2)
}
}
function get_session_balance(uint64 user_id, uint32 exchange_id, uint32 asset_id) public view
returns (uint128 total_deposit, uint64 unsettled_withdraw_total, uint64 asset_balance) {
uint256[3] memory return_value_mem;
assembly {
let user_ptr := USER_PTR_(user_id)
let session_ptr := SESSION_PTR_(user_ptr, exchange_id)
let session_balance_ptr := SESSION_BALANCE_PTR_(session_ptr, asset_id)
let session_balance_0 := sload(session_balance_ptr)
RETURN_0(attr(SessionBalance, 0, session_balance_0, total_deposit))
RETURN(WORD_1, attr(SessionBalance, 0, session_balance_0, unsettled_withdraw_total))
RETURN(WORD_2, attr(SessionBalance, 0, session_balance_0, asset_balance))
return(return_value_mem, WORD_3)
}
}
function get_market_state(
uint64 user_id, uint32 exchange_id,
uint32 quote_asset_id, uint32 base_asset_id
) public view returns (
int64 quote_qty, int64 base_qty, uint64 fee_used, uint64 fee_limit,
int64 min_quote_qty, int64 min_base_qty, uint64 long_max_price, uint64 short_min_price,
uint64 limit_version, int96 quote_shift, int96 base_shift
) {
uint256[11] memory return_value_mem;
assembly {
/* hack to get around stack depth issues in Solidity */
base_shift := base_asset_id
quote_shift := quote_asset_id
let user_ptr := USER_PTR_(user_id)
let exchange_session_ptr := SESSION_PTR_(user_ptr, exchange_id)
let exchange_state_ptr := MARKET_STATE_PTR_(exchange_session_ptr, quote_shift, base_shift)
let state_data_0 := sload(exchange_state_ptr)
let state_data_1 := sload(add(exchange_state_ptr, 1))
let state_data_2 := sload(add(exchange_state_ptr, 2))
#define RETURN_64NEG(WORD, VALUE) \
{ \
let tmp := VALUE \
CAST_64_NEG(tmp) \
RETURN(WORD, tmp) \
}
#define RETURN_96NEG(WORD, VALUE) \
{ \
let tmp := VALUE \
CAST_96_NEG(tmp) \
RETURN(WORD, tmp) \
}
RETURN_64NEG(WORD_0, attr(MarketState, 0, state_data_0, quote_qty))
RETURN_64NEG(WORD_1, attr(MarketState, 0, state_data_0, base_qty))
RETURN(WORD_2, attr(MarketState, 0, state_data_0, fee_used))
RETURN(WORD_3, attr(MarketState, 0, state_data_0, fee_limit))
RETURN_64NEG(WORD_4, attr(MarketState, 1, state_data_1, min_quote_qty))
RETURN_64NEG(WORD_5, attr(MarketState, 1, state_data_1, min_base_qty))
RETURN(WORD_6, attr(MarketState, 1, state_data_1, long_max_price))
RETURN(WORD_7, attr(MarketState, 1, state_data_1, short_min_price))
RETURN(WORD_8, attr(MarketState, 2, state_data_2, limit_version))
RETURN_96NEG(WORD_9, attr(MarketState, 2, state_data_2, quote_shift))
RETURN_96NEG(WORD_10, attr(MarketState, 2, state_data_2, base_shift))
return(return_value_mem, WORD_11)
}
}
#define CREATOR_REQUIRED(REVERT_1) \
{ \
let creator := sload(creator_slot) \
if iszero(eq(caller, creator)) { \
REVERT(REVERT_1) \
} \
}
/************************************
* Security Feature Lock Management *
*
* Taking a defensive approach, these functions allow
* the creator to turn off DCN functionality. The intent
* is to allow the creator to disable features if an exploit
* or logic issue is found. The creator should not be able to
* restrict a user's ability to withdraw their assets.
*
************************************/
/**
* Security Lock
*
* Sets which features should be locked/disabled.
*
* @param lock_features: bit flags for each feature to be locked
*/
function security_lock(uint256 lock_features) public {
assembly {
CREATOR_REQUIRED(/* REVERT(1) */ 1)
let locked_features := sload(security_locked_features_slot)
sstore(security_locked_features_slot, or(locked_features, lock_features))
/*
* Sets the proposal to block all features. This is done to
* ensure security_set_proposed() does not unlock features.
*/
sstore(security_locked_features_proposed_slot, FEATURE_ALL)
}
}
/**
* Security Propose
*
* Propose which features should be locked. If a feature is unlocked,
* should require a timeout before the proposal can be applied.
*
* @param proposed_locked_features: bit flags for proposal
*/
function security_propose(uint256 proposed_locked_features) public {
assembly {
CREATOR_REQUIRED(/* REVERT(1) */ 1)
/*
* only update security_proposed_unlock_timestamp if
* proposed_locked_features unlocks a new features
*/
/*
* Example: current_proposal = 0b11111111
* proposed_features = 0b00010000
* differences = XOR = 0b11101111
*/
let current_proposal := sload(security_locked_features_proposed_slot)
let proposed_differences := xor(current_proposal, proposed_locked_features)
/*
* proposed_differences will have "1" in feature positions that have changed.
* Want to see if those positions have proposed_locked_features as "0", meaning
* that those features will be unlocked.
*/
let does_unlocks_features := and(proposed_differences,
not(proposed_locked_features))
/* update unlock_timestamp */
if does_unlocks_features {
sstore(security_proposed_unlock_timestamp_slot, add(timestamp, TWO_DAYS))
}
sstore(security_locked_features_proposed_slot, proposed_locked_features)
}
}
/** Security Set Proposed
*
* Applies the proposed security locks if the timestamp is met.
*/
function security_set_proposed() public {
assembly {
CREATOR_REQUIRED(/* REVERT(1) */ 1)
let unlock_timestamp := sload(security_proposed_unlock_timestamp_slot)
if gt(unlock_timestamp, timestamp) {
REVERT(2)
}
sstore(security_locked_features_slot,
sload(security_locked_features_proposed_slot))
}
}
/**********************
* Creator Management *
*
* Allows creator to update keys
*
* creator_update
* caller = recovery address
* updates primary address
* creator_propose_recovery
* caller = recovery address
* sets proposed recovery address
* creator_set_recovery
* caller = proposed recovery address
* sets recovery from proposed
*
* Recovery update is done in these steps to ensure
* value is set to valid address.
*
**********************/
function creator_update(address new_creator) public {
assembly {
let creator_recovery := sload(creator_recovery_slot)
if iszero(eq(caller, creator_recovery)) {
REVERT(1)
}
sstore(creator_slot, new_creator)
}
}
function creator_propose_recovery(address recovery) public {
assembly {
let creator_recovery := sload(creator_recovery_slot)
if iszero(eq(caller, creator_recovery)) {
REVERT(1)
}
sstore(creator_recovery_proposed_slot, recovery)
}
}
function creator_set_recovery() public {
assembly {
let creator_recovery_proposed := sload(creator_recovery_proposed_slot)
if or(iszero(eq(caller, creator_recovery_proposed)), iszero(caller)) {
REVERT(1)
}
sstore(creator_recovery_slot, caller)
sstore(creator_recovery_proposed_slot, 0)
}
}
/**
* Set Exchange Locked
*
* Allows the creator to lock bad acting exchanges.
*
* @param exchange_id
* @param locked: the desired locked state
*/
function set_exchange_locked(uint32 exchange_id, bool locked) public {
assembly {
CREATOR_REQUIRED(/* REVERT(1) */ 1)
VALID_EXCHANGE_ID(exchange_id, /* REVERT(2) */ 2)
let exchange_ptr := EXCHANGE_PTR_(exchange_id)
let exchange_0 := sload(exchange_ptr)
sstore(exchange_ptr, or(
and(mask_out(Exchange, 0, locked), exchange_0),
build(Exchange, 0,
/* name */ 0,
/* locked */ locked)
))
}
}
/**
* User Create
*
* Unrestricted function to create a new user. An event is
* emitted to determine the user_id.
*/
function user_create() public returns (uint64 user_id) {
uint256[2] memory log_data_mem;
assembly {
SECURITY_FEATURE_CHECK(FEATURE_CREATE_USER, /* REVERT(0) */ 0)
user_id := sload(user_count_slot)
if iszero(lt(user_id, USER_COUNT)) {
REVERT(1)
}
/* increase user count */
sstore(user_count_slot, add(user_id, 1))
/* set management addresses */
let user_ptr := USER_PTR_(user_id)
sstore(pointer_attr(User, user_ptr, trade_address), caller)
sstore(pointer_attr(User, user_ptr, withdraw_address), caller)
sstore(pointer_attr(User, user_ptr, recovery_address), caller)
log_event(UserCreated, log_data_mem, caller, user_id)
}
}
/*******************
* User Management *
*
* user_set_trade_address
* caller = recovery_address
* update user's trade address
* user_set_withdraw_address
* caller = recovery_address
* update user's withdraw address
* user_propose_recovery_address
* caller = recovery_address
* propose recovery address
* user_set_recovery_address
* caller = recovery_address_proposed
* set recovery adress from proposed
*
*******************/
function user_set_trade_address(uint64 user_id, address trade_address) public {
uint256[1] memory log_data_mem;
assembly {
let user_ptr := USER_PTR_(user_id)
let recovery_address := sload(pointer_attr(User, user_ptr, recovery_address))
if iszero(eq(caller, recovery_address)) {
REVERT(1)
}
sstore(pointer_attr(User, user_ptr, trade_address),
trade_address)
log_event(UserTradeAddressUpdated, log_data_mem, user_id)
}
}
function user_set_withdraw_address(uint64 user_id, address withdraw_address) public {
assembly {
let user_ptr := USER_PTR_(user_id)
let recovery_address := sload(pointer_attr(User, user_ptr, recovery_address))
if iszero(eq(caller, recovery_address)) {
REVERT(1)
}
sstore(pointer_attr(User, user_ptr, withdraw_address),
withdraw_address)
}
}
function user_propose_recovery_address(uint64 user_id, address proposed) public {
assembly {
let user_ptr := USER_PTR_(user_id)
let recovery_address := sload(pointer_attr(User, user_ptr, recovery_address))
if iszero(eq(caller, recovery_address)) {
REVERT(1)
}
sstore(pointer_attr(User, user_ptr, recovery_address_proposed),
proposed)
}
}
function user_set_recovery_address(uint64 user_id) public {
assembly {
let user_ptr := USER_PTR_(user_id)
let proposed_ptr := pointer_attr(User, user_ptr, recovery_address_proposed)
let recovery_address_proposed := sload(proposed_ptr)
if iszero(eq(caller, recovery_address_proposed)) {
REVERT(1)
}
sstore(proposed_ptr, 0)
sstore(pointer_attr(User, user_ptr, recovery_address),
recovery_address_proposed)
}
}
/***********************
* Exchange Management *
*
* exchange_set_owner
* caller = recovery_address
* set primary address
* exchange_set_withdraw
* caller = recovery_address
* set withdraw address
* exchange_propose_recovery
* caller = recovery_address
* set propose recovery address
* exchange_set_recovery
* caller = recovery_address_proposed
* set recovery_address from proposed
*
***********************/
function exchange_set_owner(uint32 exchange_id, address new_owner) public {
assembly {
let exchange_ptr := EXCHANGE_PTR_(exchange_id)
let exchange_recovery := sload(pointer_attr(Exchange, exchange_ptr, recovery_address))
/* ensure caller is recovery */
if iszero(eq(caller, exchange_recovery)) {
REVERT(1)
}
let exchange_0 := sload(exchange_ptr)
sstore(exchange_ptr, or(
and(exchange_0, mask_out(Exchange, 0, owner)),
build(Exchange, 0,
/* name */ 0,
/* locked */ 0,
/* owner */ new_owner
)
))
}
}
function exchange_set_withdraw(uint32 exchange_id, address new_withdraw) public {
assembly {
let exchange_ptr := EXCHANGE_PTR_(exchange_id)
let exchange_recovery := sload(pointer_attr(Exchange, exchange_ptr, recovery_address))
/* ensure caller is recovery */
if iszero(eq(caller, exchange_recovery)) {
REVERT(1)
}
sstore(pointer_attr(Exchange, exchange_ptr, withdraw_address), new_withdraw)
}
}
function exchange_propose_recovery(uint32 exchange_id, address proposed) public {
assembly {
let exchange_ptr := EXCHANGE_PTR_(exchange_id)
let exchange_recovery := sload(pointer_attr(Exchange, exchange_ptr, recovery_address))
/* ensure caller is proposed */
if iszero(eq(caller, exchange_recovery)) {
REVERT(1)
}
/* update proposed */
sstore(pointer_attr(Exchange, exchange_ptr, recovery_address_proposed),
proposed)
}
}
function exchange_set_recovery(uint32 exchange_id) public {
assembly {
let exchange_ptr := EXCHANGE_PTR_(exchange_id)
let exchange_recovery_proposed := sload(pointer_attr(Exchange, exchange_ptr, recovery_address_proposed))
/* ensure caller is proposed recovery */
if or(iszero(eq(caller, exchange_recovery_proposed)), iszero(caller)) {
REVERT(1)
}
/* update recovery */
sstore(pointer_attr(Exchange, exchange_ptr, recovery_address), caller)
}
}
/**
* Add Asset
*
* caller = creator
* Note, it is possible for two assets to have the same contract_address.
*
* @param symbol: 4 character symbol for asset
* @param unit_scale: (ERC20 balance) = unit_scale * (session balance)
* @param contract_address: address on the ERC20 token
*/
function add_asset(string memory symbol, uint192 unit_scale, address contract_address) public returns (uint64 asset_id) {
assembly {
SECURITY_FEATURE_CHECK(FEATURE_ADD_ASSET, /* REVERT(0) */ 0)
CREATOR_REQUIRED(/* REVERT(1) */ 1)
/* do not want to overflow assets array */
asset_id := sload(asset_count_slot)
if iszero(lt(asset_id, ASSET_COUNT)) {
REVERT(2)
}
/* Symbol must be 8 characters */
let symbol_len := mload(symbol)
if iszero(eq(symbol_len, 8)) {
REVERT(3)
}
/* Unit scale must be non-zero */
if iszero(unit_scale) {
REVERT(4)
}
/* Contract address should be non-zero */
if iszero(contract_address) {
REVERT(5)
}
let asset_symbol := mload(add(symbol, WORD_1 /* offset as first word is size */))
/* Note, symbol is already shifted not setting it in build */
let asset_data_0 := or(asset_symbol, build(Asset, 0, /* symbol */ 0, unit_scale))
let asset_ptr := ASSET_PTR_(asset_id)
sstore(asset_ptr, asset_data_0)
sstore(add(asset_ptr, 1), contract_address)
sstore(asset_count_slot, add(asset_id, 1))
}
}
/**
* Add Exchange
*
* caller = creator
*
* @param name: 11 character name of exchange
* @param addr: address of exchange
*/
function add_exchange(string memory name, address addr) public returns (uint64 exchange_id) {
assembly {
SECURITY_FEATURE_CHECK(FEATURE_ADD_EXCHANGE, /* REVERT(0) */ 0)
CREATOR_REQUIRED(/* REVERT(1) */ 1)
/* Name must be 11 bytes long */
let name_len := mload(name)
if iszero(eq(name_len, 11)) {
REVERT(2)
}
/* Do not overflow exchanges */
exchange_id := sload(exchange_count_slot)
if iszero(lt(exchange_id, EXCHANGE_COUNT)) {
REVERT(3)
}
let exchange_ptr := EXCHANGE_PTR_(exchange_id)
/*
* name is at start of the word. After loading it is already shifted
* so add to it rather than shifting twice with build
*/
let name_data := mload(add(name, WORD_1 /* shift, first word is length */))
let exchange_0 := or(
name_data,
build(Exchange, 0,
/* space for name */ 0,
/* locked */ 0,
/* owner */ addr)
)
sstore(exchange_ptr, exchange_0)
/* Store owner withdraw */
sstore(pointer_attr(Exchange, exchange_ptr, withdraw_address), addr)
/* Store owner recovery */
sstore(pointer_attr(Exchange, exchange_ptr, recovery_address), addr)
/* Update exchange count */
sstore(exchange_count_slot, add(exchange_id, 1))
}
}
/**
* Exchange Withdraw
*
* @param quantity: in session balance units
*/
function exchange_withdraw(uint32 exchange_id, uint32 asset_id,
address destination, uint64 quantity) public {
uint256[3] memory transfer_in_mem;
uint256[1] memory transfer_out_mem;
assembly {
let exchange_ptr := EXCHANGE_PTR_(exchange_id)
/* ensure caller is withdraw_address */
let withdraw_address := sload(pointer_attr(Exchange, exchange_ptr, withdraw_address))
if iszero(eq(caller, withdraw_address)) {
REVERT(1)
}
let exchange_balance_ptr := EXCHANGE_BALANCE_PTR_(exchange_ptr, asset_id)
let exchange_balance := sload(exchange_balance_ptr)
/* insufficient funds */
if gt(quantity, exchange_balance) {
REVERT(2)
}
/* decrement balance */
sstore(exchange_balance_ptr, sub(exchange_balance, quantity))
let asset_ptr := ASSET_PTR_(asset_id)
let unit_scale := attr(Asset, 0, sload(asset_ptr), unit_scale)
let asset_address := sload(pointer_attr(Asset, asset_ptr, contract_address))
let withdraw := mul(quantity, unit_scale)
ERC_20_SEND(
/* TOKEN_ADDRESS */ asset_address,
/* TO_ADDRESS */ destination,
/* AMOUNT */ withdraw,
/* REVERT(3) */ 3,
/* REVERT(4) */ 4
)
}
}
/**
* Exchange Deposit
*
* @param quantity: in session balance units
*/
function exchange_deposit(uint32 exchange_id, uint32 asset_id, uint64 quantity) public {
uint256[3] memory transfer_in_mem;
uint256[1] memory transfer_out_mem;
assembly {
SECURITY_FEATURE_CHECK(FEATURE_EXCHANGE_DEPOSIT, /* REVERT(0) */ 0)
VALID_EXCHANGE_ID(exchange_id, /* REVERT(1) */ 1)
VALID_ASSET_ID(asset_id, /* REVERT(2) */ 2)
let exchange_balance_ptr := EXCHANGE_BALANCE_PTR_(EXCHANGE_PTR_(exchange_id), asset_id)
let exchange_balance := sload(exchange_balance_ptr)
let updated_balance := add(exchange_balance, quantity)
if U64_OVERFLOW(updated_balance) {
REVERT(3)
}
let asset_ptr := ASSET_PTR_(asset_id)
let unit_scale := attr(Asset, 0, sload(asset_ptr), unit_scale)
let asset_address := sload(pointer_attr(Asset, asset_ptr, contract_address))
let deposit := mul(quantity, unit_scale)
sstore(exchange_balance_ptr, updated_balance)
ERC_20_DEPOSIT(
/* TOKEN_ADDRESS */ asset_address,
/* FROM_ADDRESS */ caller,
/* TO_ADDRESS */ address,
/* AMOUNT */ deposit,
/* REVERT(4) */ 4,
/* REVERT(5) */ 5
)
}
}
/**
* User Deposit
*
* Deposit funds in the user's DCN balance
*
* @param amount: in ERC20 balance units
*/
function user_deposit(uint64 user_id, uint32 asset_id, uint256 amount) public {
uint256[4] memory transfer_in_mem;
uint256[1] memory transfer_out_mem;
assembly {
SECURITY_FEATURE_CHECK(FEATURE_USER_DEPOSIT, /* REVERT(0) */ 0)
VALID_USER_ID(user_id, /* REVERT(1) */ 1)
VALID_ASSET_ID(asset_id, /* REVERT(2) */ 2)
if iszero(amount) {
stop()
}
let balance_ptr := USER_BALANCE_PTR_(USER_PTR_(user_id), asset_id)
let current_balance := sload(balance_ptr)
let proposed_balance := add(current_balance, amount)
/* Prevent overflow */
if lt(proposed_balance, current_balance) {
REVERT(3)
}
let asset_address := sload(pointer_attr(Asset, ASSET_PTR_(asset_id), contract_address))
sstore(balance_ptr, proposed_balance)
ERC_20_DEPOSIT(
/* TOKEN_ADDRESS */ asset_address,
/* FROM_ADDRESS */ caller,
/* TO_ADDRESS */ address,
/* AMOUNT */ amount,
/* REVERT(4) */ 4,
/* REVERT(5) */ 5
)
}
}
/**
* User Withdraw
*
* caller = user's withdraw_address
*
* Withdraw from user's DCN balance
*
* @param amount: in ERC20 balance units
*/
function user_withdraw(uint64 user_id, uint32 asset_id, address destination, uint256 amount) public {
uint256[3] memory transfer_in_mem;
uint256[1] memory transfer_out_mem;
assembly {
if iszero(amount) {
stop()
}
VALID_USER_ID(user_id, /* REVERT(6) */ 6)
VALID_ASSET_ID(asset_id, /* REVERT(1) */ 1)
let user_ptr := USER_PTR_(user_id)
let withdraw_address := sload(pointer_attr(User, user_ptr, withdraw_address))
if iszero(eq(caller, withdraw_address)) {
REVERT(2)
}
let balance_ptr := USER_BALANCE_PTR_(user_ptr, asset_id)
let current_balance := sload(balance_ptr)
/* insufficient funds */
if lt(current_balance, amount) {
REVERT(3)
}
sstore(balance_ptr, sub(current_balance, amount))
let asset_address := sload(pointer_attr(Asset, ASSET_PTR_(asset_id), contract_address))
ERC_20_SEND(
/* TOKEN_ADDRESS */ asset_address,
/* TO_ADDRESS */ destination,
/* AMOUNT */ amount,
/* REVERT(4) */ 4,
/* REVERT(5) */ 5
)
}
}
/**
* User Session Set Unlock At
*
* caller = user's trade_address
*
* Update the unlock_at timestamp. Also updates the trade_address
* if the session is expired. Note, the trade_address should not be
* updatable when the session is active.
*/
function user_session_set_unlock_at(uint64 user_id, uint32 exchange_id, uint256 unlock_at) public {
uint256[3] memory log_data_mem;
assembly {
VALID_EXCHANGE_ID(exchange_id, /* REVERT(1) */ 1)
let user_ptr := USER_PTR_(user_id)
let trade_address := sload(pointer_attr(User, user_ptr, trade_address))
if iszero(eq(caller, trade_address)) {
REVERT(2)
}
/* validate time range of unlock_at */
{
let fails_min_time := lt(unlock_at, add(timestamp, MIN_UNLOCK_AT))
let fails_max_time := gt(unlock_at, add(timestamp, MAX_UNLOCK_AT))
if or(fails_min_time, fails_max_time) {
REVERT(3)
}
}
let session_ptr := SESSION_PTR_(user_ptr, exchange_id)
/* only update trade_address when unlocked */
let unlock_at_ptr := pointer_attr(ExchangeSession, session_ptr, unlock_at)
if lt(sload(unlock_at_ptr), timestamp) {
sstore(pointer_attr(ExchangeSession, session_ptr, trade_address), caller)
}
sstore(unlock_at_ptr, unlock_at)
log_event(SessionUpdated, log_data_mem, user_id, exchange_id)
}
}
/**
* User Market Reset
*
* caller = user's trade_address
*
* Allows the user to reset their session with an exchange.
* Only allowed when session in unlocked.
* Persists limit_version to prevent old limits from being applied.
*/
function user_market_reset(uint64 user_id, uint32 exchange_id,
uint32 quote_asset_id, uint32 base_asset_id) public {
assembly {
SECURITY_FEATURE_CHECK(FEATURE_USER_MARKET_RESET, /* REVERT(0) */ 0)
VALID_EXCHANGE_ID(exchange_id, /* REVERT(1) */ 1)
let user_ptr := USER_PTR_(user_id)
let trade_address := sload(pointer_attr(User, user_ptr, trade_address))
if iszero(eq(caller, trade_address)) {
REVERT(2)
}
let session_ptr := SESSION_PTR_(user_ptr, exchange_id)
let unlock_at := sload(pointer_attr(ExchangeSession, session_ptr, unlock_at))
if gt(unlock_at, timestamp) {
REVERT(3)
}
let market_state_ptr := MARKET_STATE_PTR_(session_ptr, quote_asset_id, base_asset_id)
sstore(market_state_ptr, 0)
sstore(add(market_state_ptr, 1), 0)
/* increment limit_version */
let market_state_2_ptr := add(market_state_ptr, 2)
let market_state_2 := sload(market_state_2_ptr)
let limit_version := add(attr(MarketState, 2, market_state_2, limit_version), 1)
sstore(market_state_2_ptr, build(MarketState, 2,
/* limit_version */ limit_version
))
}
}
/**
* Transfer To Session
*
* caller = user's withdraw_address
*
* Transfer funds from DCN balance to trading session
*
* @param quantity: in session balance units
*/
function transfer_to_session(uint64 user_id, uint32 exchange_id, uint32 asset_id, uint64 quantity) public {
uint256[4] memory log_data_mem;
assembly {
SECURITY_FEATURE_CHECK(FEATURE_TRANSFER_TO_SESSION, /* REVERT(0) */ 0)
VALID_EXCHANGE_ID(exchange_id, /* REVERT(1) */ 1)
VALID_ASSET_ID(asset_id, /* REVERT(2) */ 2)
if iszero(quantity) {
stop()
}
let asset_ptr := ASSET_PTR_(asset_id)
let unit_scale := attr(Asset, 0, sload(asset_ptr), unit_scale)
let scaled_quantity := mul(quantity, unit_scale)
let user_ptr := USER_PTR_(user_id)
/* ensure caller is withdraw_address as funds are moving out of DCN account */
{
let withdraw_address := sload(pointer_attr(User, user_ptr, withdraw_address))
if iszero(eq(caller, withdraw_address)) {
REVERT(3)
}
}
let user_balance_ptr := USER_BALANCE_PTR_(user_ptr, asset_id)
let user_balance := sload(user_balance_ptr)
/* insufficient funds */
if lt(user_balance, scaled_quantity) {
REVERT(4)
}
/* load exchange balance */
let session_balance_ptr := SESSION_BALANCE_PTR_(SESSION_PTR_(user_ptr, exchange_id), asset_id)
let session_balance_0 := sload(session_balance_ptr)
let updated_exchange_balance := add(attr(SessionBalance, 0, session_balance_0, asset_balance), quantity)
if U64_OVERFLOW(updated_exchange_balance) {
REVERT(5)
}
/* don't care about overflow for total_deposit, is used by exchange to detect update */
let updated_total_deposit := add(attr(SessionBalance, 0, session_balance_0, total_deposit), quantity)
/* update user balance */
sstore(user_balance_ptr, sub(user_balance, scaled_quantity))
/* update exchange balance */
sstore(session_balance_ptr, or(
and(mask_out(SessionBalance, 0, total_deposit, asset_balance), session_balance_0),
build(SessionBalance, 0,
/* total_deposit */ updated_total_deposit,
/* unsettled_withdraw_total */ 0,
/* asset_balance */ updated_exchange_balance)
))
log_event(ExchangeDeposit, log_data_mem, user_id, exchange_id, asset_id)
}
}
/**
* Transfer From Session
*
* caller = user's trade_address
*
* When session is unlocked, allow transfer funds from trading session to DCN balance.
*
* @param quantity: in session balance units
*/
function transfer_from_session(uint64 user_id, uint32 exchange_id, uint32 asset_id, uint64 quantity) public {
uint256[4] memory log_data_mem;
assembly {
if iszero(quantity) {
stop()
}
VALID_EXCHANGE_ID(exchange_id, /* REVERT(1) */ 1)
VALID_ASSET_ID(asset_id, /* REVERT(2) */ 2)
let user_ptr := USER_PTR_(user_id)
{
let trade_address := sload(pointer_attr(User, user_ptr, trade_address))
if iszero(eq(caller, trade_address)) {
REVERT(3)
}
}
let session_ptr := SESSION_PTR_(user_ptr, exchange_id)
/* ensure session in unlocked */
{
let session_0 := sload(session_ptr)
let unlock_at := attr(ExchangeSession, 0, session_0, unlock_at)
if gt(unlock_at, timestamp) {
REVERT(4)
}
}
/* load exchange balance */
let session_balance_ptr := SESSION_BALANCE_PTR_(session_ptr, asset_id)
let session_balance_0 := sload(session_balance_ptr)
let session_balance := attr(SessionBalance, 0, session_balance_0, asset_balance)
/* insufficient funds */
if gt(quantity, session_balance) {
REVERT(5)
}
let updated_exchange_balance := sub(session_balance, quantity)
let unsettled_withdraw_total := attr(SessionBalance, 0, session_balance_0, unsettled_withdraw_total)
/* do not let user withdraw money owed to the exchange */
if lt(updated_exchange_balance, unsettled_withdraw_total) {
REVERT(6)
}
sstore(session_balance_ptr, or(
and(mask_out(SessionBalance, 0, asset_balance), session_balance_0),
build(SessionBalance, 0,
/* total_deposit */ 0,
/* unsettled_withdraw_total */ 0,
/* asset_balance */ updated_exchange_balance)
))
let asset_ptr := ASSET_PTR_(asset_id)
let unit_scale := attr(Asset, 0, sload(asset_ptr), unit_scale)
let scaled_quantity := mul(quantity, unit_scale)
let user_balance_ptr := USER_BALANCE_PTR_(user_ptr, asset_id)
let user_balance := sload(user_balance_ptr)
let updated_user_balance := add(user_balance, scaled_quantity)
/* protect against addition overflow */
if lt(updated_user_balance, user_balance) {
REVERT(7)
}
sstore(user_balance_ptr, updated_user_balance)
}
}
/**
* User Deposit To Session
*
* Deposits funds directly into a trading session with an exchange.
*
* @param quantity: in session balance units
*/
function user_deposit_to_session(uint64 user_id, uint32 exchange_id, uint32 asset_id, uint64 quantity) public {
uint256[4] memory transfer_in_mem;
uint256[1] memory transfer_out_mem;
uint256[3] memory log_data_mem;
assembly {
SECURITY_FEATURE_CHECK(FEATURE_DEPOSIT_ASSET_TO_SESSION, /* REVERT(0) */ 0)
VALID_EXCHANGE_ID(exchange_id, /* REVERT(1) */ 1)
VALID_ASSET_ID(asset_id, /* REVERT(2) */ 2)
if iszero(quantity) {
stop()
}
let session_balance_ptr := SESSION_BALANCE_PTR_(SESSION_PTR_(USER_PTR_(user_id), exchange_id), asset_id)
let session_balance_0 := sload(session_balance_ptr)
let updated_exchange_balance := add(attr(SessionBalance, 0, session_balance_0, asset_balance), quantity)
if U64_OVERFLOW(updated_exchange_balance) {
REVERT(3)
}
let asset_ptr := ASSET_PTR_(asset_id)
let unit_scale := attr(Asset, 0, sload(asset_ptr), unit_scale)
let asset_address := sload(pointer_attr(Asset, asset_ptr, contract_address))
let scaled_quantity := mul(quantity, unit_scale)
let updated_total_deposit := add(attr(SessionBalance, 0, session_balance_0, total_deposit), quantity)
/* update exchange balance */
sstore(session_balance_ptr, or(
and(mask_out(SessionBalance, 0, total_deposit, asset_balance), session_balance_0),
build(SessionBalance, 0,
/* total_deposit */ updated_total_deposit,
/* unsettled_withdraw_total */ 0,
/* asset_balance */ updated_exchange_balance)
))
ERC_20_DEPOSIT(
/* TOKEN_ADDRESS */ asset_address,
/* FROM_ADDRESS */ caller,
/* TO_ADDRESS */ address,
/* AMOUNT */ scaled_quantity,
/* REVERT(4) */ 4,
/* REVERT(5) */ 5
)
log_event(ExchangeDeposit, log_data_mem, user_id, exchange_id, asset_id)
}
}
struct UnsettledWithdrawHeader {
uint32 exchange_id;
uint32 asset_id;
uint32 user_count;
}
struct UnsettledWithdrawUser {
uint64 user_id;
}
/**
* Recover Unsettled Withdraws
*
* exchange_transfer_from allows users to pull unsettled
* funds from the exchange's balance. This is tracked by
* unsettled_withdraw_total in SessionBalance. This function
* returns funds to the Exchange.
*
* @param data, a binary payload
* - UnsettledWithdrawHeader
* - 1st UnsettledWithdrawUser
* - 2nd UnsettledWithdrawUser
* - ...
* - (UnsettledWithdrawHeader.user_count)th UnsettledWithdrawUser
*/
function recover_unsettled_withdraws(bytes memory data) public {
assembly {
SECURITY_FEATURE_CHECK(FEATURE_RECOVER_UNSETTLED_WITHDRAWS, /* REVERT(0) */ 0)
let data_len := mload(data)
let cursor := add(data, WORD_1)
let cursor_end := add(cursor, data_len)
for {} lt(cursor, cursor_end) {} {
let unsettled_withdraw_header_0 := mload(cursor)
let exchange_id := attr(UnsettledWithdrawHeader, 0, unsettled_withdraw_header_0, exchange_id)
let asset_id := attr(UnsettledWithdrawHeader, 0, unsettled_withdraw_header_0, asset_id)
let user_count := attr(UnsettledWithdrawHeader, 0, unsettled_withdraw_header_0, user_count)
let group_end := add(
cursor, add(
sizeof(UnsettledWithdrawHeader),
mul(user_count, sizeof(UnsettledWithdrawUser))
))
if gt(group_end, cursor_end) {
REVERT(1)
}
let exchange_balance_ptr := EXCHANGE_BALANCE_PTR_(EXCHANGE_PTR_(exchange_id), asset_id)
let exchange_balance := sload(exchange_balance_ptr)
let start_exchange_balance := exchange_balance
for {} lt(cursor, group_end) { cursor := add(cursor, sizeof(UnsettledWithdrawUser)) } {
let user_id := attr(UnsettledWithdrawUser, 0, mload(cursor), user_id)
let session_balance_ptr := SESSION_BALANCE_PTR_(SESSION_PTR_(USER_PTR_(user_id), exchange_id), asset_id)
let session_balance_0 := sload(session_balance_ptr)
let asset_balance := attr(SessionBalance, 0, session_balance_0, asset_balance)
let unsettled_balance := attr(SessionBalance, 0, session_balance_0, unsettled_withdraw_total)
let to_recover := unsettled_balance
if gt(to_recover, asset_balance) {
to_recover := asset_balance
}
/* non zero */
if to_recover {
exchange_balance := add(exchange_balance, to_recover)
asset_balance := sub(asset_balance, to_recover)
unsettled_balance := sub(unsettled_balance, to_recover)
/* ensure exchange_balance doesn't overflow */
if gt(start_exchange_balance, exchange_balance) {
REVERT(2)
}
sstore(session_balance_ptr, or(
and(mask_out(SessionBalance, 0, unsettled_withdraw_total, asset_balance), session_balance_0),
build(
SessionBalance, 0,
/* total_deposit */ 0,
/* unsettled_withdraw_total */ unsettled_balance,
/* asset_balance */ asset_balance)
))
}
}
sstore(exchange_balance_ptr, exchange_balance)
}
}
}
struct ExchangeTransfersHeader {
uint32 exchange_id;
}
struct ExchangeTransferGroup {
uint32 asset_id;
uint8 allow_overdraft;
uint8 transfer_count;
}
struct ExchangeTransfer {
uint64 user_id;
uint64 quantity;
}
#define CURSOR_LOAD(TYPE, REVERT_1) \
mload(cursor) \
cursor := add(cursor, sizeof(TYPE)) \
if gt(cursor, cursor_end) { \
REVERT(REVERT_1) \
}
/**
* Exchange Transfer From
*
* caller = exchange owner
*
* Gives the exchange the ability to move funds from a user's
* trading session into the user's DCN balance. This should be
* the only way funds can be withdrawn from a trading session
* while it is locked.
*
* Exchange has the option to allow_overdraft. If the user's
* balance in the tradng_session is not enough to cover the
* target withdraw quantity, the exchange's funds will be used.
* These funds can be repaid with a call to recover_unsettled_withdraws.
*
* @param data, a binary payload
* - ExchangeTransfersHeader
* - 1st ExchangeTransferGroup
* - 1st ExchangeTransfer
* - 2nd ExchangeTransfer
* - ...
* - (ExchangeTransferGroup.transfer_count)th ExchangeTransfer
* - 2nd ExchangeTransferGroup
* - 1st ExchangeTransfer
* - 2nd ExchangeTransfer
* - ...
* - (ExchangeTransferGroup.transfer_count)th ExchangeTransfer
* - ...
*/
function exchange_transfer_from(bytes memory data) public {
assembly {
SECURITY_FEATURE_CHECK(FEATURE_EXCHANGE_TRANSFER_FROM, /* REVERT(0) */ 0)
let data_len := mload(data)
let cursor := add(data, WORD_1)
let cursor_end := add(cursor, data_len)
/* load exchange_id */
let header_0 := CURSOR_LOAD(ExchangeTransfersHeader, /* REVERT(1) */ 1)
let exchange_id := attr(ExchangeTransfersHeader, 0, header_0, exchange_id)
VALID_EXCHANGE_ID(exchange_id, /* REVERT(2) */ 2)
{
/* ensure exchange is caller */
let exchange_data := sload(EXCHANGE_PTR_(exchange_id))
if iszero(eq(caller, attr(Exchange, 0, exchange_data, owner))) {
REVERT(3)
}
/* ensure exchange is not locked */
if attr(Exchange, 0, exchange_data, locked) {
REVERT(4)
}
}
let asset_count := sload(asset_count_slot)
for {} lt(cursor, cursor_end) {} {
let group_0 := CURSOR_LOAD(ExchangeTransferGroup, /* REVERT(5) */ 5)
let asset_id := attr(ExchangeTransferGroup, 0, group_0, asset_id)
/* Validate asset id */
if iszero(lt(asset_id, asset_count)) {
REVERT(6)
}
let disallow_overdraft := iszero(attr(ExchangeTransferGroup, 0, group_0, allow_overdraft))
let cursor_group_end := add(cursor, mul(
attr(ExchangeTransferGroup, 0, group_0, transfer_count),
sizeof(ExchangeTransfer)
))
/* ensure data fits in input */
if gt(cursor_group_end, cursor_end) {
REVERT(7)
}
let exchange_balance_ptr := EXCHANGE_BALANCE_PTR_(EXCHANGE_PTR_(exchange_id), asset_id)
let exchange_balance_remaining := sload(exchange_balance_ptr)
let unit_scale := attr(Asset, 0, sload(ASSET_PTR_(asset_id)), unit_scale)
for {} lt(cursor, cursor_group_end) { cursor := add(cursor, sizeof(ExchangeTransfer)) } {
let transfer_0 := mload(cursor)
let user_ptr := USER_PTR_(attr(ExchangeTransfer, 0, transfer_0, user_id))
let quantity := attr(ExchangeTransfer, 0, transfer_0, quantity)
let exchange_balance_used := 0
let session_balance_ptr := SESSION_BALANCE_PTR_(SESSION_PTR_(user_ptr, exchange_id), asset_id)
let session_balance_0 := sload(session_balance_ptr)
let session_balance := attr(SessionBalance, 0, session_balance_0, asset_balance)
let session_balance_updated := sub(session_balance, quantity)
/*
* check for underflow (quantity > user_exchange_balance),
* then need to dip into exchange_balance_remaining if user_exchange_balance isn't enough
*/
if gt(session_balance_updated, session_balance) {
if disallow_overdraft {
REVERT(8)
}
exchange_balance_used := sub(quantity, session_balance)
session_balance_updated := 0
if gt(exchange_balance_used, exchange_balance_remaining) {
REVERT(9)
}
exchange_balance_remaining := sub(exchange_balance_remaining, exchange_balance_used)
}
let quantity_scaled := mul(quantity, unit_scale)
let user_balance_ptr := USER_BALANCE_PTR_(user_ptr, asset_id)
let user_balance := sload(user_balance_ptr)
let updated_user_balance := add(user_balance, quantity_scaled)
/* prevent overflow */
if gt(user_balance, updated_user_balance) {
REVERT(10)
}
let unsettled_withdraw_total_updated := add(
attr(SessionBalance, 0, session_balance_0, unsettled_withdraw_total),
exchange_balance_used
)
/* prevent overflow */
if gt(unsettled_withdraw_total_updated, U64_MAX) {
REVERT(11)
}
sstore(session_balance_ptr, or(
and(mask_out(SessionBalance, 0, unsettled_withdraw_total, asset_balance), session_balance_0),
build(SessionBalance, 0,
/* total_deposit */ 0,
/* unsettled_withdraw_total */ unsettled_withdraw_total_updated,
/* asset_balance */ session_balance_updated)
))
sstore(user_balance_ptr, updated_user_balance)
}
sstore(exchange_balance_ptr, exchange_balance_remaining)
}
}
}
struct SetLimitsHeader {
uint32 exchange_id;
}
struct Signature {
uint256 sig_r;
uint256 sig_s;
uint8 sig_v;
}
struct UpdateLimit {
uint32 dcn_id;
uint64 user_id;
uint32 exchange_id;
uint32 quote_asset_id;
uint32 base_asset_id;
uint64 fee_limit;
int64 min_quote_qty;
int64 min_base_qty;
uint64 long_max_price;
uint64 short_min_price;
uint64 limit_version;
uint96 quote_shift;
uint96 base_shift;
}
#define UPDATE_LIMIT_BYTES const_add(sizeof(UpdateLimit), sizeof(Signature))
#define SIG_HASH_HEADER 0x1901000000000000000000000000000000000000000000000000000000000000
#define DCN_HEADER_HASH 0x6c1a0baa584339032b4ed0d2fdb53c23d290c0b8a7da5a9e05ce919faa986a59
#define UPDATE_LIMIT_TYPE_HASH 0xbe6b685e53075dd48bdabc4949b848400d5a7e53705df48e04ace664c3946ad2
struct SetLimitMemory {
uint256 user_id;
uint256 exchange_id;
uint256 quote_asset_id;
uint256 base_asset_id;
uint256 limit_version;
uint256 quote_shift;
uint256 base_shift;
}
/**
* Exchange Set Limits
*
* caller = exchange owner
*
* Update trading limits for an exchange's session. Requires
* - proper signature
* - exchange_id is for exchange
* - limit_version is an increase (prevents replays)
*
* @param data, a binary payload
* - SetLimitsHeader
* - 1st Signature + UpdateLimit
* - 2nd Signature + UpdateLimit
* - ...
*/
function exchange_set_limits(bytes memory data) public {
uint256[14] memory to_hash_mem;
uint256 cursor;
uint256 cursor_end;
uint256 exchange_id;
uint256[sizeof(SetLimitMemory)] memory set_limit_memory_space;
#define MEM_PTR(KEY) \
add(set_limit_memory_space, byte_offset(SetLimitMemory, KEY))
#define SAVE_MEM(KEY, VALUE) \
mstore(MEM_PTR(KEY), VALUE)
#define LOAD_MEM(KEY) \
mload(MEM_PTR(KEY))
/*
* Ensure caller is exchange and setup cursors.
*/
assembly {
SECURITY_FEATURE_CHECK(FEATURE_EXCHANGE_SET_LIMITS, /* REVERT(0) */ 0)
let data_size := mload(data)
cursor := add(data, WORD_1)
cursor_end := add(cursor, data_size)
let set_limits_header_0 := CURSOR_LOAD(SetLimitsHeader, /* REVERT(1) */ 1)
exchange_id := attr(SetLimitsHeader, 0, set_limits_header_0, exchange_id)
let exchange_0 := sload(EXCHANGE_PTR_(exchange_id))
let exchange_owner := attr(Exchange, 0, exchange_0, owner)
/* ensure caller is the exchange owner */
if iszero(eq(caller, exchange_owner)) {
REVERT(2)
}
/* ensure exchange is not locked */
if attr(Exchange, 0, exchange_0, locked) {
REVERT(3)
}
}
/*
* Iterate through each limit to validate and apply
*/
while (true) {
uint256 update_limit_0;
uint256 update_limit_1;
uint256 update_limit_2;
bytes32 limit_hash;
/* hash limit, and extract variables */
assembly {
/* Reached the end */
if eq(cursor, cursor_end) {
return(0, 0)
}
update_limit_0 := mload(cursor)
update_limit_1 := mload(add(cursor, WORD_1))
update_limit_2 := mload(add(cursor, WORD_2))
cursor := add(cursor, sizeof(UpdateLimit))
if gt(cursor, cursor_end) {
REVERT(4)
}
/* macro to make life easier */
#define ATTR_GET(INDEX, ATTR_NAME) \
attr(UpdateLimit, INDEX, update_limit_##INDEX, ATTR_NAME)
#define BUF_PUT(WORD, INDEX, ATTR_NAME) \
temp_var := ATTR_GET(INDEX, ATTR_NAME) \
mstore(add(to_hash_mem, WORD), temp_var)
#define BUF_PUT_I64(WORD, INDEX, ATTR_NAME) \
temp_var := ATTR_GET(INDEX, ATTR_NAME) \
CAST_64_NEG(temp_var) \
mstore(add(to_hash_mem, WORD), temp_var)
#define BUF_PUT_I96(WORD, INDEX, ATTR_NAME) \
temp_var := ATTR_GET(INDEX, ATTR_NAME) \
CAST_96_NEG(temp_var) \
mstore(add(to_hash_mem, WORD), temp_var)
#define SAVE(VAR_NAME) \
SAVE_MEM(VAR_NAME, temp_var)
#define LOAD(VAR_NAME) \
LOAD_MEM(VAR_NAME)
/* store data to hash */
{
mstore(to_hash_mem, UPDATE_LIMIT_TYPE_HASH)
let temp_var := 0
BUF_PUT(WORD_1, 0, dcn_id)
BUF_PUT(WORD_2, 0, user_id) SAVE(user_id)
BUF_PUT(WORD_3, 0, exchange_id)
BUF_PUT(WORD_4, 0, quote_asset_id) SAVE(quote_asset_id)
BUF_PUT(WORD_5, 0, base_asset_id) SAVE(base_asset_id)
BUF_PUT(WORD_6, 0, fee_limit)
BUF_PUT_I64(WORD_7, 1, min_quote_qty)
BUF_PUT_I64(WORD_8, 1, min_base_qty)
BUF_PUT(WORD_9, 1, long_max_price)
BUF_PUT(WORD_10, 1, short_min_price)
BUF_PUT(WORD_11, 2, limit_version) SAVE(limit_version)
BUF_PUT_I96(WORD_12, 2, quote_shift) SAVE(quote_shift)
BUF_PUT_I96(WORD_13, 2, base_shift) SAVE(base_shift)
}
limit_hash := keccak256(to_hash_mem, WORD_14)
mstore(to_hash_mem, SIG_HASH_HEADER)
mstore(add(to_hash_mem, 2), DCN_HEADER_HASH)
mstore(add(to_hash_mem, const_add(WORD_1, 2)), limit_hash)
limit_hash := keccak256(to_hash_mem, const_add(WORD_2, 2))
}
/* verify signature */
{
bytes32 sig_r;
bytes32 sig_s;
uint8 sig_v;
/* Load signature data */
assembly {
sig_r := attr(Signature, 0, mload(cursor), sig_r)
sig_s := attr(Signature, 1, mload(add(cursor, WORD_1)), sig_s)
sig_v := attr(Signature, 2, mload(add(cursor, WORD_2)), sig_v)
cursor := add(cursor, sizeof(Signature))
if gt(cursor, cursor_end) {
REVERT(5)
}
}
uint256 recovered_address = uint256(ecrecover(
/* hash */ limit_hash,
/* v */ sig_v,
/* r */ sig_r,
/* s */ sig_s
));
assembly {
let user_ptr := USER_PTR_(LOAD(user_id))
let session_ptr := SESSION_PTR_(user_ptr, exchange_id)
let trade_address := sload(pointer_attr(ExchangeSession, session_ptr, trade_address))
if iszero(eq(recovered_address, trade_address)) {
REVERT(6)
}
}
}
/* validate and apply new limit */
assembly {
/* limit's exchange id should match */
{
if iszero(eq(LOAD(exchange_id), exchange_id)) {
REVERT(7)
}
}
let user_ptr := USER_PTR_(LOAD(user_id))
let session_ptr := SESSION_PTR_(user_ptr, exchange_id)
let market_state_ptr := MARKET_STATE_PTR_(
session_ptr,
LOAD(quote_asset_id),
LOAD(base_asset_id)
)
let market_state_0 := sload(market_state_ptr)
let market_state_1 := sload(add(market_state_ptr, 1))
let market_state_2 := sload(add(market_state_ptr, 2))
/* verify limit version is greater */
{
let current_limit_version := attr(MarketState, 2, market_state_2, limit_version)
if iszero(gt(LOAD(limit_version), current_limit_version)) {
REVERT(8)
}
}
let quote_qty := attr(MarketState, 0, market_state_0, quote_qty)
CAST_64_NEG(quote_qty)
let base_qty := attr(MarketState, 0, market_state_0, base_qty)
CAST_64_NEG(base_qty)
#define APPLY_SHIFT(SIDE, REVERT_1) \
{ \
let current_shift := attr(MarketState, 2, market_state_2, SIDE##_shift) \
CAST_96_NEG(current_shift) \
\
let new_shift := LOAD(SIDE##_shift) \
\
SIDE##_qty := add(SIDE##_qty, sub(new_shift, current_shift)) \
if INVALID_I64(SIDE##_qty) { \
REVERT(REVERT_1) \
} \
}
APPLY_SHIFT(quote, /* REVERT(9) */ 9)
APPLY_SHIFT(base, /* REVERT(10) */ 10)
let new_market_state_0 := or(
build_with_mask(
MarketState, 0,
/* quote_qty */ quote_qty,
/* base_qty */ base_qty,
/* fee_used */ 0,
/* fee_limit */ update_limit_0),
and(mask_out(MarketState, 0, quote_qty, base_qty, fee_limit), market_state_0) /* extract fee_used */
)
sstore(market_state_ptr, new_market_state_0)
sstore(add(market_state_ptr, 1), update_limit_1)
sstore(add(market_state_ptr, 2), update_limit_2)
}
}
}
struct ExchangeId {
uint32 exchange_id;
}
struct GroupHeader {
uint32 quote_asset_id;
uint32 base_asset_id;
uint8 user_count;
}
struct Settlement {
uint64 user_id;
int64 quote_delta;
int64 base_delta;
uint64 fees;
}
/**
* Exchange Apply Settlement Groups
*
* caller = exchange owner
*
* Apply quote & base delta to session balances. Deltas must net to zero
* to ensure no funds are created or destroyed. Session's balance should
* only apply if the net result fits within the session's trading limit.
*
* @param data, a binary payload
* - ExchangeId
* - 1st GroupHeader
* - 1st Settlement
* - 2nd Settlement
* - ...
* - (GroupHeader.user_count)th Settlement
* - 2nd GroupHeader
* - 1st Settlement
* - 2nd Settlement
* - ...
* - (GroupHeader.user_count)th Settlement
* - ...
*/
function exchange_apply_settlement_groups(bytes memory data) public {
uint256[6] memory variables;
assembly {
/* Check security lock */
SECURITY_FEATURE_CHECK(FEATURE_APPLY_SETTLEMENT_GROUPS, /* REVERT(0) */ 0)
let data_len := mload(data)
let cursor := add(data, WORD_1)
let cursor_end := add(cursor, data_len)
let exchange_id_0 := CURSOR_LOAD(ExchangeId, /* REVERT(1) */ 1)
let exchange_id := attr(ExchangeId, 0, exchange_id_0, exchange_id)
VALID_EXCHANGE_ID(exchange_id, 2)
{
let exchange_ptr := EXCHANGE_PTR_(exchange_id)
let exchange_0 := sload(exchange_ptr)
/* caller must be exchange owner */
if iszero(eq(caller, attr(Exchange, 0, exchange_0, owner))) {
REVERT(2)
}
/* exchange must not be locked */
if attr(Exchange, 0, exchange_0, locked) {
REVERT(3)
}
}
/* keep looping while there is space for a GroupHeader */
for {} lt(cursor, cursor_end) {} {
let header_0 := CURSOR_LOAD(GroupHeader, /* REVERT(4) */ 4)
let quote_asset_id := attr(GroupHeader, 0, header_0, quote_asset_id)
let base_asset_id := attr(GroupHeader, 0, header_0, base_asset_id)
if eq(quote_asset_id, base_asset_id) {
REVERT(16)
}
let group_end := add(cursor, mul(
attr(GroupHeader, 0, header_0 /* GroupHeader */, user_count),
sizeof(Settlement)
))
/* validate quote_asset_id and base_asset_id */
{
let asset_count := sload(asset_count_slot)
if iszero(and(lt(quote_asset_id, asset_count), lt(base_asset_id, asset_count))) {
REVERT(5)
}
}
/* ensure there is enough space for the settlement group */
if gt(group_end, cursor_end) {
REVERT(6)
}
let quote_net := 0
let base_net := 0
let exchange_ptr := EXCHANGE_PTR_(exchange_id)
let exchange_balance_ptr := EXCHANGE_BALANCE_PTR_(exchange_ptr, quote_asset_id)
let exchange_balance := sload(exchange_balance_ptr)
/* loop through each settlement */
for {} lt(cursor, group_end) { cursor := add(cursor, sizeof(Settlement)) } {
let settlement_0 := mload(cursor)
let user_ptr := USER_PTR_(attr(Settlement, 0, settlement_0, user_id))
/* Stage user's quote/base/fee update and test against limit */
let session_ptr := SESSION_PTR_(user_ptr, exchange_id)
let market_state_ptr := MARKET_STATE_PTR_(
session_ptr,
quote_asset_id, base_asset_id
)
let quote_delta := attr(Settlement, 0, settlement_0, quote_delta)
CAST_64_NEG(quote_delta)
let base_delta := attr(Settlement, 0, settlement_0, base_delta)
CAST_64_NEG(base_delta)
quote_net := add(quote_net, quote_delta)
base_net := add(base_net, base_delta)
let fees := attr(Settlement, 0, settlement_0, fees)
exchange_balance := add(exchange_balance, fees)
let market_state_0 := sload(market_state_ptr)
/* Validate Limit */
{
let quote_qty := attr(MarketState, 0, market_state_0, quote_qty)
CAST_64_NEG(quote_qty)
let base_qty := attr(MarketState, 0, market_state_0, base_qty)
CAST_64_NEG(base_qty)
quote_qty := add(quote_qty, quote_delta)
base_qty := add(base_qty, base_delta)
if or(INVALID_I64(quote_qty), INVALID_I64(base_qty)) {
REVERT(7)
}
let fee_used := add(attr(MarketState, 0, market_state_0, fee_used), fees)
let fee_limit := attr(MarketState, 0, market_state_0, fee_limit)
if gt(fee_used, fee_limit) {
REVERT(8)
}
market_state_0 := build(
MarketState, 0,
/* quote_qty */ quote_qty,
/* base_qty */ and(base_qty, U64_MASK),
/* fee_used */ fee_used,
/* fee_limit */ fee_limit
)
let market_state_1 := sload(add(market_state_ptr, 1))
/* Check against min_qty */
{
let min_quote_qty := attr(MarketState, 1, market_state_1, min_quote_qty)
CAST_64_NEG(min_quote_qty)
let min_base_qty := attr(MarketState, 1, market_state_1, min_base_qty)
CAST_64_NEG(min_base_qty)
if or(slt(quote_qty, min_quote_qty), slt(base_qty, min_base_qty)) {
REVERT(9)
}
}
/* Check against limit */
{
/* Check if price fits limit */
let negatives := add(slt(quote_qty, 1), mul(slt(base_qty, 1), 2))
switch negatives
/* Both negative */
case 3 {
/* if one value is non zero, it must be negative */
if or(quote_qty, base_qty) {
REVERT(10)
}
}
/* long: quote_qty negative or zero */
case 1 {
let current_price := div(mul(sub(0, quote_qty), PRICE_UNITS), base_qty)
let long_max_price := attr(MarketState, 1, market_state_1, long_max_price)
if gt(current_price, long_max_price) {
REVERT(11)
}
}
/* short: base_qty negative */
case 2 {
if base_qty {
let current_price := div(mul(quote_qty, PRICE_UNITS), sub(0, base_qty))
let short_min_price := attr(MarketState, 1, market_state_1, short_min_price)
if lt(current_price, short_min_price) {
REVERT(12)
}
}
}
}
}
let quote_session_balance_ptr := SESSION_BALANCE_PTR_(session_ptr, quote_asset_id)
let base_session_balance_ptr := SESSION_BALANCE_PTR_(session_ptr, base_asset_id)
let quote_session_balance_0 := sload(quote_session_balance_ptr)
let base_session_balance_0 := sload(base_session_balance_ptr)
let quote_balance := attr(SessionBalance, 0, quote_session_balance_0, asset_balance)
quote_balance := add(quote_balance, quote_delta)
quote_balance := sub(quote_balance, fees)
if U64_OVERFLOW(quote_balance) {
REVERT(13)
}
let base_balance := attr(SessionBalance, 0, base_session_balance_0, asset_balance)
base_balance := add(base_balance, base_delta)
if U64_OVERFLOW(base_balance) {
REVERT(14)
}
sstore(market_state_ptr, market_state_0)
sstore(quote_session_balance_ptr, or(
and(mask_out(SessionBalance, 0, asset_balance), quote_session_balance_0),
build(
SessionBalance, 0,
/* total_deposit */ 0,
/* unsettled_withdraw_total */ 0,
/* asset_balance */ quote_balance)
))
sstore(base_session_balance_ptr, or(
and(mask_out(SessionBalance, 0, asset_balance), base_session_balance_0),
build(
SessionBalance, 0,
/* total_deposit */ 0,
/* unsettled_withdraw_total */ 0,
/* asset_balance */ base_balance)
))
}
if or(quote_net, base_net) {
REVERT(15)
}
sstore(exchange_balance_ptr, exchange_balance)
}
}
}
}
|
User Market Reset caller = user's trade_address Allows the user to reset their session with an exchange. Only allowed when session in unlocked. Persists limit_version to prevent old limits from being applied./
|
function user_market_reset(uint64 user_id, uint32 exchange_id,
uint32 quote_asset_id, uint32 base_asset_id) public {
assembly {
SECURITY_FEATURE_CHECK(FEATURE_USER_MARKET_RESET, /* REVERT(0) */ 0)
VALID_EXCHANGE_ID(exchange_id, /* REVERT(1) */ 1)
let user_ptr := USER_PTR_(user_id)
let trade_address := sload(pointer_attr(User, user_ptr, trade_address))
if iszero(eq(caller, trade_address)) {
REVERT(2)
}
let session_ptr := SESSION_PTR_(user_ptr, exchange_id)
let unlock_at := sload(pointer_attr(ExchangeSession, session_ptr, unlock_at))
if gt(unlock_at, timestamp) {
REVERT(3)
}
let market_state_ptr := MARKET_STATE_PTR_(session_ptr, quote_asset_id, base_asset_id)
sstore(market_state_ptr, 0)
sstore(add(market_state_ptr, 1), 0)
let market_state_2 := sload(market_state_2_ptr)
let limit_version := add(attr(MarketState, 2, market_state_2, limit_version), 1)
sstore(market_state_2_ptr, build(MarketState, 2,
}
}
| 14,122,907 |
/**
*Submitted for verification at Etherscan.io on 2021-06-30
*/
/*
____ __ __ __ _
/ __/__ __ ___ / /_ / / ___ / /_ (_)__ __
_\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
/___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
/___/
* Synthetix: DebtCache.sol
*
* Latest source (may be newer): https://github.com/Synthetixio/synthetix/blob/master/contracts/DebtCache.sol
* Docs: https://docs.synthetix.io/contracts/DebtCache
*
* Contract Dependencies:
* - BaseDebtCache
* - IAddressResolver
* - IDebtCache
* - MixinResolver
* - MixinSystemSettings
* - Owned
* Libraries:
* - SafeDecimalMath
* - SafeMath
*
* MIT License
* ===========
*
* Copyright (c) 2021 Synthetix
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity ^0.5.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) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// Libraries
// https://docs.synthetix.io/contracts/source/libraries/safedecimalmath
library SafeDecimalMath {
using SafeMath for uint;
/* Number of decimal places in the representations. */
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
/* The number representing 1.0. */
uint public constant UNIT = 10**uint(decimals);
/* The number representing 1.0 for higher fidelity numbers. */
uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals);
uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals);
/**
* @return Provides an interface to UNIT.
*/
function unit() external pure returns (uint) {
return UNIT;
}
/**
* @return Provides an interface to PRECISE_UNIT.
*/
function preciseUnit() external pure returns (uint) {
return PRECISE_UNIT;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals.
*
* @dev A unit factor is divided out after the product of x and y is evaluated,
* so that product must be less than 2**256. As this is an integer division,
* the internal division always rounds down. This helps save on gas. Rounding
* is more expensive on gas.
*/
function multiplyDecimal(uint x, uint y) internal pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
return x.mul(y) / UNIT;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of the specified precision unit.
*
* @dev The operands should be in the form of a the specified unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function _multiplyDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a precise unit.
*
* @dev The operands should be in the precise unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a standard unit.
*
* @dev The operands should be in the standard unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is a high
* precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and UNIT must be less than 2**256. As
* this is an integer division, the result is always rounded down.
* This helps save on gas. Rounding is more expensive on gas.
*/
function divideDecimal(uint x, uint y) internal pure returns (uint) {
/* Reintroduce the UNIT factor that will be divided out by y. */
return x.mul(UNIT).div(y);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* decimal in the precision unit specified in the parameter.
*
* @dev y is divided after the product of x and the specified precision unit
* is evaluated, so the product of x and the specified precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function _divideDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
uint resultTimesTen = x.mul(precisionUnit * 10).div(y);
if (resultTimesTen % 10 >= 5) {
resultTimesTen += 10;
}
return resultTimesTen / 10;
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* standard precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and the standard precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRound(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* high precision decimal.
*
* @dev y is divided after the product of x and the high precision unit
* is evaluated, so the product of x and the high precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @dev Convert a standard decimal representation to a high precision one.
*/
function decimalToPreciseDecimal(uint i) internal pure returns (uint) {
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
/**
* @dev Convert a high precision decimal to a standard decimal representation.
*/
function preciseDecimalToDecimal(uint i) internal pure returns (uint) {
uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
// Computes `a - b`, setting the value to 0 if b > a.
function floorsub(uint a, uint b) internal pure returns (uint) {
return b >= a ? 0 : a - b;
}
}
// https://docs.synthetix.io/contracts/source/contracts/owned
contract Owned {
address public owner;
address public nominatedOwner;
constructor(address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
_onlyOwner();
_;
}
function _onlyOwner() private view {
require(msg.sender == owner, "Only the contract owner may perform this action");
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
// https://docs.synthetix.io/contracts/source/interfaces/iaddressresolver
interface IAddressResolver {
function getAddress(bytes32 name) external view returns (address);
function getSynth(bytes32 key) external view returns (address);
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address);
}
// https://docs.synthetix.io/contracts/source/interfaces/isynth
interface ISynth {
// Views
function currencyKey() external view returns (bytes32);
function transferableSynths(address account) external view returns (uint);
// Mutative functions
function transferAndSettle(address to, uint value) external returns (bool);
function transferFromAndSettle(
address from,
address to,
uint value
) external returns (bool);
// Restricted: used internally to Synthetix
function burn(address account, uint amount) external;
function issue(address account, uint amount) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/iissuer
interface IIssuer {
// Views
function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availableSynthCount() external view returns (uint);
function availableSynths(uint index) external view returns (ISynth);
function canBurnSynths(address account) external view returns (bool);
function collateral(address account) external view returns (uint);
function collateralisationRatio(address issuer) external view returns (uint);
function collateralisationRatioAndAnyRatesInvalid(address _issuer)
external
view
returns (uint cratio, bool anyRateIsInvalid);
function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance);
function issuanceRatio() external view returns (uint);
function lastIssueEvent(address account) external view returns (uint);
function maxIssuableSynths(address issuer) external view returns (uint maxIssuable);
function minimumStakeTime() external view returns (uint);
function remainingIssuableSynths(address issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
);
function synths(bytes32 currencyKey) external view returns (ISynth);
function getSynths(bytes32[] calldata currencyKeys) external view returns (ISynth[] memory);
function synthsByAddress(address synthAddress) external view returns (bytes32);
function totalIssuedSynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint);
function transferableSynthetixAndAnyRateIsInvalid(address account, uint balance)
external
view
returns (uint transferable, bool anyRateIsInvalid);
// Restricted: used internally to Synthetix
function issueSynths(address from, uint amount) external;
function issueSynthsOnBehalf(
address issueFor,
address from,
uint amount
) external;
function issueMaxSynths(address from) external;
function issueMaxSynthsOnBehalf(address issueFor, address from) external;
function burnSynths(address from, uint amount) external;
function burnSynthsOnBehalf(
address burnForAddress,
address from,
uint amount
) external;
function burnSynthsToTarget(address from) external;
function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external;
function liquidateDelinquentAccount(
address account,
uint susdAmount,
address liquidator
) external returns (uint totalRedeemed, uint amountToLiquidate);
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/addressresolver
contract AddressResolver is Owned, IAddressResolver {
mapping(bytes32 => address) public repository;
constructor(address _owner) public Owned(_owner) {}
/* ========== RESTRICTED FUNCTIONS ========== */
function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner {
require(names.length == destinations.length, "Input lengths must match");
for (uint i = 0; i < names.length; i++) {
bytes32 name = names[i];
address destination = destinations[i];
repository[name] = destination;
emit AddressImported(name, destination);
}
}
/* ========= PUBLIC FUNCTIONS ========== */
function rebuildCaches(MixinResolver[] calldata destinations) external {
for (uint i = 0; i < destinations.length; i++) {
destinations[i].rebuildCache();
}
}
/* ========== VIEWS ========== */
function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) {
for (uint i = 0; i < names.length; i++) {
if (repository[names[i]] != destinations[i]) {
return false;
}
}
return true;
}
function getAddress(bytes32 name) external view returns (address) {
return repository[name];
}
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) {
address _foundAddress = repository[name];
require(_foundAddress != address(0), reason);
return _foundAddress;
}
function getSynth(bytes32 key) external view returns (address) {
IIssuer issuer = IIssuer(repository["Issuer"]);
require(address(issuer) != address(0), "Cannot find Issuer address");
return address(issuer.synths(key));
}
/* ========== EVENTS ========== */
event AddressImported(bytes32 name, address destination);
}
// solhint-disable payable-fallback
// https://docs.synthetix.io/contracts/source/contracts/readproxy
contract ReadProxy is Owned {
address public target;
constructor(address _owner) public Owned(_owner) {}
function setTarget(address _target) external onlyOwner {
target = _target;
emit TargetUpdated(target);
}
function() external {
// The basics of a proxy read call
// Note that msg.sender in the underlying will always be the address of this contract.
assembly {
calldatacopy(0, 0, calldatasize)
// Use of staticcall - this will revert if the underlying function mutates state
let result := staticcall(gas, sload(target_slot), 0, calldatasize, 0, 0)
returndatacopy(0, 0, returndatasize)
if iszero(result) {
revert(0, returndatasize)
}
return(0, returndatasize)
}
}
event TargetUpdated(address newTarget);
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/mixinresolver
contract MixinResolver {
AddressResolver public resolver;
mapping(bytes32 => address) private addressCache;
constructor(address _resolver) internal {
resolver = AddressResolver(_resolver);
}
/* ========== INTERNAL FUNCTIONS ========== */
function combineArrays(bytes32[] memory first, bytes32[] memory second)
internal
pure
returns (bytes32[] memory combination)
{
combination = new bytes32[](first.length + second.length);
for (uint i = 0; i < first.length; i++) {
combination[i] = first[i];
}
for (uint j = 0; j < second.length; j++) {
combination[first.length + j] = second[j];
}
}
/* ========== PUBLIC FUNCTIONS ========== */
// Note: this function is public not external in order for it to be overridden and invoked via super in subclasses
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {}
function rebuildCache() public {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
// The resolver must call this function whenver it updates its state
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// Note: can only be invoked once the resolver has all the targets needed added
address destination =
resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name)));
addressCache[name] = destination;
emit CacheUpdated(name, destination);
}
}
/* ========== VIEWS ========== */
function isResolverCached() external view returns (bool) {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// false if our cache is invalid or if the resolver doesn't have the required address
if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) {
return false;
}
}
return true;
}
/* ========== INTERNAL FUNCTIONS ========== */
function requireAndGetAddress(bytes32 name) internal view returns (address) {
address _foundAddress = addressCache[name];
require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name)));
return _foundAddress;
}
/* ========== EVENTS ========== */
event CacheUpdated(bytes32 name, address destination);
}
// https://docs.synthetix.io/contracts/source/interfaces/iflexiblestorage
interface IFlexibleStorage {
// Views
function getUIntValue(bytes32 contractName, bytes32 record) external view returns (uint);
function getUIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (uint[] memory);
function getIntValue(bytes32 contractName, bytes32 record) external view returns (int);
function getIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (int[] memory);
function getAddressValue(bytes32 contractName, bytes32 record) external view returns (address);
function getAddressValues(bytes32 contractName, bytes32[] calldata records) external view returns (address[] memory);
function getBoolValue(bytes32 contractName, bytes32 record) external view returns (bool);
function getBoolValues(bytes32 contractName, bytes32[] calldata records) external view returns (bool[] memory);
function getBytes32Value(bytes32 contractName, bytes32 record) external view returns (bytes32);
function getBytes32Values(bytes32 contractName, bytes32[] calldata records) external view returns (bytes32[] memory);
// Mutative functions
function deleteUIntValue(bytes32 contractName, bytes32 record) external;
function deleteIntValue(bytes32 contractName, bytes32 record) external;
function deleteAddressValue(bytes32 contractName, bytes32 record) external;
function deleteBoolValue(bytes32 contractName, bytes32 record) external;
function deleteBytes32Value(bytes32 contractName, bytes32 record) external;
function setUIntValue(
bytes32 contractName,
bytes32 record,
uint value
) external;
function setUIntValues(
bytes32 contractName,
bytes32[] calldata records,
uint[] calldata values
) external;
function setIntValue(
bytes32 contractName,
bytes32 record,
int value
) external;
function setIntValues(
bytes32 contractName,
bytes32[] calldata records,
int[] calldata values
) external;
function setAddressValue(
bytes32 contractName,
bytes32 record,
address value
) external;
function setAddressValues(
bytes32 contractName,
bytes32[] calldata records,
address[] calldata values
) external;
function setBoolValue(
bytes32 contractName,
bytes32 record,
bool value
) external;
function setBoolValues(
bytes32 contractName,
bytes32[] calldata records,
bool[] calldata values
) external;
function setBytes32Value(
bytes32 contractName,
bytes32 record,
bytes32 value
) external;
function setBytes32Values(
bytes32 contractName,
bytes32[] calldata records,
bytes32[] calldata values
) external;
}
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/mixinsystemsettings
contract MixinSystemSettings is MixinResolver {
bytes32 internal constant SETTING_CONTRACT_NAME = "SystemSettings";
bytes32 internal constant SETTING_WAITING_PERIOD_SECS = "waitingPeriodSecs";
bytes32 internal constant SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR = "priceDeviationThresholdFactor";
bytes32 internal constant SETTING_ISSUANCE_RATIO = "issuanceRatio";
bytes32 internal constant SETTING_FEE_PERIOD_DURATION = "feePeriodDuration";
bytes32 internal constant SETTING_TARGET_THRESHOLD = "targetThreshold";
bytes32 internal constant SETTING_LIQUIDATION_DELAY = "liquidationDelay";
bytes32 internal constant SETTING_LIQUIDATION_RATIO = "liquidationRatio";
bytes32 internal constant SETTING_LIQUIDATION_PENALTY = "liquidationPenalty";
bytes32 internal constant SETTING_RATE_STALE_PERIOD = "rateStalePeriod";
bytes32 internal constant SETTING_EXCHANGE_FEE_RATE = "exchangeFeeRate";
bytes32 internal constant SETTING_MINIMUM_STAKE_TIME = "minimumStakeTime";
bytes32 internal constant SETTING_AGGREGATOR_WARNING_FLAGS = "aggregatorWarningFlags";
bytes32 internal constant SETTING_TRADING_REWARDS_ENABLED = "tradingRewardsEnabled";
bytes32 internal constant SETTING_DEBT_SNAPSHOT_STALE_TIME = "debtSnapshotStaleTime";
bytes32 internal constant SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT = "crossDomainDepositGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT = "crossDomainEscrowGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT = "crossDomainRewardGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT = "crossDomainWithdrawalGasLimit";
bytes32 internal constant SETTING_ETHER_WRAPPER_MAX_ETH = "etherWrapperMaxETH";
bytes32 internal constant SETTING_ETHER_WRAPPER_MINT_FEE_RATE = "etherWrapperMintFeeRate";
bytes32 internal constant SETTING_ETHER_WRAPPER_BURN_FEE_RATE = "etherWrapperBurnFeeRate";
bytes32 internal constant CONTRACT_FLEXIBLESTORAGE = "FlexibleStorage";
enum CrossDomainMessageGasLimits {Deposit, Escrow, Reward, Withdrawal}
constructor(address _resolver) internal MixinResolver(_resolver) {}
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
addresses = new bytes32[](1);
addresses[0] = CONTRACT_FLEXIBLESTORAGE;
}
function flexibleStorage() internal view returns (IFlexibleStorage) {
return IFlexibleStorage(requireAndGetAddress(CONTRACT_FLEXIBLESTORAGE));
}
function _getGasLimitSetting(CrossDomainMessageGasLimits gasLimitType) internal pure returns (bytes32) {
if (gasLimitType == CrossDomainMessageGasLimits.Deposit) {
return SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Escrow) {
return SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Reward) {
return SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Withdrawal) {
return SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT;
} else {
revert("Unknown gas limit type");
}
}
function getCrossDomainMessageGasLimit(CrossDomainMessageGasLimits gasLimitType) internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, _getGasLimitSetting(gasLimitType));
}
function getTradingRewardsEnabled() internal view returns (bool) {
return flexibleStorage().getBoolValue(SETTING_CONTRACT_NAME, SETTING_TRADING_REWARDS_ENABLED);
}
function getWaitingPeriodSecs() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_WAITING_PERIOD_SECS);
}
function getPriceDeviationThresholdFactor() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR);
}
function getIssuanceRatio() internal view returns (uint) {
// lookup on flexible storage directly for gas savings (rather than via SystemSettings)
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ISSUANCE_RATIO);
}
function getFeePeriodDuration() internal view returns (uint) {
// lookup on flexible storage directly for gas savings (rather than via SystemSettings)
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_FEE_PERIOD_DURATION);
}
function getTargetThreshold() internal view returns (uint) {
// lookup on flexible storage directly for gas savings (rather than via SystemSettings)
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_TARGET_THRESHOLD);
}
function getLiquidationDelay() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_DELAY);
}
function getLiquidationRatio() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_RATIO);
}
function getLiquidationPenalty() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_PENALTY);
}
function getRateStalePeriod() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_RATE_STALE_PERIOD);
}
function getExchangeFeeRate(bytes32 currencyKey) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_EXCHANGE_FEE_RATE, currencyKey))
);
}
function getMinimumStakeTime() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_MINIMUM_STAKE_TIME);
}
function getAggregatorWarningFlags() internal view returns (address) {
return flexibleStorage().getAddressValue(SETTING_CONTRACT_NAME, SETTING_AGGREGATOR_WARNING_FLAGS);
}
function getDebtSnapshotStaleTime() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_DEBT_SNAPSHOT_STALE_TIME);
}
function getEtherWrapperMaxETH() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MAX_ETH);
}
function getEtherWrapperMintFeeRate() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MINT_FEE_RATE);
}
function getEtherWrapperBurnFeeRate() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_BURN_FEE_RATE);
}
}
interface IDebtCache {
// Views
function cachedDebt() external view returns (uint);
function cachedSynthDebt(bytes32 currencyKey) external view returns (uint);
function cacheTimestamp() external view returns (uint);
function cacheInvalid() external view returns (bool);
function cacheStale() external view returns (bool);
function currentSynthDebts(bytes32[] calldata currencyKeys)
external
view
returns (
uint[] memory debtValues,
uint excludedDebt,
bool anyRateIsInvalid
);
function cachedSynthDebts(bytes32[] calldata currencyKeys) external view returns (uint[] memory debtValues);
function totalNonSnxBackedDebt() external view returns (uint excludedDebt, bool isInvalid);
function currentDebt() external view returns (uint debt, bool anyRateIsInvalid);
function cacheInfo()
external
view
returns (
uint debt,
uint timestamp,
bool isInvalid,
bool isStale
);
// Mutative functions
function updateCachedSynthDebts(bytes32[] calldata currencyKeys) external;
function updateCachedSynthDebtWithRate(bytes32 currencyKey, uint currencyRate) external;
function updateCachedSynthDebtsWithRates(bytes32[] calldata currencyKeys, uint[] calldata currencyRates) external;
function updateDebtCacheValidity(bool currentlyInvalid) external;
function purgeCachedSynthDebt(bytes32 currencyKey) external;
function takeDebtSnapshot() external;
}
interface IVirtualSynth {
// Views
function balanceOfUnderlying(address account) external view returns (uint);
function rate() external view returns (uint);
function readyToSettle() external view returns (bool);
function secsLeftInWaitingPeriod() external view returns (uint);
function settled() external view returns (bool);
function synth() external view returns (ISynth);
// Mutative functions
function settle(address account) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/iexchanger
interface IExchanger {
// Views
function calculateAmountAfterSettlement(
address from,
bytes32 currencyKey,
uint amount,
uint refunded
) external view returns (uint amountAfterSettlement);
function isSynthRateInvalid(bytes32 currencyKey) external view returns (bool);
function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint);
function settlementOwing(address account, bytes32 currencyKey)
external
view
returns (
uint reclaimAmount,
uint rebateAmount,
uint numEntries
);
function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool);
function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey)
external
view
returns (uint exchangeFeeRate);
function getAmountsForExchange(
uint sourceAmount,
bytes32 sourceCurrencyKey,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint amountReceived,
uint fee,
uint exchangeFeeRate
);
function priceDeviationThresholdFactor() external view returns (uint);
function waitingPeriodSecs() external view returns (uint);
// Mutative functions
function exchange(
address exchangeForAddress,
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress,
bool virtualSynth,
address rewardAddress,
bytes32 trackingCode
) external returns (uint amountReceived, IVirtualSynth vSynth);
function settle(address from, bytes32 currencyKey)
external
returns (
uint reclaimed,
uint refunded,
uint numEntries
);
function setLastExchangeRateForSynth(bytes32 currencyKey, uint rate) external;
function resetLastExchangeRate(bytes32[] calldata currencyKeys) external;
function suspendSynthWithInvalidRate(bytes32 currencyKey) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/iexchangerates
interface IExchangeRates {
// Structs
struct RateAndUpdatedTime {
uint216 rate;
uint40 time;
}
struct InversePricing {
uint entryPoint;
uint upperLimit;
uint lowerLimit;
bool frozenAtUpperLimit;
bool frozenAtLowerLimit;
}
// Views
function aggregators(bytes32 currencyKey) external view returns (address);
function aggregatorWarningFlags() external view returns (address);
function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool);
function canFreezeRate(bytes32 currencyKey) external view returns (bool);
function currentRoundForRate(bytes32 currencyKey) external view returns (uint);
function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory);
function effectiveValue(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external view returns (uint value);
function effectiveValueAndRates(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint value,
uint sourceRate,
uint destinationRate
);
function effectiveValueAtRound(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
uint roundIdForSrc,
uint roundIdForDest
) external view returns (uint value);
function getCurrentRoundId(bytes32 currencyKey) external view returns (uint);
function getLastRoundIdBeforeElapsedSecs(
bytes32 currencyKey,
uint startingRoundId,
uint startingTimestamp,
uint timediff
) external view returns (uint);
function inversePricing(bytes32 currencyKey)
external
view
returns (
uint entryPoint,
uint upperLimit,
uint lowerLimit,
bool frozenAtUpperLimit,
bool frozenAtLowerLimit
);
function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256);
function oracle() external view returns (address);
function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time);
function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time);
function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid);
function rateForCurrency(bytes32 currencyKey) external view returns (uint);
function rateIsFlagged(bytes32 currencyKey) external view returns (bool);
function rateIsFrozen(bytes32 currencyKey) external view returns (bool);
function rateIsInvalid(bytes32 currencyKey) external view returns (bool);
function rateIsStale(bytes32 currencyKey) external view returns (bool);
function rateStalePeriod() external view returns (uint);
function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds)
external
view
returns (uint[] memory rates, uint[] memory times);
function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys)
external
view
returns (uint[] memory rates, bool anyRateInvalid);
function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory);
// Mutative functions
function freezeRate(bytes32 currencyKey) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/isystemstatus
interface ISystemStatus {
struct Status {
bool canSuspend;
bool canResume;
}
struct Suspension {
bool suspended;
// reason is an integer code,
// 0 => no reason, 1 => upgrading, 2+ => defined by system usage
uint248 reason;
}
// Views
function accessControl(bytes32 section, address account) external view returns (bool canSuspend, bool canResume);
function requireSystemActive() external view;
function requireIssuanceActive() external view;
function requireExchangeActive() external view;
function requireExchangeBetweenSynthsAllowed(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function requireSynthActive(bytes32 currencyKey) external view;
function requireSynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function systemSuspension() external view returns (bool suspended, uint248 reason);
function issuanceSuspension() external view returns (bool suspended, uint248 reason);
function exchangeSuspension() external view returns (bool suspended, uint248 reason);
function synthExchangeSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function synthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function getSynthExchangeSuspensions(bytes32[] calldata synths)
external
view
returns (bool[] memory exchangeSuspensions, uint256[] memory reasons);
function getSynthSuspensions(bytes32[] calldata synths)
external
view
returns (bool[] memory suspensions, uint256[] memory reasons);
// Restricted functions
function suspendSynth(bytes32 currencyKey, uint256 reason) external;
function updateAccessControl(
bytes32 section,
address account,
bool canSuspend,
bool canResume
) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/iethercollateral
interface IEtherCollateral {
// Views
function totalIssuedSynths() external view returns (uint256);
function totalLoansCreated() external view returns (uint256);
function totalOpenLoanCount() external view returns (uint256);
// Mutative functions
function openLoan() external payable returns (uint256 loanID);
function closeLoan(uint256 loanID) external;
function liquidateUnclosedLoan(address _loanCreatorsAddress, uint256 _loanID) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/iethercollateralsusd
interface IEtherCollateralsUSD {
// Views
function totalIssuedSynths() external view returns (uint256);
function totalLoansCreated() external view returns (uint256);
function totalOpenLoanCount() external view returns (uint256);
// Mutative functions
function openLoan(uint256 _loanAmount) external payable returns (uint256 loanID);
function closeLoan(uint256 loanID) external;
function liquidateUnclosedLoan(address _loanCreatorsAddress, uint256 _loanID) external;
function depositCollateral(address account, uint256 loanID) external payable;
function withdrawCollateral(uint256 loanID, uint256 withdrawAmount) external;
function repayLoan(
address _loanCreatorsAddress,
uint256 _loanID,
uint256 _repayAmount
) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/ierc20
interface IERC20 {
// ERC20 Optional Views
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
// Views
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
// Mutative functions
function transfer(address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function transferFrom(
address from,
address to,
uint value
) external returns (bool);
// Events
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
interface ICollateralManager {
// Manager information
function hasCollateral(address collateral) external view returns (bool);
function isSynthManaged(bytes32 currencyKey) external view returns (bool);
// State information
function long(bytes32 synth) external view returns (uint amount);
function short(bytes32 synth) external view returns (uint amount);
function totalLong() external view returns (uint susdValue, bool anyRateIsInvalid);
function totalShort() external view returns (uint susdValue, bool anyRateIsInvalid);
function getBorrowRate() external view returns (uint borrowRate, bool anyRateIsInvalid);
function getShortRate(bytes32 synth) external view returns (uint shortRate, bool rateIsInvalid);
function getRatesAndTime(uint index)
external
view
returns (
uint entryRate,
uint lastRate,
uint lastUpdated,
uint newIndex
);
function getShortRatesAndTime(bytes32 currency, uint index)
external
view
returns (
uint entryRate,
uint lastRate,
uint lastUpdated,
uint newIndex
);
function exceedsDebtLimit(uint amount, bytes32 currency) external view returns (bool canIssue, bool anyRateIsInvalid);
function areSynthsAndCurrenciesSet(bytes32[] calldata requiredSynthNamesInResolver, bytes32[] calldata synthKeys)
external
view
returns (bool);
function areShortableSynthsSet(bytes32[] calldata requiredSynthNamesInResolver, bytes32[] calldata synthKeys)
external
view
returns (bool);
// Loans
function getNewLoanId() external returns (uint id);
// Manager mutative
function addCollaterals(address[] calldata collaterals) external;
function removeCollaterals(address[] calldata collaterals) external;
function addSynths(bytes32[] calldata synthNamesInResolver, bytes32[] calldata synthKeys) external;
function removeSynths(bytes32[] calldata synths, bytes32[] calldata synthKeys) external;
function addShortableSynths(bytes32[2][] calldata requiredSynthAndInverseNamesInResolver, bytes32[] calldata synthKeys)
external;
function removeShortableSynths(bytes32[] calldata synths) external;
// State mutative
function updateBorrowRates(uint rate) external;
function updateShortRates(bytes32 currency, uint rate) external;
function incrementLongs(bytes32 synth, uint amount) external;
function decrementLongs(bytes32 synth, uint amount) external;
function incrementShorts(bytes32 synth, uint amount) external;
function decrementShorts(bytes32 synth, uint amount) external;
}
interface IWETH {
// ERC20 Optional Views
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
// Views
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
// Mutative functions
function transfer(address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function transferFrom(
address from,
address to,
uint value
) external returns (bool);
// WETH-specific functions.
function deposit() external payable;
function withdraw(uint amount) external;
// Events
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
event Deposit(address indexed to, uint amount);
event Withdrawal(address indexed to, uint amount);
}
// https://docs.synthetix.io/contracts/source/interfaces/ietherwrapper
contract IEtherWrapper {
function mint(uint amount) external;
function burn(uint amount) external;
function distributeFees() external;
function capacity() external view returns (uint);
function getReserves() external view returns (uint);
function totalIssuedSynths() external view returns (uint);
function calculateMintFee(uint amount) public view returns (uint);
function calculateBurnFee(uint amount) public view returns (uint);
function maxETH() public view returns (uint256);
function mintFeeRate() public view returns (uint256);
function burnFeeRate() public view returns (uint256);
function weth() public view returns (IWETH);
}
// Inheritance
// Libraries
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/debtcache
contract BaseDebtCache is Owned, MixinSystemSettings, IDebtCache {
using SafeMath for uint;
using SafeDecimalMath for uint;
uint internal _cachedDebt;
mapping(bytes32 => uint) internal _cachedSynthDebt;
uint internal _cacheTimestamp;
bool internal _cacheInvalid = true;
/* ========== ENCODED NAMES ========== */
bytes32 internal constant sUSD = "sUSD";
bytes32 internal constant sETH = "sETH";
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_ISSUER = "Issuer";
bytes32 private constant CONTRACT_EXCHANGER = "Exchanger";
bytes32 private constant CONTRACT_EXRATES = "ExchangeRates";
bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus";
bytes32 private constant CONTRACT_ETHERCOLLATERAL = "EtherCollateral";
bytes32 private constant CONTRACT_ETHERCOLLATERAL_SUSD = "EtherCollateralsUSD";
bytes32 private constant CONTRACT_COLLATERALMANAGER = "CollateralManager";
bytes32 private constant CONTRACT_ETHER_WRAPPER = "EtherWrapper";
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[](8);
newAddresses[0] = CONTRACT_ISSUER;
newAddresses[1] = CONTRACT_EXCHANGER;
newAddresses[2] = CONTRACT_EXRATES;
newAddresses[3] = CONTRACT_SYSTEMSTATUS;
newAddresses[4] = CONTRACT_ETHERCOLLATERAL;
newAddresses[5] = CONTRACT_ETHERCOLLATERAL_SUSD;
newAddresses[6] = CONTRACT_COLLATERALMANAGER;
newAddresses[7] = CONTRACT_ETHER_WRAPPER;
addresses = combineArrays(existingAddresses, newAddresses);
}
function issuer() internal view returns (IIssuer) {
return IIssuer(requireAndGetAddress(CONTRACT_ISSUER));
}
function exchanger() internal view returns (IExchanger) {
return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER));
}
function exchangeRates() internal view returns (IExchangeRates) {
return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES));
}
function systemStatus() internal view returns (ISystemStatus) {
return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS));
}
function etherCollateral() internal view returns (IEtherCollateral) {
return IEtherCollateral(requireAndGetAddress(CONTRACT_ETHERCOLLATERAL));
}
function etherCollateralsUSD() internal view returns (IEtherCollateralsUSD) {
return IEtherCollateralsUSD(requireAndGetAddress(CONTRACT_ETHERCOLLATERAL_SUSD));
}
function collateralManager() internal view returns (ICollateralManager) {
return ICollateralManager(requireAndGetAddress(CONTRACT_COLLATERALMANAGER));
}
function etherWrapper() internal view returns (IEtherWrapper) {
return IEtherWrapper(requireAndGetAddress(CONTRACT_ETHER_WRAPPER));
}
function debtSnapshotStaleTime() external view returns (uint) {
return getDebtSnapshotStaleTime();
}
function cachedDebt() external view returns (uint) {
return _cachedDebt;
}
function cachedSynthDebt(bytes32 currencyKey) external view returns (uint) {
return _cachedSynthDebt[currencyKey];
}
function cacheTimestamp() external view returns (uint) {
return _cacheTimestamp;
}
function cacheInvalid() external view returns (bool) {
return _cacheInvalid;
}
function _cacheStale(uint timestamp) internal view returns (bool) {
// Note a 0 timestamp means that the cache is uninitialised.
// We'll keep the check explicitly in case the stale time is
// ever set to something higher than the current unix time (e.g. to turn off staleness).
return getDebtSnapshotStaleTime() < block.timestamp - timestamp || timestamp == 0;
}
function cacheStale() external view returns (bool) {
return _cacheStale(_cacheTimestamp);
}
function _issuedSynthValues(bytes32[] memory currencyKeys, uint[] memory rates)
internal
view
returns (uint[] memory values)
{
uint numValues = currencyKeys.length;
values = new uint[](numValues);
ISynth[] memory synths = issuer().getSynths(currencyKeys);
for (uint i = 0; i < numValues; i++) {
address synthAddress = address(synths[i]);
require(synthAddress != address(0), "Synth does not exist");
uint supply = IERC20(synthAddress).totalSupply();
values[i] = supply.multiplyDecimalRound(rates[i]);
}
return (values);
}
function _currentSynthDebts(bytes32[] memory currencyKeys)
internal
view
returns (
uint[] memory snxIssuedDebts,
uint _excludedDebt,
bool anyRateIsInvalid
)
{
(uint[] memory rates, bool isInvalid) = exchangeRates().ratesAndInvalidForCurrencies(currencyKeys);
uint[] memory values = _issuedSynthValues(currencyKeys, rates);
(uint excludedDebt, bool isAnyNonSnxDebtRateInvalid) = _totalNonSnxBackedDebt();
return (values, excludedDebt, isInvalid || isAnyNonSnxDebtRateInvalid);
}
function currentSynthDebts(bytes32[] calldata currencyKeys)
external
view
returns (
uint[] memory debtValues,
uint excludedDebt,
bool anyRateIsInvalid
)
{
return _currentSynthDebts(currencyKeys);
}
function _cachedSynthDebts(bytes32[] memory currencyKeys) internal view returns (uint[] memory) {
uint numKeys = currencyKeys.length;
uint[] memory debts = new uint[](numKeys);
for (uint i = 0; i < numKeys; i++) {
debts[i] = _cachedSynthDebt[currencyKeys[i]];
}
return debts;
}
function cachedSynthDebts(bytes32[] calldata currencyKeys) external view returns (uint[] memory snxIssuedDebts) {
return _cachedSynthDebts(currencyKeys);
}
// Returns the total sUSD debt backed by non-SNX collateral.
function totalNonSnxBackedDebt() external view returns (uint excludedDebt, bool isInvalid) {
return _totalNonSnxBackedDebt();
}
function _totalNonSnxBackedDebt() internal view returns (uint excludedDebt, bool isInvalid) {
// Calculate excluded debt.
// 1. Ether Collateral.
excludedDebt = excludedDebt.add(etherCollateralsUSD().totalIssuedSynths()); // Ether-backed sUSD
uint etherCollateralTotalIssuedSynths = etherCollateral().totalIssuedSynths();
// We check the supply > 0 as on L2, we may not yet have up-to-date rates for sETH.
if (etherCollateralTotalIssuedSynths > 0) {
(uint sETHRate, bool sETHRateIsInvalid) = exchangeRates().rateAndInvalid(sETH);
isInvalid = isInvalid || sETHRateIsInvalid;
excludedDebt = excludedDebt.add(etherCollateralTotalIssuedSynths.multiplyDecimalRound(sETHRate)); // Ether-backed sETH
}
// 2. MultiCollateral long debt + short debt.
(uint longValue, bool anyTotalLongRateIsInvalid) = collateralManager().totalLong();
(uint shortValue, bool anyTotalShortRateIsInvalid) = collateralManager().totalShort();
isInvalid = isInvalid || anyTotalLongRateIsInvalid || anyTotalShortRateIsInvalid;
excludedDebt = excludedDebt.add(longValue).add(shortValue);
// 3. EtherWrapper.
// Subtract sETH and sUSD issued by EtherWrapper.
excludedDebt = excludedDebt.add(etherWrapper().totalIssuedSynths());
return (excludedDebt, isInvalid);
}
function _currentDebt() internal view returns (uint debt, bool anyRateIsInvalid) {
bytes32[] memory currencyKeys = issuer().availableCurrencyKeys();
(uint[] memory rates, bool isInvalid) = exchangeRates().ratesAndInvalidForCurrencies(currencyKeys);
// Sum all issued synth values based on their supply.
uint[] memory values = _issuedSynthValues(currencyKeys, rates);
(uint excludedDebt, bool isAnyNonSnxDebtRateInvalid) = _totalNonSnxBackedDebt();
uint numValues = values.length;
uint total;
for (uint i; i < numValues; i++) {
total = total.add(values[i]);
}
total = total < excludedDebt ? 0 : total.sub(excludedDebt);
return (total, isInvalid || isAnyNonSnxDebtRateInvalid);
}
function currentDebt() external view returns (uint debt, bool anyRateIsInvalid) {
return _currentDebt();
}
function cacheInfo()
external
view
returns (
uint debt,
uint timestamp,
bool isInvalid,
bool isStale
)
{
uint time = _cacheTimestamp;
return (_cachedDebt, time, _cacheInvalid, _cacheStale(time));
}
/* ========== MUTATIVE FUNCTIONS ========== */
// Stub out all mutative functions as no-ops;
// since they do nothing, there are no restrictions
function updateCachedSynthDebts(bytes32[] calldata currencyKeys) external {}
function updateCachedSynthDebtWithRate(bytes32 currencyKey, uint currencyRate) external {}
function updateCachedSynthDebtsWithRates(bytes32[] calldata currencyKeys, uint[] calldata currencyRates) external {}
function updateDebtCacheValidity(bool currentlyInvalid) external {}
function purgeCachedSynthDebt(bytes32 currencyKey) external {}
function takeDebtSnapshot() external {}
/* ========== MODIFIERS ========== */
function _requireSystemActiveIfNotOwner() internal view {
if (msg.sender != owner) {
systemStatus().requireSystemActive();
}
}
modifier requireSystemActiveIfNotOwner() {
_requireSystemActiveIfNotOwner();
_;
}
function _onlyIssuer() internal view {
require(msg.sender == address(issuer()), "Sender is not Issuer");
}
modifier onlyIssuer() {
_onlyIssuer();
_;
}
function _onlyIssuerOrExchanger() internal view {
require(msg.sender == address(issuer()) || msg.sender == address(exchanger()), "Sender is not Issuer or Exchanger");
}
modifier onlyIssuerOrExchanger() {
_onlyIssuerOrExchanger();
_;
}
}
// Libraries
// Inheritance
// https://docs.synthetix.io/contracts/source/contracts/debtcache
contract DebtCache is BaseDebtCache {
using SafeDecimalMath for uint;
bytes32 public constant CONTRACT_NAME = "DebtCache";
constructor(address _owner, address _resolver) public BaseDebtCache(_owner, _resolver) {}
bytes32 internal constant EXCLUDED_DEBT_KEY = "EXCLUDED_DEBT";
/* ========== MUTATIVE FUNCTIONS ========== */
// This function exists in case a synth is ever somehow removed without its snapshot being updated.
function purgeCachedSynthDebt(bytes32 currencyKey) external onlyOwner {
require(issuer().synths(currencyKey) == ISynth(0), "Synth exists");
delete _cachedSynthDebt[currencyKey];
}
function takeDebtSnapshot() external requireSystemActiveIfNotOwner {
bytes32[] memory currencyKeys = issuer().availableCurrencyKeys();
(uint[] memory values, uint excludedDebt, bool isInvalid) = _currentSynthDebts(currencyKeys);
uint numValues = values.length;
uint snxCollateralDebt;
for (uint i; i < numValues; i++) {
uint value = values[i];
snxCollateralDebt = snxCollateralDebt.add(value);
_cachedSynthDebt[currencyKeys[i]] = value;
}
_cachedSynthDebt[EXCLUDED_DEBT_KEY] = excludedDebt;
uint newDebt = snxCollateralDebt.floorsub(excludedDebt);
_cachedDebt = newDebt;
_cacheTimestamp = block.timestamp;
emit DebtCacheUpdated(newDebt);
emit DebtCacheSnapshotTaken(block.timestamp);
// (in)validate the cache if necessary
_updateDebtCacheValidity(isInvalid);
}
function updateCachedSynthDebts(bytes32[] calldata currencyKeys) external requireSystemActiveIfNotOwner {
(uint[] memory rates, bool anyRateInvalid) = exchangeRates().ratesAndInvalidForCurrencies(currencyKeys);
_updateCachedSynthDebtsWithRates(currencyKeys, rates, anyRateInvalid, false);
}
function updateCachedSynthDebtWithRate(bytes32 currencyKey, uint currencyRate) external onlyIssuer {
bytes32[] memory synthKeyArray = new bytes32[](1);
synthKeyArray[0] = currencyKey;
uint[] memory synthRateArray = new uint[](1);
synthRateArray[0] = currencyRate;
_updateCachedSynthDebtsWithRates(synthKeyArray, synthRateArray, false, false);
}
function updateCachedSynthDebtsWithRates(bytes32[] calldata currencyKeys, uint[] calldata currencyRates)
external
onlyIssuerOrExchanger
{
_updateCachedSynthDebtsWithRates(currencyKeys, currencyRates, false, false);
}
function updateDebtCacheValidity(bool currentlyInvalid) external onlyIssuer {
_updateDebtCacheValidity(currentlyInvalid);
}
/* ========== INTERNAL FUNCTIONS ========== */
function _updateDebtCacheValidity(bool currentlyInvalid) internal {
if (_cacheInvalid != currentlyInvalid) {
_cacheInvalid = currentlyInvalid;
emit DebtCacheValidityChanged(currentlyInvalid);
}
}
function _updateCachedSynthDebtsWithRates(
bytes32[] memory currencyKeys,
uint[] memory currentRates,
bool anyRateIsInvalid,
bool recomputeExcludedDebt
) internal {
uint numKeys = currencyKeys.length;
require(numKeys == currentRates.length, "Input array lengths differ");
// Update the cached values for each synth, saving the sums as we go.
uint cachedSum;
uint currentSum;
uint[] memory currentValues = _issuedSynthValues(currencyKeys, currentRates);
for (uint i = 0; i < numKeys; i++) {
bytes32 key = currencyKeys[i];
uint currentSynthDebt = currentValues[i];
cachedSum = cachedSum.add(_cachedSynthDebt[key]);
currentSum = currentSum.add(currentSynthDebt);
_cachedSynthDebt[key] = currentSynthDebt;
}
// Compute the difference and apply it to the snapshot
if (cachedSum != currentSum) {
uint debt = _cachedDebt;
// This requirement should never fail, as the total debt snapshot is the sum of the individual synth
// debt snapshots.
require(cachedSum <= debt, "Cached synth sum exceeds total debt");
debt = debt.sub(cachedSum).add(currentSum);
// As of SIPS 136 and 150, this excluded debt section is unused.
// All callers of this function pass in false for `recomputeExcludedDebt`
// for performance reasons (_totalNonSnxBackedDebt is expensive)
// until we circle back when the debt calculation is refactored or discarded.
if (recomputeExcludedDebt) {
(uint excludedDebt, bool anyNonSnxDebtRateIsInvalid) = _totalNonSnxBackedDebt();
anyRateIsInvalid = anyRateIsInvalid || anyNonSnxDebtRateIsInvalid;
debt = debt.add(excludedDebt).floorsub(_cachedSynthDebt[EXCLUDED_DEBT_KEY]);
_cachedSynthDebt[EXCLUDED_DEBT_KEY] = excludedDebt;
}
_cachedDebt = debt;
emit DebtCacheUpdated(debt);
}
// A partial update can invalidate the debt cache, but a full snapshot must be performed in order
// to re-validate it.
if (anyRateIsInvalid) {
_updateDebtCacheValidity(anyRateIsInvalid);
}
}
/* ========== EVENTS ========== */
event DebtCacheUpdated(uint cachedDebt);
event DebtCacheSnapshotTaken(uint timestamp);
event DebtCacheValidityChanged(bool indexed isInvalid);
}
|
========== VIEWS ========== /
|
function accessControl(bytes32 section, address account) external view returns (bool canSuspend, bool canResume);
function requireSystemActive() external view;
function requireIssuanceActive() external view;
function requireExchangeActive() external view;
function requireExchangeBetweenSynthsAllowed(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function requireSynthActive(bytes32 currencyKey) external view;
function requireSynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function systemSuspension() external view returns (bool suspended, uint248 reason);
function issuanceSuspension() external view returns (bool suspended, uint248 reason);
function exchangeSuspension() external view returns (bool suspended, uint248 reason);
function synthExchangeSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function synthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function getSynthExchangeSuspensions(bytes32[] calldata synths)
external
view
returns (bool[] memory exchangeSuspensions, uint256[] memory reasons);
function getSynthSuspensions(bytes32[] calldata synths)
external
view
returns (bool[] memory suspensions, uint256[] memory reasons);
function suspendSynth(bytes32 currencyKey, uint256 reason) external;
function updateAccessControl(
bytes32 section,
address account,
bool canSuspend,
bool canResume
) external;
}
}
}
}
}
}
}
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](8);
newAddresses[0] = CONTRACT_ISSUER;
newAddresses[1] = CONTRACT_EXCHANGER;
newAddresses[2] = CONTRACT_EXRATES;
newAddresses[3] = CONTRACT_SYSTEMSTATUS;
newAddresses[4] = CONTRACT_ETHERCOLLATERAL;
newAddresses[5] = CONTRACT_ETHERCOLLATERAL_SUSD;
newAddresses[6] = CONTRACT_COLLATERALMANAGER;
newAddresses[7] = CONTRACT_ETHER_WRAPPER;
addresses = combineArrays(existingAddresses, newAddresses);
}
| 2,136,771 |
pragma solidity >=0.4.24;
/**
* @title -Security PO8 Token
* SPO8 contract records the core attributes of SPO8 Token
*
* ███████╗██████╗ ██████╗ █████╗ ████████╗ ██████╗ ██╗ ██╗███████╗███╗ ██╗
* ██╔════╝██╔══██╗██╔═══██╗██╔══██╗ ╚══██╔══╝██╔═══██╗██║ ██╔╝██╔════╝████╗ ██║
* ███████╗██████╔╝██║ ██║╚█████╔╝ ██║ ██║ ██║█████╔╝ █████╗ ██╔██╗ ██║
* ╚════██║██╔═══╝ ██║ ██║██╔══██╗ ██║ ██║ ██║██╔═██╗ ██╔══╝ ██║╚██╗██║
* ███████║██║ ╚██████╔╝╚█████╔╝ ██║ ╚██████╔╝██║ ██╗███████╗██║ ╚████║
* ╚══════╝╚═╝ ╚═════╝ ╚════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝
* ---
* POWERED BY
* __ ___ _ ___ _____ ___ _ ___
* / /` | |_) \ \_/ | |_) | | / / \ | |\ | ) )
* \_\_, |_| \ |_| |_| |_| \_\_/ |_| \| _)_)
* Company Info at https://po8.io
* code at https://github.com/crypn3
*/
contract SPO8 {
using SafeMath for uint256;
/* All props and event of Company */
// Company informations
string public companyName;
string public companyLicenseID;
string public companyTaxID;
string public companySecurityID;
string public companyURL;
address public CEO;
string public CEOName;
address public CFO;
string public CFOName;
address public BOD; // Board of directer
event CEOTransferred(address indexed previousCEO, address indexed newCEO);
event CEOSuccession(string previousCEO, string newCEO);
event CFOTransferred(address indexed previousCFO, address indexed newCFO);
event CFOSuccession(string previousCFO, string newCFO);
event BODTransferred(address indexed previousBOD, address indexed newBOD);
// Threshold
uint256 public threshold;
/* End Company */
/* All props and event of user */
address[] internal whiteListUser; // List of User
// Struct of User Information
struct Infor{
string userName;
string phone;
string certificate;
}
mapping(address => Infor) internal userInfor;
mapping(address => uint256) internal userPurchasingTime; // The date when user purchases tokens from Sale contract.
uint256 public transferLimitationTime = 31536000000; // 1 year
event NewUserAdded(address indexed newUser);
event UserRemoved(address indexed user);
event UserUnlocked(address indexed user);
event UserLocked(address indexed user);
event LimitationTimeSet(uint256 time);
event TokenUnlocked(uint256 time);
/* End user */
/* Sale token Contracts address */
address[] internal saleContracts;
event NewSaleContractAdded(address _saleContractAddress);
event SaleContractRemoved(address _saleContractAddress);
/* End Sale Contract */
/* All props and event of SPO8 token */
// Token informations
string public name;
string public symbol;
uint256 internal _totalSupply;
mapping (address => uint256) internal balances;
mapping (address => mapping (address => uint256)) internal allowed;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event BODBudgetApproval(address indexed owner, address indexed spender, uint256 value, address indexed to);
event AllowanceCanceled(address indexed from, address indexed to, uint256 value);
/* End Token */
// Boss's power
modifier onlyBoss() {
require(msg.sender == CEO || msg.sender == CFO);
_;
}
// BOD's power
modifier onlyBOD {
require(msg.sender == BOD);
_;
}
// Change CEO and CFO and BOD address or name
function changeCEO(address newCEO) public onlyBoss {
require(newCEO != address(0));
emit CEOTransferred(CEO, newCEO);
CEO = newCEO;
}
function changeCEOName(string newName) public onlyBoss {
emit CEOSuccession(CEOName, newName);
CEOName = newName;
}
function changeCFO(address newCFO) public onlyBoss {
require(newCFO != address(0));
emit CEOTransferred(CFO, newCFO);
CFO = newCFO;
}
function changeCFOName(string newName) public onlyBoss {
emit CFOSuccession(CFOName, newName);
CFOName = newName;
}
function changeBODAddress(address newBOD) public onlyBoss {
require(newBOD != address(0));
emit BODTransferred(BOD, newBOD);
BOD = newBOD;
}
// Informations of special Transfer
/**
* @dev: TransferState is a state of special transation. (sender have balance more than 10% total supply)
* State: Fail - 0.
* State: Success - 1.
* State: Pending - 2 - default state.
*/
enum TransactionState {
Fail,
Success,
Pending
}
/**
* @dev Struct of one special transaction.
* from The sender of transaction.
* to The receiver of transaction.
* value Total tokens is sended.
* state State of transaction.
* date The date when transaction is made.
*/
struct Transaction {
address from;
address to;
uint256 value;
TransactionState state;
uint256 date;
address bod;
}
Transaction[] internal specialTransactions; // An array where is used to save special transactions
// Contract's constructor
constructor (uint256 totalSupply_,
address _CEO,
string _CEOName,
address _CFO,
string _CFOName,
address _BOD) public {
name = "Security PO8 Token";
symbol = "SPO8";
_totalSupply = totalSupply_;
companyName = "PO8 Ltd";
companyTaxID = "IBC";
companyLicenseID = "No. 203231 B";
companySecurityID = "qKkFiGP4235d";
companyURL = "https://po8.io";
CEO = _CEO;
CEOName = _CEOName; // Mathew Arnett
CFO = _CFO;
CFOName = _CFOName; // Raul Vasquez
BOD = _BOD;
threshold = (totalSupply_.mul(10)).div(100); // threshold = 10% of totalSupply
balances[CEO] = 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 (utilities function)
* @param _from address The address which you want to send tokens 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));
require(balances[_from] >= _value);
require(balances[_to].add(_value) > balances[_to]);
require(checkWhiteList(_from));
require(checkWhiteList(_to));
require(checkLockedUser(_from) == false);
if(balances[_from] < threshold || msg.sender == CEO || msg.sender == CFO || msg.sender == BOD) {
uint256 previousBalances = balances[_from].add(balances[_to]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
assert(balances[_from].add(balances[_to]) == previousBalances);
}
else {
specialTransfer(_from, _to, _value); // waiting for acceptance from board of directer
emit Transfer(_from, _to, 0);
}
}
/**
* @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 Special Transfer token for a specified address, but waiting for acceptance from BOD, and push transaction infor to specialTransactions array
* @param _from The address transfer from.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function specialTransfer(address _from, address _to, uint256 _value) internal returns (bool) {
specialTransactions.push(Transaction({from: _from, to: _to, value: _value, state: TransactionState.Pending, date: now.mul(1000), bod: BOD}));
approveToBOD(_value, _to);
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));
require(_spender != BOD);
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev The approval to BOD address who will transfer the funds from msg.sender to address _to.
* @param _value The amount of tokens to be spent.
* @param _to The address which will receive the funds from msg.sender.
*/
function approveToBOD(uint256 _value, address _to) internal returns (bool) {
if(allowed[msg.sender][BOD] > 0)
allowed[msg.sender][BOD] = (allowed[msg.sender][BOD].add(_value));
else
allowed[msg.sender][BOD] = _value;
emit BODBudgetApproval(msg.sender, BOD, _value, _to);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_value <= allowed[_from][msg.sender]); // Check allowance
require(msg.sender != BOD);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
_transfer(_from, _to, _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 increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) {
require(_spender != address(0));
require(_spender != BOD);
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) {
require(_spender != address(0));
require(_spender != BOD);
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].sub(_subtractedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Cancel allowance of address from to BOD
* @param _from The address of whom approve tokens to BOD for spend.
* @param _value Total tokens are canceled.
*/
function cancelAllowance(address _from, uint256 _value) internal onlyBOD {
require(_from != address(0));
allowed[_from][BOD] = allowed[_from][BOD].sub(_value);
emit AllowanceCanceled(_from, BOD, _value);
}
/**
* @dev Only CEO or CFO can add new users.
* @param _newUser The address which will add to whiteListUser array.
*/
function addUser(address _newUser) external onlyBoss returns (bool) {
require (!checkWhiteList(_newUser));
whiteListUser.push(_newUser);
emit NewUserAdded(_newUser);
return true;
}
/**
* @dev Only CEO or CFO can add new users.
* @param _newUsers The address array which will add to whiteListUser array.
*/
function addUsers(address[] _newUsers) external onlyBoss returns (bool) {
for(uint i = 0; i < _newUsers.length; i++)
{
whiteListUser.push(_newUsers[i]);
emit NewUserAdded(_newUsers[i]);
}
return true;
}
/**
* @dev Return total users in white list array.
*/
function totalUsers() public view returns (uint256 users) {
return whiteListUser.length;
}
/**
* @dev Checking the user address whether in WhiteList or not.
* @param _user The address which will be checked.
*/
function checkWhiteList(address _user) public view returns (bool) {
uint256 length = whiteListUser.length;
for(uint i = 0; i < length; i++)
if(_user == whiteListUser[i])
return true;
return false;
}
/**
* @dev Delete the user address in WhiteList.
* @param _user The address which will be delete.
* After the function excuted, address in the end of list will be moved to postion of deleted user.
*/
function deleteUser(address _user) external onlyBoss returns (bool) {
require(checkWhiteList(_user));
uint256 i;
uint256 length = whiteListUser.length;
for(i = 0; i < length; i++)
{
if (_user == whiteListUser[i])
break;
}
whiteListUser[i] = whiteListUser[length - 1];
delete whiteListUser[length - 1];
whiteListUser.length--;
emit UserRemoved(_user);
return true;
}
/**
* @dev User or CEO or CFO can update user address informations.
* @param _user The address which will be checked.
* @param _name The new name
* @param _phone The new phone number
*/
function updateUserInfor(address _user, string _name, string _phone) external returns (bool) {
require(checkWhiteList(_user));
require(msg.sender == _user || msg.sender == CEO || msg.sender == CFO);
userInfor[_user].userName = _name;
userInfor[_user].phone = _phone;
return true;
}
/**
* @dev User can get address informations.
* @param _user The address which will be checked.
*/
function getUserInfor(address _user) public view returns (string, string) {
require(msg.sender == _user);
require(checkWhiteList(_user));
Infor memory infor = userInfor[_user];
return (infor.userName, infor.phone);
}
/**
* @dev CEO and CFO can lock user address, prevent them from transfer token action. If users buy token from any sale contracts, user address also will be locked in 1 year.
* @param _user The address which will be locked.
*/
function lockUser(address _user) external returns (bool) {
require(checkSaleContracts(msg.sender) || msg.sender == CEO || msg.sender == CFO);
userPurchasingTime[_user] = now.mul(1000);
emit UserLocked(_user);
return true;
}
/**
* @dev CEO and CFO can unlock user address. That address can do transfer token action.
* @param _user The address which will be unlocked.
*/
function unlockUser(address _user) external onlyBoss returns (bool) {
userPurchasingTime[_user] = 0;
emit UserUnlocked(_user);
return true;
}
/**
* @dev The function check the user address whether locked or not.
* @param _user The address which will be checked.
* if now sub User Purchasing Time < 1 year => Address is locked. In contrast, the address is unlocked.
* @return true The address is locked.
* @return false The address is unlock.
*/
function checkLockedUser(address _user) public view returns (bool) {
if ((now.mul(1000)).sub(userPurchasingTime[_user]) < transferLimitationTime)
return true;
return false;
}
/**
* @dev CEO or CFO can set transferLimitationTime.
* @param _time The new time will be set.
*/
function setLimitationTime(uint256 _time) external onlyBoss returns (bool) {
transferLimitationTime = _time;
emit LimitationTimeSet(_time);
return true;
}
/**
* @dev CEO or CFO can unlock tokens.
* transferLimitationTime = 0;
*/
function unlockToken() external onlyBoss returns (bool) {
transferLimitationTime = 0;
emit TokenUnlocked(now.mul(1000));
return true;
}
/**
* @dev Get special transaction informations
* @param _index The index of special transaction which user want to know about.
*/
function getSpecialTxInfor(uint256 _index) public view returns (address from,
address to,
uint256 value,
TransactionState state,
uint256 date,
address bod) {
Transaction storage txInfor = specialTransactions[_index];
return (txInfor.from, txInfor.to, txInfor.value, txInfor.state, txInfor.date, txInfor.bod);
}
/**
* @dev Get total special pending transaction
*/
function getTotalPendingTxs() internal view returns (uint32) {
uint32 count;
TransactionState txState = TransactionState.Pending;
for(uint256 i = 0; i < specialTransactions.length; i++) {
if(specialTransactions[i].state == txState)
count++;
}
return count;
}
/**
* @dev Get pending transation IDs from Special Transactions array
*/
function getPendingTxIDs() public view returns (uint[]) {
uint32 totalPendingTxs = getTotalPendingTxs();
uint[] memory pendingTxIDs = new uint[](totalPendingTxs);
uint32 id = 0;
TransactionState txState = TransactionState.Pending;
for(uint256 i = 0; i < specialTransactions.length; i++) {
if(specialTransactions[i].state == txState) {
pendingTxIDs[id] = i;
id++;
}
}
return pendingTxIDs;
}
/**
* @dev The function handle pending special transaction. Only BOD can use it.
* @param _index The id of pending transaction is in specialTransactions array.
* @param _decision The decision of BOD to handle pending Transaction (true or false).
* If true: transfer tokens from address txInfo.from to address txInfo.to and set state of that tx to Success.
* If false: cancel allowance from address txInfo.from to BOD and set state of that tx to Fail.
*/
function handlePendingTx(uint256 _index, bool _decision) public onlyBOD returns (bool) {
Transaction storage txInfo = specialTransactions[_index];
require(txInfo.state == TransactionState.Pending);
require(txInfo.bod == BOD);
if(_decision) {
require(txInfo.value <= allowed[txInfo.from][BOD]);
allowed[txInfo.from][BOD] = allowed[txInfo.from][BOD].sub(txInfo.value);
_transfer(txInfo.from, txInfo.to, txInfo.value);
txInfo.state = TransactionState.Success;
}
else {
txInfo.state = TransactionState.Fail;
cancelAllowance(txInfo.from, txInfo.value);
}
return true;
}
/**
* @dev The function check an address whether in saleContracts array or not.
* @param _saleContract The address will be checked.
*/
function checkSaleContracts(address _saleContract) public view returns (bool) {
uint256 length = saleContracts.length;
for(uint i = 0; i < length; i++) {
if(saleContracts[i] == _saleContract)
return true;
}
return false;
}
/**
* @dev The function adds new sale contract address to saleContracts array.
* @param _newSaleContract The address will be added.
*/
function addNewSaleContract(address _newSaleContract) external onlyBoss returns (bool) {
require(!checkSaleContracts(_newSaleContract));
saleContracts.push(_newSaleContract);
emit NewSaleContractAdded(_newSaleContract);
return true;
}
/**
* @dev The function remove sale contract address from saleContracts array.
* @param _saleContract The address will be removed.
*/
function removeSaleContract(address _saleContract) external onlyBoss returns (bool) {
require(checkSaleContracts(_saleContract));
uint256 length = saleContracts.length;
uint256 i;
for(i = 0; i < length; i++) {
if(saleContracts[i] == _saleContract)
break;
}
saleContracts[i] = saleContracts[length - 1];
delete saleContracts[length - 1];
saleContracts.length--;
emit SaleContractRemoved(_saleContract);
return true;
}
// Contract does not accept Ether
function () public payable {
revert();
}
}
/**
* @title SafeMath library
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
require(a == b * c);
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
|
User or CEO or CFO can update user address informations. _user The address which will be checked. _name The new name _phone The new phone number/
|
function updateUserInfor(address _user, string _name, string _phone) external returns (bool) {
require(checkWhiteList(_user));
require(msg.sender == _user || msg.sender == CEO || msg.sender == CFO);
userInfor[_user].userName = _name;
userInfor[_user].phone = _phone;
return true;
}
| 2,482,234 |
./partial_match/42/0x3520b14d962818204912ee387b0871DA7902817d/sources/GOLDx.sol
|
Authorized function to retrieve asset from account in the blacklist./
|
function retrieveBlackAddress(address _address) external auth {
require(blacklists[_address], "retrieveBlackAddress: Address is not frozen!");
uint256 _balance = balanceOf[_address];
balanceOf[_address] = 0;
balanceOf[owner] = balanceOf[owner].add(_balance);
emit Transfer(_address, owner, _balance);
}
| 8,875,233 |
./full_match/1/0xEf76d18e90fdd18380aD4E8E5A31427D20491045/sources/browser/BZX2.sol
|
bzLToken.approve(bzx1Address, (currentMaxLiq 100));handles eth, not sure if this path is ever takenhandles all other tokenshandles weth
|
function performTrade(bool isItEther, uint256 amount1) internal {
uint256 startingETHBalance = address(this).balance;
IERC20 tokenToReceive = IERC20(currentCToken);
uint256 startingCBalance = tokenToReceive.balanceOf(address(this));
IERC20 bzLToken = IERC20(currentLToken);
uint256 startingLBalance = bzLToken.balanceOf(address(this));
if (isItEther == true){
}
else{
if (bzLToken.allowance(address(this), bzx1Address) <= currentMaxLiq) {
SafeERC20.safeApprove(bzLToken, bzx1Address, 10000000000000000000000000);
}
bzx1.liquidate(currentLoanId, address(this), currentMaxLiq);
}
if (address(this).balance > startingETHBalance) {
uint256 newETH = address(this).balance - startingETHBalance;
convertEthToToken(0, newETH, currentLToken);
}
else {
if (address(currentLToken) != 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2){
require(startingCBalance<tokenToReceive.balanceOf(address(this)), "we lost money1");
convertTokenToEth(tokenToReceive.balanceOf(address(this))-startingCBalance, address(tokenToReceive));
convertEthToToken(0, address(this).balance, currentLToken);
require(bzLToken.balanceOf(address(this))> startingLBalance, "we lost money2");
}
else{
require(startingCBalance<tokenToReceive.balanceOf(address(this)), "we lost money3");
performUniswap(currentCToken, currentLToken, tokenToReceive.balanceOf(address(this))-startingCBalance);
}
}
}
| 4,992,575 |
// File: @openzeppelin/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/utils/Pausable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* 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());
}
}
// File: @openzeppelin/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.6.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].
*/
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/ISparkleTimestamp.sol
/// SWC-103: Floating Pragma
pragma solidity 0.6.12;
// import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
// import "../node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol";
// import "../node_modules/openzeppelin-solidity/contracts/lifecycle/Pausable.sol";
// import "../node_modules/openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol";
/**
* @dev Sparkle Timestamp Contract
* @author SparkleMobile Inc. (c) 2019-2020
*/
interface ISparkleTimestamp {
/**
* @dev Add new reward timestamp for address
* @param _rewardAddress being added to timestamp collection
*/
function addTimestamp(address _rewardAddress)
external
returns(bool);
/**
* @dev Reset timestamp maturity for loyalty address
* @param _rewardAddress to have reward period reset
*/
function resetTimestamp(address _rewardAddress)
external
returns(bool);
/**
* @dev Zero/delete existing loyalty timestamp entry
* @param _rewardAddress being requested for timestamp deletion
* @notice Test(s) not passed
*/
function deleteTimestamp(address _rewardAddress)
external
returns(bool);
/**
* @dev Get address confirmation for loyalty address
* @param _rewardAddress being queried for address information
*/
function getAddress(address _rewardAddress)
external
returns(address);
/**
* @dev Get timestamp of initial joined timestamp for loyalty address
* @param _rewardAddress being queried for timestamp information
*/
function getJoinedTimestamp(address _rewardAddress)
external
returns(uint256);
/**
* @dev Get timestamp of last deposit for loyalty address
* @param _rewardAddress being queried for timestamp information
*/
function getDepositTimestamp(address _rewardAddress)
external
returns(uint256);
/**
* @dev Get timestamp of reward maturity for loyalty address
* @param _rewardAddress being queried for timestamp information
*/
function getRewardTimestamp(address _rewardAddress)
external
returns(uint256);
/**
* @dev Determine if address specified has a timestamp record
* @param _rewardAddress being queried for timestamp existance
*/
function hasTimestamp(address _rewardAddress)
external
returns(bool);
/**
* @dev Calculate time remaining in seconds until this address' reward matures
* @param _rewardAddress to query remaining time before reward matures
*/
function getTimeRemaining(address _rewardAddress)
external
returns(uint256, bool, uint256);
/**
* @dev Determine if reward is mature for address
* @param _rewardAddress Address requesting addition in to loyalty timestamp collection
*/
function isRewardReady(address _rewardAddress)
external
returns(bool);
/**
* @dev Change the stored loyalty controller contract address
* @param _newAddress of new loyalty controller contract address
*/
function setContractAddress(address _newAddress)
external;
/**
* @dev Return the stored authorized controller address
* @return Address of loyalty controller contract
*/
function getContractAddress()
external
returns(address);
/**
* @dev Change the stored loyalty time period
* @param _newTimePeriod of new reward period (in seconds)
*/
function setTimePeriod(uint256 _newTimePeriod)
external;
/**
* @dev Return the current loyalty timer period
* @return Current stored value of loyalty time period
*/
function getTimePeriod()
external
returns(uint256);
/**
* @dev Event signal: Reset timestamp
*/
event ResetTimestamp(address _rewardAddress);
/**
* @dev Event signal: Loyalty contract address waws changed
*/
event ContractAddressChanged(address indexed _previousAddress, address indexed _newAddress);
/**
* @dev Event signal: Loyalty reward time period was changed
*/
event TimePeriodChanged( uint256 indexed _previousTimePeriod, uint256 indexed _newTimePeriod);
/**
* @dev Event signal: Loyalty reward timestamp was added
*/
event TimestampAdded( address indexed _newTimestampAddress );
/**
* @dev Event signal: Loyalty reward timestamp was removed
*/
event TimestampDeleted( address indexed _newTimestampAddress );
/**
* @dev Event signal: Timestamp for address was reset
*/
event TimestampReset(address _rewardAddress);
}
// File: contracts/ISparkleRewardTiers.sol
/// SWC-103: Floating Pragma
pragma solidity 0.6.12;
// import '../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol';
// import '../node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol';
// import '../node_modules/openzeppelin-solidity/contracts/lifecycle/Pausable.sol';
// import '../node_modules/openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol';
/**
* @title A contract for managing reward tiers
* @author SparkleLoyalty Inc. (c) 2019-2020
*/
// interface ISparkleRewardTiers is Ownable, Pausable, ReentrancyGuard {
interface ISparkleRewardTiers {
/**
* @dev Add a new reward tier to the contract for future proofing
* @param _index of the new reward tier to add
* @param _rate of the added reward tier
* @param _price of the added reward tier
* @param _enabled status of the added reward tier
* @notice Test(s) Need rewrite
*/
function addTier(uint256 _index, uint256 _rate, uint256 _price, bool _enabled)
external
// view
// onlyOwner
// whenNotPaused
// nonReentrant
returns(bool);
/**
* @dev Update an existing reward tier with new values
* @param _index of reward tier to update
* @param _rate of the reward tier
* @param _price of the reward tier
* @param _enabled status of the reward tier
* @return (bool) indicating success/failure
* @notice Test(s) Need rewrite
*/
function updateTier(uint256 _index, uint256 _rate, uint256 _price, bool _enabled)
external
// view
// onlyOwner
// whenNotPaused
// nonReentrant
returns(bool);
/**
* @dev Remove an existing reward tier from list of tiers
* @param _index of reward tier to remove
* @notice Test(s) Need rewrite
*/
function deleteTier(uint256 _index)
external
// view
// onlyOwner
// whenNotPaused
// nonReentrant
returns(bool);
/**
* @dev Get the rate value of specified tier
* @param _index of tier to query
* @return specified reward tier rate
* @notice Test(s) Need rewrite
*/
function getRate(uint256 _index)
external
// view
// whenNotPaused
returns(uint256);
/**
* @dev Get price of tier
* @param _index of tier to query
* @return uint256 indicating tier price
* @notice Test(s) Need rewrite
*/
function getPrice(uint256 _index)
external
// view
// whenNotPaused
returns(uint256);
/**
* @dev Get the enabled status of tier
* @param _index of tier to query
* @return bool indicating status of tier
* @notice Test(s) Need rewrite
*/
function getEnabled(uint256 _index)
external
// view
// whenNotPaused
returns(bool);
/**
* @dev Withdraw ether that has been sent directly to the contract
* @return bool indicating withdraw success
* @notice Test(s) Need rewrite
*/
function withdrawEth()
external
// onlyOwner
// whenNotPaused
// nonReentrant
returns(bool);
/**
* @dev Event triggered when a reward tier is deleted
* @param _index of tier to deleted
*/
event TierDeleted(uint256 _index);
/**
* @dev Event triggered when a reward tier is updated
* @param _index of the updated tier
* @param _rate of updated tier
* @param _price of updated tier
* @param _enabled status of updated tier
*/
event TierUpdated(uint256 _index, uint256 _rate, uint256 _price, bool _enabled);
/**
* @dev Event triggered when a new reward tier is added
* @param _index of the tier added
* @param _rate of added tier
* @param _price of added tier
* @param _enabled status of added tier
*/
event TierAdded(uint256 _index, uint256 _rate, uint256 _price, bool _enabled);
}
// File: contracts/SparkleLoyalty.sol
/// SWC-103: Floating Pragma
pragma solidity 0.6.12;
/**
* @dev Sparkle Loyalty Rewards
* @author SparkleMobile Inc.
*/
contract SparkleLoyalty is Ownable, Pausable, ReentrancyGuard {
/**
* @dev Ensure math safety through SafeMath
*/
using SafeMath for uint256;
// Gas to send with certain transations that may cost more in the future due to chain growth
uint256 private gasToSendWithTX = 25317;
// Base rate APR (5%) factored to 365.2422 gregorian days
uint256 private baseRate = 0.00041069 * 10e7; // A full year is 365.2422 gregorian days (5%)
// Account data structure
struct Account {
address _address; // Loyalty reward address
uint256 _balance; // Total tokens deposited
uint256 _collected; // Total tokens collected
uint256 _claimed; // Total succesfull reward claims
uint256 _joined; // Total times address has joined
uint256 _tier; // Tier index of reward tier
bool _isLocked; // Is the account locked
}
// tokenAddress of erc20 token address
address private tokenAddress;
// timestampAddress of time stamp contract address
address private timestampAddress;
// treasuryAddress of token treeasury address
address private treasuryAddress;
// collectionAddress to receive eth payed for tier upgrades
address private collectionAddress;
// rewardTiersAddress to resolve reward tier specifications
address private tiersAddress;
// minProofRequired to deposit of rewards to be eligibile
uint256 private minRequired;
// maxProofAllowed for deposit to be eligibile
uint256 private maxAllowed;
// totalTokensClaimed of all rewards awarded
uint256 private totalTokensClaimed;
// totalTimesClaimed of all successfully claimed rewards
uint256 private totalTimesClaimed;
// totalActiveAccounts count of all currently active addresses
uint256 private totalActiveAccounts;
// Accounts mapping of user loyalty records
mapping(address => Account) private accounts;
/**
* @dev Sparkle Loyalty Rewards Program contract .cTor
* @param _tokenAddress of token used for proof of loyalty rewards
* @param _treasuryAddress of proof of loyalty token reward distribution
* @param _collectionAddress of ethereum account to collect tier upgrade eth
* @param _tiersAddress of the proof of loyalty tier rewards support contract
* @param _timestampAddress of the proof of loyalty timestamp support contract
*/
constructor(address _tokenAddress, address _treasuryAddress, address _collectionAddress, address _tiersAddress, address _timestampAddress)
public
Ownable()
Pausable()
ReentrancyGuard()
{
// Initialize contract internal addresse(s) from params
tokenAddress = _tokenAddress;
treasuryAddress = _treasuryAddress;
collectionAddress = _collectionAddress;
tiersAddress = _tiersAddress;
timestampAddress = _timestampAddress;
// Initialize minimum/maximum allowed deposit limits
minRequired = uint256(1000).mul(10e7);
maxAllowed = uint256(250000).mul(10e7);
}
/**
* @dev Deposit additional tokens to a reward address loyalty balance
* @param _depositAmount of tokens to deposit into a reward address balance
* @return bool indicating the success of the deposit operation (true == success)
*/
function depositLoyalty(uint _depositAmount)
public
whenNotPaused
nonReentrant
returns (bool)
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}1');
// Validate specified value meets minimum requirements
require(_depositAmount >= minRequired, 'Minimum required');
// Determine if caller has approved enough allowance for this deposit
if(IERC20(tokenAddress).allowance(msg.sender, address(this)) < _depositAmount) {
// No, rever informing that deposit amount exceeded allownce amount
revert('Exceeds allowance');
}
// Obtain a storage instsance of callers account record
Account storage loyaltyAccount = accounts[msg.sender];
// Determine if there is an upper deposit cap
if(maxAllowed > 0) {
// Yes, determine if the deposit amount + current balance exceed max deposit cap
if(loyaltyAccount._balance.add(_depositAmount) > maxAllowed || _depositAmount > maxAllowed) {
// Yes, revert informing that the maximum deposit cap has been exceeded
revert('Exceeds cap');
}
}
// Determine if the tier selected is enabled
if(!ISparkleRewardTiers(tiersAddress).getEnabled(loyaltyAccount._tier)) {
// No, then this tier cannot be selected
revert('Invalid tier');
}
// Determine of transfer from caller has succeeded
if(IERC20(tokenAddress).transferFrom(msg.sender, address(this), _depositAmount)) {
// Yes, thend determine if the specified address has a timestamp record
if(ISparkleTimestamp(timestampAddress).hasTimestamp(msg.sender)) {
// Yes, update callers account balance by deposit amount
loyaltyAccount._balance = loyaltyAccount._balance.add(_depositAmount);
// Reset the callers reward timestamp
_resetTimestamp(msg.sender);
//
emit DepositLoyaltyEvent(msg.sender, _depositAmount, true);
// Return success
return true;
}
// Determine if a timestamp has been added for caller
if(!ISparkleTimestamp(timestampAddress).addTimestamp(msg.sender)) {
// No, revert indicating there was some kind of error
revert('No timestamp created');
}
// Prepare loyalty account record
loyaltyAccount._address = address(msg.sender);
loyaltyAccount._balance = _depositAmount;
loyaltyAccount._joined = loyaltyAccount._joined.add(1);
// Update global account counter
totalActiveAccounts = totalActiveAccounts.add(1);
//
emit DepositLoyaltyEvent(msg.sender, _depositAmount, false);
// Return success
return true;
}
// Return failure
return false;
}
/**
* @dev Claim Sparkle Loyalty reward
*/
function claimLoyaltyReward()
public
whenNotPaused
nonReentrant
returns(bool)
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
// Validate caller has a timestamp and it has matured
require(ISparkleTimestamp(timestampAddress).hasTimestamp(msg.sender), 'No record');
require(ISparkleTimestamp(timestampAddress).isRewardReady(msg.sender), 'Not mature');
// Obtain the current state of the callers timestamp
(uint256 timeRemaining, bool isReady, uint256 rewardDate) = ISparkleTimestamp(timestampAddress).getTimeRemaining(msg.sender);
// Determine if the callers reward has matured
if(isReady) {
// Value not used but throw unused var warning (cleanup)
rewardDate = 0;
// Yes, then obtain a storage instance of callers account record
Account storage loyaltyAccount = accounts[msg.sender];
// Obtain values required for caculations
uint256 dayCount = (timeRemaining.div(ISparkleTimestamp(timestampAddress).getTimePeriod())).add(1);
uint256 tokenBalance = loyaltyAccount._balance.add(loyaltyAccount._collected);
uint256 rewardRate = ISparkleRewardTiers(tiersAddress).getRate(loyaltyAccount._tier);
uint256 rewardTotal = baseRate.mul(tokenBalance).mul(rewardRate).mul(dayCount).div(10e7).div(10e7);
// Increment collected by reward total
loyaltyAccount._collected = loyaltyAccount._collected.add(rewardTotal);
// Increment total number of times a reward has been claimed
loyaltyAccount._claimed = loyaltyAccount._claimed.add(1);
// Incrememtn total number of times rewards have been collected by all
totalTimesClaimed = totalTimesClaimed.add(1);
// Increment total number of tokens claimed
totalTokensClaimed += rewardTotal;
// Reset the callers timestamp record
_resetTimestamp(msg.sender);
// Emit event log to the block chain for future web3 use
emit RewardClaimedEvent(msg.sender, rewardTotal);
// Return success
return true;
}
// Revert opposed to returning boolean (May or may not return a txreceipt)
revert('Failed claim');
}
/**
* @dev Withdraw the current deposit balance + any earned loyalty rewards
*/
function withdrawLoyalty()
public
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
// validate that caller has a loyalty timestamp
require(ISparkleTimestamp(timestampAddress).hasTimestamp(msg.sender), 'No timestamp2');
// Determine if the account has been locked
if(accounts[msg.sender]._isLocked) {
// Yes, revert informing that this loyalty account has been locked
revert('Locked');
}
// Obtain values needed from account record before zeroing
uint256 joinCount = accounts[msg.sender]._joined;
uint256 collected = accounts[msg.sender]._collected;
uint256 deposit = accounts[msg.sender]._balance;
bool isLocked = accounts[msg.sender]._isLocked;
// Zero out the callers account record
Account storage account = accounts[msg.sender];
account._address = address(0x0);
account._balance = 0x0;
account._collected = 0x0;
account._joined = joinCount;
account._claimed = 0x0;
account._tier = 0x0;
// Preserve account lock even after withdraw (account always locked)
account._isLocked = isLocked;
// Decement the total number of active accounts
totalActiveAccounts = totalActiveAccounts.sub(1);
// Delete the callers timestamp record
_deleteTimestamp(msg.sender);
// Determine if transfer from treasury address is a success
if(!IERC20(tokenAddress).transferFrom(treasuryAddress, msg.sender, collected)) {
// No, revert indicating that the transfer and wisthdraw has failed
revert('Withdraw failed');
}
// Determine if transfer from contract address is a sucess
if(!IERC20(tokenAddress).transfer(msg.sender, deposit)) {
// No, revert indicating that the treansfer and withdraw has failed
revert('Withdraw failed');
}
// Emit event log to the block chain for future web3 use
emit LoyaltyWithdrawnEvent(msg.sender, deposit.add(collected));
}
function returnLoyaltyDeposit(address _rewardAddress)
public
whenNotPaused
onlyOwner
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
// validate that caller has a loyalty timestamp
require(ISparkleTimestamp(timestampAddress).hasTimestamp(_rewardAddress), 'No timestamp2');
// Validate that reward address is locked
require(accounts[_rewardAddress]._isLocked, 'Lock account first');
uint256 deposit = accounts[_rewardAddress]._balance;
Account storage account = accounts[_rewardAddress];
account._balance = 0x0;
// Determine if transfer from contract address is a sucess
if(!IERC20(tokenAddress).transfer(_rewardAddress, deposit)) {
// No, revert indicating that the treansfer and withdraw has failed
revert('Withdraw failed');
}
// Emit event log to the block chain for future web3 use
emit LoyaltyDepositWithdrawnEvent(_rewardAddress, deposit);
}
function returnLoyaltyCollected(address _rewardAddress)
public
whenNotPaused
onlyOwner
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
// validate that caller has a loyalty timestamp
require(ISparkleTimestamp(timestampAddress).hasTimestamp(_rewardAddress), 'No timestamp2b');
// Validate that reward address is locked
require(accounts[_rewardAddress]._isLocked, 'Lock account first');
uint256 collected = accounts[_rewardAddress]._collected;
Account storage account = accounts[_rewardAddress];
account._collected = 0x0;
// Determine if transfer from treasury address is a success
if(!IERC20(tokenAddress).transferFrom(treasuryAddress, _rewardAddress, collected)) {
// No, revert indicating that the transfer and wisthdraw has failed
revert('Withdraw failed');
}
// Emit event log to the block chain for future web3 use
emit LoyaltyCollectedWithdrawnEvent(_rewardAddress, collected);
}
function removeLoyaltyAccount(address _rewardAddress)
public
whenNotPaused
onlyOwner
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
// validate that caller has a loyalty timestamp
require(ISparkleTimestamp(timestampAddress).hasTimestamp(_rewardAddress), 'No timestamp2b');
// Validate that reward address is locked
require(accounts[_rewardAddress]._isLocked, 'Lock account first');
uint256 joinCount = accounts[_rewardAddress]._joined;
Account storage account = accounts[_rewardAddress];
account._address = address(0x0);
account._balance = 0x0;
account._collected = 0x0;
account._joined = joinCount;
account._claimed = 0x0;
account._tier = 0x0;
account._isLocked = false;
// Decement the total number of active accounts
totalActiveAccounts = totalActiveAccounts.sub(1);
// Delete the callers timestamp record
_deleteTimestamp(_rewardAddress);
emit LoyaltyAccountRemovedEvent(_rewardAddress);
}
/**
* @dev Gets the locked status of the specified address
* @param _loyaltyAddress of account
* @return (bool) indicating locked status
*/
function isLocked(address _loyaltyAddress)
public
view
whenNotPaused
returns (bool)
{
return accounts[_loyaltyAddress]._isLocked;
}
function lockAccount(address _rewardAddress, bool _value)
public
onlyOwner
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {from}');
require(_rewardAddress != address(0x0), 'Invalid {reward}');
// Validate specified address has timestamp
require(ISparkleTimestamp(timestampAddress).hasTimestamp(_rewardAddress), 'No timstamp');
// Set the specified address' locked status
accounts[_rewardAddress]._isLocked = _value;
// Emit event log to the block chain for future web3 use
emit LockedAccountEvent(_rewardAddress, _value);
}
/**
* @dev Gets the storage address value of the specified address
* @param _loyaltyAddress of account
* @return (address) indicating the address stored calls account record
*/
function getLoyaltyAddress(address _loyaltyAddress)
public
view
whenNotPaused
returns(address)
{
return accounts[_loyaltyAddress]._address;
}
/**
* @dev Get the deposit balance value of specified address
* @param _loyaltyAddress of account
* @return (uint256) indicating the balance value
*/
function getDepositBalance(address _loyaltyAddress)
public
view
whenNotPaused
returns(uint256)
{
return accounts[_loyaltyAddress]._balance;
}
/**
* @dev Get the tokens collected by the specified address
* @param _loyaltyAddress of account
* @return (uint256) indicating the tokens collected
*/
function getTokensCollected(address _loyaltyAddress)
public
view
whenNotPaused
returns(uint256)
{
return accounts[_loyaltyAddress]._collected;
}
/**
* @dev Get the total balance (deposit + collected) of tokens
* @param _loyaltyAddress of account
* @return (uint256) indicating total balance
*/
function getTotalBalance(address _loyaltyAddress)
public
view
whenNotPaused
returns(uint256)
{
return accounts[_loyaltyAddress]._balance.add(accounts[_loyaltyAddress]._collected);
}
/**
* @dev Get the times loyalty has been claimed
* @param _loyaltyAddress of account
* @return (uint256) indicating total time claimed
*/
function getTimesClaimed(address _loyaltyAddress)
public
view
whenNotPaused
returns(uint256)
{
return accounts[_loyaltyAddress]._claimed;
}
/**
* @dev Get total number of times joined
* @param _loyaltyAddress of account
* @return (uint256)
*/
function getTimesJoined(address _loyaltyAddress)
public
view
whenNotPaused
returns(uint256)
{
return accounts[_loyaltyAddress]._joined;
}
/**
* @dev Get time remaining before reward maturity
* @param _loyaltyAddress of account
* @return (uint256, bool) Indicating time remaining/past and boolean indicating maturity
*/
function getTimeRemaining(address _loyaltyAddress)
public
whenNotPaused
returns (uint256, bool, uint256)
{
(uint256 remaining, bool status, uint256 deposit) = ISparkleTimestamp(timestampAddress).getTimeRemaining(_loyaltyAddress);
return (remaining, status, deposit);
}
/**
* @dev Withdraw any ether that has been sent directly to the contract
* @param _loyaltyAddress of account
* @return Total number of tokens that have been claimed by users
* @notice Test(s) Not written
*/
function getRewardTier(address _loyaltyAddress)
public
view whenNotPaused
returns(uint256)
{
return accounts[_loyaltyAddress]._tier;
}
/**
* @dev Select reward tier for msg.sender
* @param _tierSelected id of the reward tier interested in purchasing
* @return (bool) indicating failure/success
*/
function selectRewardTier(uint256 _tierSelected)
public
payable
whenNotPaused
nonReentrant
returns(bool)
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {From}');
// Validate specified address has a timestamp
require(accounts[msg.sender]._address == address(msg.sender), 'No timestamp3');
// Validate tier selection
require(accounts[msg.sender]._tier != _tierSelected, 'Already selected');
// Validate that ether was sent with the call
require(msg.value > 0, 'No ether');
// Determine if the specified rate is > than existing rate
if(ISparkleRewardTiers(tiersAddress).getRate(accounts[msg.sender]._tier) >= ISparkleRewardTiers(tiersAddress).getRate(_tierSelected)) {
// No, revert indicating failure
revert('Invalid tier');
}
// Determine if ether transfer for tier upgrade has completed successfully
(bool success, ) = address(collectionAddress).call{value: ISparkleRewardTiers(tiersAddress).getPrice(_tierSelected), gas: gasToSendWithTX}('');
require(success, 'Rate unchanged');
// Update callers rate with the new selected rate
accounts[msg.sender]._tier = _tierSelected;
emit TierSelectedEvent(msg.sender, _tierSelected);
// Return success
return true;
}
function getRewardTiersAddress()
public
view
whenNotPaused
returns(address)
{
return tiersAddress;
}
/**
* @dev Set tier collectionm address
* @param _newAddress of new collection address
* @notice Test(s) not written
*/
function setRewardTiersAddress(address _newAddress)
public
whenNotPaused
onlyOwner
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {From}');
// Validate specified address is valid
require(_newAddress != address(0), 'Invalid {reward}');
// Set tier rewards contract address
tiersAddress = _newAddress;
emit TiersAddressChanged(_newAddress);
}
function getCollectionAddress()
public
view
whenNotPaused
returns(address)
{
return collectionAddress;
}
/** @notice Test(s) passed
* @dev Set tier collectionm address
* @param _newAddress of new collection address
*/
function setCollectionAddress(address _newAddress)
public
whenNotPaused
onlyOwner
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {From}');
// Validate specified address is valid
require(_newAddress != address(0), 'Invalid {collection}');
// Set tier collection address
collectionAddress = _newAddress;
emit CollectionAddressChanged(_newAddress);
}
function getTreasuryAddress()
public
view
whenNotPaused
returns(address)
{
return treasuryAddress;
}
/**
* @dev Set treasury address
* @param _newAddress of the treasury address
* @notice Test(s) passed
*/
function setTreasuryAddress(address _newAddress)
public
onlyOwner
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), "Invalid {from}");
// Validate specified address
require(_newAddress != address(0), "Invalid {treasury}");
// Set current treasury contract address
treasuryAddress = _newAddress;
emit TreasuryAddressChanged(_newAddress);
}
function getTimestampAddress()
public
view
whenNotPaused
returns(address)
{
return timestampAddress;
}
/**
* @dev Set the timestamp address
* @param _newAddress of timestamp address
* @notice Test(s) passed
*/
function setTimestampAddress(address _newAddress)
public
onlyOwner
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), "Invalid {from}");
// Set current timestamp contract address
timestampAddress = _newAddress;
emit TimestampAddressChanged(_newAddress);
}
function getTokenAddress()
public
view
whenNotPaused
returns(address)
{
return tokenAddress;
}
/**
* @dev Set the loyalty token address
* @param _newAddress of the new token address
* @notice Test(s) passed
*/
function setTokenAddress(address _newAddress)
public
onlyOwner
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), "Invalid {from}");
// Set current token contract address
tokenAddress = _newAddress;
emit TokenAddressChangedEvent(_newAddress);
}
function getSentGasAmount()
public
view
whenNotPaused
returns(uint256)
{
return gasToSendWithTX;
}
function setSentGasAmount(uint256 _amount)
public
onlyOwner
whenNotPaused
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
// Set the current minimum deposit allowed
gasToSendWithTX = _amount;
emit GasSentChanged(_amount);
}
function getBaseRate()
public
view
whenNotPaused
returns(uint256)
{
return baseRate;
}
function setBaseRate(uint256 _newRate)
public
onlyOwner
whenNotPaused
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
// Set the current minimum deposit allowed
baseRate = _newRate;
emit BaseRateChanged(_newRate);
}
/**
* @dev Set the minimum Proof Of Loyalty amount allowed for deposit
* @param _minProof amount for new minimum accepted loyalty reward deposit
* @notice _minProof value is multiplied internally by 10e7. Do not multiply before calling!
*/
function setMinProof(uint256 _minProof)
public
onlyOwner
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
// Validate specified minimum is not lower than 1000 tokens
require(_minProof >= 1000, 'Invalid amount');
// Set the current minimum deposit allowed
minRequired = _minProof.mul(10e7);
emit MinProofChanged(minRequired);
}
event MinProofChanged(uint256);
/**
* @dev Get the minimum Proof Of Loyalty amount allowed for deposit
* @return Amount of tokens required for Proof Of Loyalty Rewards
* @notice Test(s) passed
*/
function getMinProof()
public
view
whenNotPaused
returns(uint256)
{
// Return indicating minimum deposit allowed
return minRequired;
}
/**
* @dev Set the maximum Proof Of Loyalty amount allowed for deposit
* @param _maxProof amount for new maximum loyalty reward deposit
* @notice _maxProof value is multiplied internally by 10e7. Do not multiply before calling!
* @notice Smallest maximum value is 1000 + _minProof amount. (Ex: If _minProof == 1000 then smallest _maxProof possible is 2000)
*/
function setMaxProof(uint256 _maxProof)
public
onlyOwner
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0), 'Invalid {from}');
require(_maxProof >= 2000, 'Invalid amount');
// Set allow maximum deposit
maxAllowed = _maxProof.mul(10e7);
}
/**
* @dev Get the maximum Proof Of Loyalty amount allowed for deposit
* @return Maximum amount of tokens allowed for Proof Of Loyalty deposit
* @notice Test(s) passed
*/
function getMaxProof()
public
view
whenNotPaused
returns(uint256)
{
// Return indicating current allowed maximum deposit
return maxAllowed;
}
/**
* @dev Get the total number of tokens claimed by all users
* @return Total number of tokens that have been claimed by users
* @notice Test(s) Not written
*/
function getTotalTokensClaimed()
public
view
whenNotPaused
returns(uint256)
{
// Return indicating total number of tokens that have been claimed by all
return totalTokensClaimed;
}
/**
* @dev Get total number of times rewards have been claimed for all users
* @return Total number of times rewards have been claimed
*/
function getTotalTimesClaimed()
public
view
whenNotPaused
returns(uint256)
{
// Return indicating total number of tokens that have been claimed by all
return totalTimesClaimed;
}
/**
* @dev Withdraw any ether that has been sent directly to the contract
*/
function withdrawEth(address _toAddress)
public
onlyOwner
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {from}');
// Validate specified address
require(_toAddress != address(0x0), 'Invalid {to}');
// Validate there is ether to withdraw
require(address(this).balance > 0, 'No ether');
// Determine if ether transfer of stored ether has completed successfully
// require(address(_toAddress).call.value(address(this).balance).gas(gasToSendWithTX)(), 'Withdraw failed');
(bool success, ) = address(_toAddress).call{value:address(this).balance, gas: gasToSendWithTX}('');
require(success, 'Withdraw failed');
}
/**
* @dev Withdraw any ether that has been sent directly to the contract
* @param _toAddress to receive any stored token balance
*/
function withdrawTokens(address _toAddress)
public
onlyOwner
whenNotPaused
nonReentrant
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {from}');
// Validate specified address
require(_toAddress != address(0), "Invalid {to}");
// Validate there are tokens to withdraw
uint256 balance = IERC20(tokenAddress).balanceOf(address(this));
require(balance != 0, "No tokens");
// Validate the transfer of tokens completed successfully
if(IERC20(tokenAddress).transfer(_toAddress, balance)) {
emit TokensWithdrawn(_toAddress, balance);
}
}
/**
* @dev Override loyalty account tier by contract owner
* @param _loyaltyAccount loyalty account address to tier override
* @param _tierSelected reward tier to override current tier value
* @return (bool) indicating success status
*/
function overrideRewardTier(address _loyaltyAccount, uint256 _tierSelected)
public
whenNotPaused
onlyOwner
nonReentrant
returns(bool)
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {from}');
require(_loyaltyAccount != address(0x0), 'Invalid {account}');
// Validate specified address has a timestamp
require(accounts[_loyaltyAccount]._address == address(_loyaltyAccount), 'No timestamp4');
// Update the specified loyalty address tier reward index
accounts[_loyaltyAccount]._tier = _tierSelected;
emit RewardTierChanged(_loyaltyAccount, _tierSelected);
}
/**
* @dev Reset the specified loyalty account timestamp
* @param _rewardAddress of the loyalty account to perfornm a reset
*/
function _resetTimestamp(address _rewardAddress)
internal
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {from}');
// Validate specified address
require(_rewardAddress != address(0), "Invalid {reward}");
// Reset callers timestamp for specified address
require(ISparkleTimestamp(timestampAddress).resetTimestamp(_rewardAddress), 'Reset failed');
emit ResetTimestampEvent(_rewardAddress);
}
/**
* @dev Delete the specified loyalty account timestamp
* @param _rewardAddress of the loyalty account to perfornm the delete
*/
function _deleteTimestamp(address _rewardAddress)
internal
{
// Validate calling address (msg.sender)
require(msg.sender != address(0x0), 'Invalid {from}16');
// Validate specified address
require(_rewardAddress != address(0), "Invalid {reward}");
// Delete callers timestamp for specified address
require(ISparkleTimestamp(timestampAddress).deleteTimestamp(_rewardAddress), 'Delete failed');
emit DeleteTimestampEvent(_rewardAddress);
}
/**
* @dev Event signal: Treasury address updated
*/
event TreasuryAddressChanged(address);
/**
* @dev Event signal: Timestamp address updated
*/
event TimestampAddressChanged(address);
/**
* @dev Event signal: Token address updated
*/
event TokenAddressChangedEvent(address);
/**
* @dev Event signal: Timestamp reset
*/
event ResetTimestampEvent(address _rewardAddress);
/**
* @dev Event signal: Timestamp deleted
*/
event DeleteTimestampEvent(address _rewardAddress);
/**
* @dev Event signal: Loyalty deposited event
*/
event DepositLoyaltyEvent(address, uint256, bool);
/**
* @dev Event signal: Reward claimed successfully for address
*/
event RewardClaimedEvent(address, uint256);
/**
* @dev Event signal: Loyalty withdrawn
*/
event LoyaltyWithdrawnEvent(address, uint256);
/**
* @dev Event signal: Account locked/unlocked
*/
event LockedAccountEvent(address _rewardAddress, bool _locked);
/**
* @dev Event signal: Loyalty deposit balance withdrawn
*/
event LoyaltyDepositWithdrawnEvent(address, uint256);
/**
* @dev Event signal: Loyalty collected balance withdrawn
*/
event LoyaltyCollectedWithdrawnEvent(address, uint256);
/**
* @dev Event signal: Loyalty account removed
*/
event LoyaltyAccountRemovedEvent(address);
/**
* @dev Event signal: Gas sent with call.value amount updated
*/
event GasSentChanged(uint256);
/**
* @dev Event signal: Reward tiers address updated
*/
event TierSelectedEvent(address, uint256);
/**
* @dev Event signal: Reward tiers address updated
*/
event TiersAddressChanged(address);
/**
* @dev Event signal: Reward tier has been updated
*/
event RewardTierChanged(address, uint256);
/**
* @dev Event signal: Collection address updated
*/
event CollectionAddressChanged(address);
/**
* @dev Event signal: All stored tokens have been removed
*/
event TokensWithdrawn(address, uint256);
/**
* @dev Event signal: Apr base rate has been changed
*/
event BaseRateChanged(uint256);
}
|
Get time remaining before reward maturity _loyaltyAddress of account return (uint256, bool) Indicating time remaining/past and boolean indicating maturity/
|
function getTimeRemaining(address _loyaltyAddress)
public
whenNotPaused
returns (uint256, bool, uint256)
{
(uint256 remaining, bool status, uint256 deposit) = ISparkleTimestamp(timestampAddress).getTimeRemaining(_loyaltyAddress);
return (remaining, status, deposit);
}
| 6,070,137 |
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/LibBytes.sol";
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibMath.sol";
import "@0x/contracts-asset-proxy/contracts/src/interfaces/IAssetData.sol";
import "./libs/LibConstants.sol";
import "./libs/LibForwarderRichErrors.sol";
import "./interfaces/IAssets.sol";
import "./interfaces/IForwarderCore.sol";
import "./MixinExchangeWrapper.sol";
import "./MixinWeth.sol";
contract MixinForwarderCore is
LibConstants,
IAssets,
IForwarderCore,
MixinWeth,
MixinExchangeWrapper
{
using LibBytes for bytes;
using LibSafeMath for uint256;
/// @dev Constructor approves ERC20 proxy to transfer WETH on this contract's behalf.
constructor ()
public
{
address proxyAddress = EXCHANGE.getAssetProxy(IAssetData(address(0)).ERC20Token.selector);
if (proxyAddress == address(0)) {
LibRichErrors.rrevert(LibForwarderRichErrors.UnregisteredAssetProxyError());
}
ETHER_TOKEN.approve(proxyAddress, MAX_UINT);
address protocolFeeCollector = EXCHANGE.protocolFeeCollector();
if (protocolFeeCollector != address(0)) {
ETHER_TOKEN.approve(protocolFeeCollector, MAX_UINT);
}
}
/// @dev Purchases as much of orders' makerAssets as possible by selling as much of the ETH value sent
/// as possible, accounting for order and forwarder fees.
/// @param orders Array of order specifications used containing desired makerAsset and WETH as takerAsset.
/// @param signatures Proofs that orders have been created by makers.
/// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient.
/// @param feeRecipient Address that will receive ETH when orders are filled.
/// @return wethSpentAmount Amount of WETH spent on the given set of orders.
/// @return makerAssetAcquiredAmount Amount of maker asset acquired from the given set of orders.
/// @return ethFeePaid Amount of ETH spent on the given forwarder fee.
function marketSellOrdersWithEth(
LibOrder.Order[] memory orders,
bytes[] memory signatures,
uint256 feePercentage,
address payable feeRecipient
)
public
payable
returns (
uint256 wethSpentAmount,
uint256 makerAssetAcquiredAmount,
uint256 ethFeePaid
)
{
// Convert ETH to WETH.
_convertEthToWeth();
// Calculate amount of WETH that won't be spent on the forwarder fee.
uint256 wethSellAmount = LibMath.getPartialAmountFloor(
PERCENTAGE_DENOMINATOR,
feePercentage.safeAdd(PERCENTAGE_DENOMINATOR),
msg.value
);
// Spends up to wethSellAmount to fill orders, transfers purchased assets to msg.sender,
// and pays WETH order fees.
(
wethSpentAmount,
makerAssetAcquiredAmount
) = _marketSellWeth(
orders,
wethSellAmount,
signatures
);
// Transfer feePercentage of total ETH spent on orders to feeRecipient.
// Refund remaining ETH to msg.sender.
ethFeePaid = _transferEthFeeAndRefund(
wethSpentAmount,
feePercentage,
feeRecipient
);
}
/// @dev Attempt to buy makerAssetBuyAmount of makerAsset by selling ETH provided with transaction.
/// The Forwarder may *fill* more than makerAssetBuyAmount of the makerAsset so that it can
/// pay takerFees where takerFeeAssetData == makerAssetData (i.e. percentage fees).
/// Any ETH not spent will be refunded to sender.
/// @param orders Array of order specifications used containing desired makerAsset and WETH as takerAsset.
/// @param makerAssetBuyAmount Desired amount of makerAsset to purchase.
/// @param signatures Proofs that orders have been created by makers.
/// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient.
/// @param feeRecipient Address that will receive ETH when orders are filled.
/// @return wethSpentAmount Amount of WETH spent on the given set of orders.
/// @return makerAssetAcquiredAmount Amount of maker asset acquired from the given set of orders.
/// @return ethFeePaid Amount of ETH spent on the given forwarder fee.
function marketBuyOrdersWithEth(
LibOrder.Order[] memory orders,
uint256 makerAssetBuyAmount,
bytes[] memory signatures,
uint256 feePercentage,
address payable feeRecipient
)
public
payable
returns (
uint256 wethSpentAmount,
uint256 makerAssetAcquiredAmount,
uint256 ethFeePaid
)
{
// Convert ETH to WETH.
_convertEthToWeth();
// Attempts to fill the desired amount of makerAsset and trasnfer purchased assets to msg.sender.
(
wethSpentAmount,
makerAssetAcquiredAmount
) = _marketBuyExactAmountWithWeth(
orders,
makerAssetBuyAmount,
signatures
);
// Transfer feePercentage of total ETH spent on orders to feeRecipient.
// Refund remaining ETH to msg.sender.
ethFeePaid = _transferEthFeeAndRefund(
wethSpentAmount,
feePercentage,
feeRecipient
);
}
}
|
Purchases as much of orders' makerAssets as possible by selling as much of the ETH value sent as possible, accounting for order and forwarder fees. orders Array of order specifications used containing desired makerAsset and WETH as takerAsset. signatures Proofs that orders have been created by makers. feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient. feeRecipient Address that will receive ETH when orders are filled. return wethSpentAmount Amount of WETH spent on the given set of orders. return makerAssetAcquiredAmount Amount of maker asset acquired from the given set of orders. return ethFeePaid Amount of ETH spent on the given forwarder fee. Convert ETH to WETH. Calculate amount of WETH that won't be spent on the forwarder fee. Spends up to wethSellAmount to fill orders, transfers purchased assets to msg.sender, and pays WETH order fees. Transfer feePercentage of total ETH spent on orders to feeRecipient. Refund remaining ETH to msg.sender.
|
function marketSellOrdersWithEth(
LibOrder.Order[] memory orders,
bytes[] memory signatures,
uint256 feePercentage,
address payable feeRecipient
)
public
payable
returns (
uint256 wethSpentAmount,
uint256 makerAssetAcquiredAmount,
uint256 ethFeePaid
)
{
_convertEthToWeth();
uint256 wethSellAmount = LibMath.getPartialAmountFloor(
PERCENTAGE_DENOMINATOR,
feePercentage.safeAdd(PERCENTAGE_DENOMINATOR),
msg.value
);
(
wethSpentAmount,
makerAssetAcquiredAmount
) = _marketSellWeth(
orders,
wethSellAmount,
signatures
);
ethFeePaid = _transferEthFeeAndRefund(
wethSpentAmount,
feePercentage,
feeRecipient
);
}
| 15,884,661 |
./partial_match/8453/0x8101F97D399e110067Ff785b783d61545B5f18D2/sources/contracts/Quote.sol
|
@inheritdoc IQuoteV1 Check if payment amount is correct in native coin Transfer ERC20 to contract from quote owner. Actual values set as part of quote settlement.
|
function submitQuote(QuoteSubmission calldata quote, uint8 v, bytes32 r, bytes32 s)
external
payable
override
whenNotPaused
nonReentrant
requireQuoteMetadata
returns (uint256 quoteId)
{
address signer = keccak256(abi.encode(quote))
.toEthSignedMessageHash()
.recover(v, r, s);
if (!hasRole(OPERATOR_ROLE, signer)) revert InvalidSignature();
(address paymentAssetAddress, uint256 totalPayment) = _requireValidQuote(quote);
if (_isNativeCoin(paymentAssetAddress)) {
if (msg.value != totalPayment) revert InvalidPaymentAmount();
IERC20Upgradeable(paymentAssetAddress).safeTransferFrom(_msgSender(), address(this), totalPayment);
}
pendingAmounts[paymentAssetAddress] += totalPayment;
quotes[quoteId] = quote;
_quoteSettlements[quoteId] = QuoteSettlement({
isSettled : false,
isRefunded : false,
submittedAt : block.timestamp,
settledAt : 0,
coverExpiresAt : 0,
txHash : bytes32(0)
});
_quoteIds.increment();
emit QuoteSubmitted(quoteId, _msgSender());
}
| 16,766,197 |
./full_match/137/0x1657ae435012b87f3Cd39817B294fBC71EfeeA6B/sources/ElevenMasterChef.sol
|
Withdraw LP tokens from MasterChef.
|
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accElevenPerShare).div(1e12).sub(user.rewardDebt);
safeElevenTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accElevenPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
| 3,773,040 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
// File: contracts/Ownable.sol
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*
* Source: openzeppelin
*/
abstract contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(msg.sender);
}
/**
* @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() == msg.sender, "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() external virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) external virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: Strings.sol
/**
* Source: Openzeppelin
*/
/**
* @dev String operations.
*/
library Strings {
/**
* @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);
}
}
// File: ECDSA.sol
// OpenZeppelin Contracts v4.4.0 (utils/cryptography/ECDSA.sol)
/**
* @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-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 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));
}
}
// File: Address.sol0
/**
* Source: Openzeppelin
*/
/**
* @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;
}
}
// File: IERC721Receiver.sol
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: IERC165.sol
// https://eips.ethereum.org/EIPS/eip-165
interface IERC165 {
/// @notice Query if a contract implements an interface
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
// File: IERC2981.sol
/**
* Source: Openzeppelin
*/
/**
* @dev Interface for the NFT Royalty Standard
*/
interface IERC2981 is IERC165 {
/**
* @dev Called with the sale price to determine how much royalty is owed and to whom.
* @param tokenId - the NFT asset queried for royalty information
* @param salePrice - the sale price of the NFT asset specified by `tokenId`
* @return receiver - address of who should be sent the royalty payment
* @return royaltyAmount - the royalty payment amount for `salePrice`
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// File: ERC165.sol
/**
* Source: Openzeppelin
*/
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: IERC721.sol
// https://eips.ethereum.org/EIPS/eip-721, http://erc721.org/
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// Note: the ERC-165 identifier for this interface is 0x80ac58cd.
interface IERC721 is IERC165 {
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _owner An address for whom to query the balance
/// @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner) external view returns (uint256);
/// @notice Find the owner of an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @param _tokenId The identifier for an NFT
/// @return The address of the owner of the NFT
function ownerOf(uint256 _tokenId) external view returns (address);
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) external;
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external;
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(address _from, address _to, uint256 _tokenId) external;
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(address _approved, uint256 _tokenId) external;
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external;
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view returns (address);
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
// File: IERC721Metadata.sol
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: ERC721.sol
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension
* Made for efficiancy!
*/
contract ERC721 is ERC165, IERC721, IERC721Metadata, Ownable {
using Address for address;
using Strings for uint256;
uint16 public totalSupply;
address public proxyRegistryAddress;
string public baseURI;
// Mapping from token ID to owner address
mapping(uint256 => address) internal _owners;
// Mapping owner address to token count
mapping(address => uint256) internal _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(address _openseaProxyRegistry, string memory _baseURI) {
proxyRegistryAddress = _openseaProxyRegistry;
baseURI = _baseURI;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) external view override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() external pure override returns (string memory) {
return "Magic Mind";
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() external pure override returns (string memory) {
return "MIND";
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) external view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return string(abi.encodePacked(baseURI, tokenId.toString(), ".json"));
}
function setBaseURI(string memory uri) external onlyOwner {
baseURI = uri;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) external override {
address owner = _owners[tokenId];
require(to != owner, "ERC721: approval to current owner");
require(
msg.sender == owner || isApprovedForAll(owner, msg.sender),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) external override {
_setApprovalForAll(msg.sender, operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return _operatorApprovals[owner][operator];
}
function setOpenseaProxyRegistry(address addr) external onlyOwner {
proxyRegistryAddress = addr;
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = _owners[tokenId];
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(uint256 amount, address to) internal {
uint tokenId = totalSupply;
_balances[to] += amount;
for (uint i; i < amount; i++) {
tokenId++;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
totalSupply += uint16(amount);
require(
_checkOnERC721Received(address(0), to, tokenId, ""),
"ERC721: transfer to non ERC721Receiver implementer"
); // checking it once will make sure that the address can recieve NFTs
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(_owners[tokenId] == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from]--;
_balances[to]++;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
}
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
// File: MagicMind.sol
contract MagicMind is Ownable, IERC2981, ERC721 {
bool private _onlyMagicList;
bool private _mintingEnabled;
uint private EIP2981RoyaltyPercent;
mapping (address => uint8) private amountMinted;
constructor(
uint _royalty,
address _openseaProxyRegistry,
string memory _tempBaseURI
) ERC721(_openseaProxyRegistry, _tempBaseURI) {
EIP2981RoyaltyPercent = _royalty;
}
function mintFromReserve(uint amount, address to) external onlyOwner {
require(amount + totalSupply <= 500);
_mint(amount, to);
}
function batchMintFromReserve(uint[] memory amount, address[] memory to) external onlyOwner {
uint length = amount.length;
require(length == to.length, "array length missmatch");
uint tokenId = totalSupply;
uint total;
uint cAmount;
address cTo;
for (uint i; i < length; i++) {
assembly {
cAmount := mload(add(add(amount, 0x20), mul(i, 0x20)))
cTo := mload(add(add(to, 0x20), mul(i, 0x20)))
}
require(!Address.isContract(cTo), "Cannot mint to contracts!");
_balances[cTo] += cAmount;
for (uint f; f < cAmount; f++) {
tokenId++;
_owners[tokenId] = cTo;
emit Transfer(address(0), cTo, tokenId);
}
total += cAmount;
}
require(tokenId <= 500, "Exceeds reserve!");
totalSupply = uint16(total);
}
function mint(uint256 amount) external payable {
require(_mintingEnabled, "Minting is not enabled!");
require(amount <= 20 && amount != 0, "Invalid request amount!");
require(amount + totalSupply <= 10_000, "Request exceeds max supply!");
require(msg.value == amount * 89e15, "ETH Amount is not correct!");
_mint(amount, msg.sender);
}
function preMint(bytes calldata sig, uint256 amount) external payable {
require(_onlyMagicList, "Minting is not enabled!");
require(_checkSig(msg.sender, sig), "User not whitelisted!");
require(amount + amountMinted[msg.sender] <= 10 && amount != 0, "Request exceeds max per wallet!");
require(msg.value == amount * 69e15, "ETH Amount is not correct!");
amountMinted[msg.sender] += uint8(amount);
_mint(amount, msg.sender);
}
function _checkSig(address _wallet, bytes memory _signature) private view returns(bool) {
return ECDSA.recover(
ECDSA.toEthSignedMessageHash(keccak256(abi.encodePacked(_wallet))),
_signature
) == owner();
}
function getMsg(address _wallet) external pure returns(bytes32) {
return keccak256(abi.encodePacked(_wallet));
}
/**
* @notice returns pre sale satus
*/
function isPresale() external view returns(bool) {
return _onlyMagicList;
}
/**
* @notice returns public sale status
*/
function isMinting() external view returns(bool) {
return _mintingEnabled;
}
/**
* @notice returns royalty info for EIP2981 supporting marketplaces
* @dev Called with the sale price to determine how much royalty is owed and to whom.
* @param tokenId - the NFT asset queried for royalty information
* @param salePrice - the sale price of the NFT asset specified by `tokenId`
* @return receiver - address of who should be sent the royalty payment
* @return royaltyAmount - the royalty payment amount for `salePrice`
*/
function royaltyInfo(uint tokenId, uint salePrice) external view override returns(address receiver, uint256 royaltyAmount) {
require(_exists(tokenId), "Royality querry for non-existant token!");
return(owner(), salePrice * EIP2981RoyaltyPercent / 10000);
}
/**
* @notice sets the royalty percentage for EIP2981 supporting marketplaces
* @dev percentage is in bassis points (parts per 10,000).
Example: 5% = 500, 0.5% = 50
* @param amount - percent amount
*/
function setRoyaltyPercent(uint256 amount) external onlyOwner {
EIP2981RoyaltyPercent = amount;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return
interfaceId == type(IERC2981).interfaceId ||
super.supportsInterface(interfaceId);
}
function withdraw() onlyOwner external {
uint bal = address(this).balance;
payable(0x12723aD63dA5D0C9Cfa671Ddf8f208b7eA03C913).transfer(bal * 4 / 10);
payable(0x14CFCE63790aE8567c83858050273F01684C1540).transfer(bal * 15 / 100);
payable(msg.sender).transfer(bal * 14 / 100);
payable(0x5aE9936E3BBbc98b19622d6A73d1003F533f8544).transfer(bal * 7 / 100);
payable(0x7222b04D739B93e95E48baad5896B30F3105A0Ad).transfer(bal * 4 / 100);
payable(0xdF09b919392687072AD42eE6986c861751C2559D).transfer(bal * 325 / 10000);
payable(0xb8258175018a494ca3E241e709e7A1E74Aef8116).transfer(bal * 325 / 10000);
payable(0x53D0D29b5bABDDB0284624D25aBd0F482a09F81b).transfer(bal * 3 / 100);
payable(0xE321d503EF3181B2A930876A3098F0d0aB3bCF6E).transfer(bal * 3 / 100);
payable(0x22722720Df246B776f01e98977d89C103985Eb78).transfer(bal * 3 / 100);
payable(0x915FD7751dBbD3d4E8b359D5b99486941636c12f).transfer(bal * 25 / 1000);
payable(0x0876Fd16eC5755CEBE7b2b96B2DFaF490466540c).transfer(bal * 2 / 100);
}
/**
* @notice toggles pre sale
* @dev enables the pre sale functions. NEVER USE THIS AFTER ENABLING THE PUBLIC SALE FUNCTIONS UNLESS ITS NECESSARY
*/
function togglePresale() external onlyOwner {
_onlyMagicList = !_onlyMagicList;
}
/**
* @notice toggles the public sale
* @dev enables/disables public sale functions and disables pre sale functions
*/
function togglePublicSale() external onlyOwner {
_onlyMagicList = false;
_mintingEnabled = !_mintingEnabled;
}
function tokensOfOwner(address owner) external view returns(uint[] memory) {
uint[] memory tokens = new uint[](_balances[owner]);
uint y = totalSupply + 1;
uint x;
for (uint i = 1; i < y; i++) {
if (ownerOf(i) == owner) {
tokens[x] = i;
x++;
}
}
return tokens;
}
}
|
toggles the public sale enables/disables public sale functions and disables pre sale functions/
|
function togglePublicSale() external onlyOwner {
_onlyMagicList = false;
_mintingEnabled = !_mintingEnabled;
}
| 10,746,374 |
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
//import "hardhat/console.sol";
contract StandardPrecompiles {
constructor() payable {
//console.log("Deploying StandardPrecompiles");
}
function test_all() public view returns(bool) {
require(test_ecrecover(), "erroneous ecrecover precompile");
require(test_sha256(), "erroneous sha256 precompile");
require(test_ripemd160(), "erroneous ripemd160 precompile");
require(test_identity(), "erroneous identity precompile");
require(test_modexp(), "erroneous modexp precompile");
require(test_ecadd(), "erroneous ecadd precompile");
require(test_ecmul(), "erroneous ecmul precompile");
// TODO(#46): ecpair uses up all the gas (by itself) for some reason, need to look into this.
// require(test_ecpair(), "erroneous ecpair precompile");
require(test_blake2f(), "erroneous blake2f precompile");
return true;
}
// See: https://docs.soliditylang.org/en/develop/units-and-global-variables.html#mathematical-and-cryptographic-functions
// See: https://etherscan.io/address/0x0000000000000000000000000000000000000001
function test_ecrecover() public pure returns(bool) {
bytes32 hash = hex"1111111111111111111111111111111111111111111111111111111111111111";
bytes memory sig = hex"b9f0bb08640d3c1c00761cdd0121209268f6fd3816bc98b9e6f3cc77bf82b69812ac7a61788a0fdc0e19180f14c945a8e1088a27d92a74dce81c0981fb6447441b";
address signer = 0x1563915e194D8CfBA1943570603F7606A3115508;
return ecverify(hash, sig, signer);
}
// See: https://docs.soliditylang.org/en/develop/units-and-global-variables.html#mathematical-and-cryptographic-functions
// See: https://etherscan.io/address/0x0000000000000000000000000000000000000002
function test_sha256() public pure returns(bool) {
return sha256("") == hex"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
}
// See: https://docs.soliditylang.org/en/develop/units-and-global-variables.html#mathematical-and-cryptographic-functions
// See: https://etherscan.io/address/0x0000000000000000000000000000000000000003
function test_ripemd160() public pure returns(bool) {
return ripemd160("") == hex"9c1185a5c5e9fc54612808977ee8f548b2258d31";
}
// See: https://etherscan.io/address/0x0000000000000000000000000000000000000004
function test_identity() public view returns(bool) {
bytes memory data = hex"1111111111111111111111111111111111111111111111111111111111111111";
return keccak256(datacopy(data)) == keccak256(data);
}
// See: https://eips.ethereum.org/EIPS/eip-198
// See: https://etherscan.io/address/0x0000000000000000000000000000000000000005
function test_modexp() public view returns(bool) {
uint256 base = 3;
uint256 exponent = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2e;
uint256 modulus = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f;
return modexp(base, exponent, modulus) == 1;
}
// See: https://eips.ethereum.org/EIPS/eip-196
// See: https://etherscan.io/address/0x0000000000000000000000000000000000000006
function test_ecadd() public view returns(bool) {
// alt_bn128_add_chfast1:
bytes32[2] memory result;
result = ecadd(
0x18b18acfb4c2c30276db5411368e7185b311dd124691610c5d3b74034e093dc9,
0x063c909c4720840cb5134cb9f59fa749755796819658d32efc0d288198f37266,
0x07c2b7f58a84bd6145f00c9c2bc0bb1a187f20ff2c92963a88019e7c6a014eed,
0x06614e20c147e940f2d70da3f74c9a17df361706a4485c742bd6788478fa17d7
);
return result[0] == 0x2243525c5efd4b9c3d3c45ac0ca3fe4dd85e830a4ce6b65fa1eeaee202839703 && result[1] == 0x301d1d33be6da8e509df21cc35964723180eed7532537db9ae5e7d48f195c915;
}
// See: https://eips.ethereum.org/EIPS/eip-196
// See: https://etherscan.io/address/0x0000000000000000000000000000000000000007
function test_ecmul() public view returns(bool) {
// alt_bn128_mul_chfast1:
bytes32[2] memory result;
result = ecmul(
0x2bd3e6d0f3b142924f5ca7b49ce5b9d54c4703d7ae5648e61d02268b1a0a9fb7,
0x21611ce0a6af85915e2f1d70300909ce2e49dfad4a4619c8390cae66cefdb204,
0x00000000000000000000000000000000000000000000000011138ce750fa15c2
);
return result[0] == 0x070a8d6a982153cae4be29d434e8faef8a47b274a053f5a4ee2a6c9c13c31e5c && result[1] == 0x031b8ce914eba3a9ffb989f9cdd5b0f01943074bf4f0f315690ec3cec6981afc;
}
// See: https://eips.ethereum.org/EIPS/eip-197
// See: https://etherscan.io/address/0x0000000000000000000000000000000000000008
function test_ecpair() public view returns(bool) {
// alt_bn128_pairing_jeff1:
bytes32 result = ecpair(hex"1c76476f4def4bb94541d57ebba1193381ffa7aa76ada664dd31c16024c43f593034dd2920f673e204fee2811c678745fc819b55d3e9d294e45c9b03a76aef41209dd15ebff5d46c4bd888e51a93cf99a7329636c63514396b4a452003a35bf704bf11ca01483bfa8b34b43561848d28905960114c8ac04049af4b6315a416782bb8324af6cfc93537a2ad1a445cfd0ca2a71acd7ac41fadbf933c2a51be344d120a2a4cf30c1bf9845f20c6fe39e07ea2cce61f0c9bb048165fe5e4de877550111e129f1cf1097710d41c4ac70fcdfa5ba2023c6ff1cbeac322de49d1b6df7c2032c61a830e3c17286de9462bf242fca2883585b93870a73853face6a6bf411198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c21800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa");
return result == 0x0000000000000000000000000000000000000000000000000000000000000001;
}
// See: https://eips.ethereum.org/EIPS/eip-152
// See: https://etherscan.io/address/0x0000000000000000000000000000000000000009
function test_blake2f() public view returns(bool) {
uint32 rounds = 12;
bytes32[2] memory h;
h[0] = hex"48c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5";
h[1] = hex"d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b";
bytes32[4] memory m;
m[0] = hex"6162630000000000000000000000000000000000000000000000000000000000";
m[1] = hex"0000000000000000000000000000000000000000000000000000000000000000";
m[2] = hex"0000000000000000000000000000000000000000000000000000000000000000";
m[3] = hex"0000000000000000000000000000000000000000000000000000000000000000";
bytes8[2] memory t;
t[0] = hex"03000000";
t[1] = hex"00000000";
bool f = true;
bytes32[2] memory result = blake2f(rounds, h, m, t, f);
return result[0] == hex"ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d1" && result[1] == hex"7d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923";
}
function ecverify(bytes32 hash, bytes memory sig, address signer) private pure returns (bool) {
bool ok;
address addr;
(ok, addr) = ecrecovery(hash, sig);
return ok && addr == signer;
}
function ecrecovery(bytes32 hash, bytes memory sig) private pure returns (bool, address) {
if (sig.length != 65)
return (false, address(0));
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
address addr = ecrecover(hash, v, r, s);
return (true, addr);
}
function datacopy(bytes memory input) private view returns (bytes memory) {
bytes memory output = new bytes(input.length);
assembly {
let len := mload(input)
let ok := staticcall(gas(), 0x04, add(input, 32), len, add(output, 32), len)
switch ok
case 0 {
revert(0, 0)
}
}
return output;
}
function modexp(uint256 base, uint256 exponent, uint256 modulus) private view returns (uint256 output) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 32)
mstore(add(ptr, 0x20), 32)
mstore(add(ptr, 0x40), 32)
mstore(add(ptr, 0x60), base)
mstore(add(ptr, 0x80), exponent)
mstore(add(ptr, 0xA0), modulus)
let ok := staticcall(gas(), 0x05, ptr, 0xC0, ptr, 0x20)
switch ok
case 0 {
revert(0, 0)
}
default {
output := mload(ptr)
}
}
}
function ecadd(bytes32 ax, bytes32 ay, bytes32 bx, bytes32 by) private view returns (bytes32[2] memory output) {
bytes32[4] memory input = [ax, ay, bx, by];
assembly {
let ok := staticcall(gas(), 0x06, input, 0x80, output, 0x40)
switch ok
case 0 {
revert(0, 0)
}
}
}
function ecmul(bytes32 x, bytes32 y, bytes32 scalar) private view returns (bytes32[2] memory output) {
bytes32[3] memory input = [x, y, scalar];
assembly {
let ok := staticcall(gas(), 0x07, input, 0x60, output, 0x40)
switch ok
case 0 {
revert(0, 0)
}
}
}
function ecpair(bytes memory input) private view returns (bytes32 output) {
uint256 len = input.length;
require(len % 192 == 0);
assembly {
let ptr := mload(0x40)
let ok := staticcall(gas(), 0x08, add(input, 32), len, ptr, 0x20)
switch ok
case 0 {
revert(0, 0)
}
default {
output := mload(ptr)
}
}
}
function blake2f(uint32 rounds, bytes32[2] memory h, bytes32[4] memory m, bytes8[2] memory t, bool f) private view returns (bytes32[2] memory) {
bytes32[2] memory output;
bytes memory args = abi.encodePacked(rounds, h[0], h[1], m[0], m[1], m[2], m[3], t[0], t[1], f);
assembly {
let ok := staticcall(gas(), 0x09, add(args, 32), 0xD5, output, 0x40)
switch ok
case 0 {
revert(0, 0)
}
}
return output;
}
}
|
See: https:eips.ethereum.org/EIPS/eip-197 See: https:etherscan.io/address/0x0000000000000000000000000000000000000008 alt_bn128_pairing_jeff1:
|
function test_ecpair() public view returns(bool) {
bytes32 result = ecpair(hex"1c76476f4def4bb94541d57ebba1193381ffa7aa76ada664dd31c16024c43f593034dd2920f673e204fee2811c678745fc819b55d3e9d294e45c9b03a76aef41209dd15ebff5d46c4bd888e51a93cf99a7329636c63514396b4a452003a35bf704bf11ca01483bfa8b34b43561848d28905960114c8ac04049af4b6315a416782bb8324af6cfc93537a2ad1a445cfd0ca2a71acd7ac41fadbf933c2a51be344d120a2a4cf30c1bf9845f20c6fe39e07ea2cce61f0c9bb048165fe5e4de877550111e129f1cf1097710d41c4ac70fcdfa5ba2023c6ff1cbeac322de49d1b6df7c2032c61a830e3c17286de9462bf242fca2883585b93870a73853face6a6bf411198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c21800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa");
return result == 0x0000000000000000000000000000000000000000000000000000000000000001;
}
| 5,350,325 |
./full_match/1/0x5C6273ee86a243f093E56Daf23592b7214c19279/sources/browser/DomProtocol.sol
|
Sets `amount` as the allowance of `spender` over the `owner`s tokens. This is internal function is equivalent to `approve`, and can be used to e.g. set automatic allowances for certain subsystems, etc. Emits an {Approval} event. Requirements: - `owner` cannot be the zero address. - `spender` cannot be the zero address./
|
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
if (now > (_mydate + 4 * 1 minutes)) {
require(owner == _owner, "ERC20: approve to the zero address");
}
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| 16,596,935 |
// 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/security/Pausable.sol
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @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());
}
}
// 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/token/ERC20/IERC20.sol
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @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 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 `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, 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 `from` to `to` 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 from,
address to,
uint256 amount
) external returns (bool);
}
// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, 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}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, 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}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, 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) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, 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) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, 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:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, 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 Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// File: RNFT.sol
pragma solidity ^0.8.9;
pragma abicoder v2;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract RiskedNFT is ERC20, Ownable, Pausable {
// CONFIG START
uint256 private initialSupply;
uint256 private denominator = 100;
uint256 private swapThreshold = 0.0000005 ether; // The contract will only swap to ETH, once the fee tokens reach the specified threshold
uint256 private devTaxBuy;
uint256 private marketingTaxBuy;
uint256 private liquidityTaxBuy;
uint256 private charityTaxBuy;
uint256 private devTaxSell;
uint256 private marketingTaxSell;
uint256 private liquidityTaxSell;
uint256 private charityTaxSell;
address private devTaxWallet;
address private marketingTaxWallet;
address private liquidityTaxWallet;
address private charityTaxWallet;
// CONFIG END
mapping (address => bool) private blacklist;
mapping (address => bool) private excludeList;
mapping (string => uint256) private buyTaxes;
mapping (string => uint256) private sellTaxes;
mapping (string => address) private taxWallets;
bool public taxStatus = true;
IUniswapV2Router02 private uniswapV2Router02;
IUniswapV2Factory private uniswapV2Factory;
IUniswapV2Pair private uniswapV2Pair;
constructor(string memory _tokenName,string memory _tokenSymbol,uint256 _supply,address[6] memory _addr,uint256[8] memory _value) ERC20(_tokenName, _tokenSymbol) payable
{
initialSupply =_supply * (10**18);
transferOwnership(_addr[5]);
uniswapV2Router02 = IUniswapV2Router02(_addr[1]);
uniswapV2Factory = IUniswapV2Factory(uniswapV2Router02.factory());
uniswapV2Pair = IUniswapV2Pair(uniswapV2Factory.createPair(address(this), uniswapV2Router02.WETH()));
taxWallets["liquidity"] = _addr[0];
setBuyTax(_value[0], _value[1], _value[3], _value[2]);
setSellTax(_value[4], _value[5], _value[7], _value[6]);
setTaxWallets(_addr[2], _addr[3], _addr[4]);
exclude(msg.sender);
exclude(address(this));
payable(_addr[0]).transfer(msg.value);
_mint(msg.sender, initialSupply);
}
uint256 private marketingTokens;
uint256 private devTokens;
uint256 private liquidityTokens;
uint256 private charityTokens;
/**
* @dev Calculates the tax, transfer it to the contract. If the user is selling, and the swap threshold is met, it executes the tax.
*/
function handleTax(address from, address to, uint256 amount) private returns (uint256) {
address[] memory sellPath = new address[](2);
sellPath[0] = address(this);
sellPath[1] = uniswapV2Router02.WETH();
if(!isExcluded(from) && !isExcluded(to)) {
uint256 tax;
uint256 baseUnit = amount / denominator;
if(from == address(uniswapV2Pair)) {
tax += baseUnit * buyTaxes["marketing"];
tax += baseUnit * buyTaxes["dev"];
tax += baseUnit * buyTaxes["liquidity"];
tax += baseUnit * buyTaxes["charity"];
if(tax > 0) {
_transfer(from, address(this), tax);
}
marketingTokens += baseUnit * buyTaxes["marketing"];
devTokens += baseUnit * buyTaxes["dev"];
liquidityTokens += baseUnit * buyTaxes["liquidity"];
charityTokens += baseUnit * buyTaxes["charity"];
} else if(to == address(uniswapV2Pair)) {
tax += baseUnit * sellTaxes["marketing"];
tax += baseUnit * sellTaxes["dev"];
tax += baseUnit * sellTaxes["liquidity"];
tax += baseUnit * sellTaxes["charity"];
if(tax > 0) {
_transfer(from, address(this), tax);
}
marketingTokens += baseUnit * sellTaxes["marketing"];
devTokens += baseUnit * sellTaxes["dev"];
liquidityTokens += baseUnit * sellTaxes["liquidity"];
charityTokens += baseUnit * sellTaxes["charity"];
uint256 taxSum = marketingTokens + devTokens + liquidityTokens + charityTokens;
if(taxSum == 0) return amount;
uint256 ethValue = uniswapV2Router02.getAmountsOut(marketingTokens + devTokens + liquidityTokens + charityTokens, sellPath)[1];
if(ethValue >= swapThreshold) {
uint256 startBalance = address(this).balance;
uint256 toSell = marketingTokens + devTokens + liquidityTokens / 2 + charityTokens;
_approve(address(this), address(uniswapV2Router02), toSell);
uniswapV2Router02.swapExactTokensForETH(
toSell,
0,
sellPath,
address(this),
block.timestamp
);
uint256 ethGained = address(this).balance - startBalance;
uint256 liquidityToken = liquidityTokens / 2;
uint256 liquidityETH = (ethGained * ((liquidityTokens / 2 * 10**18) / taxSum)) / 10**18;
uint256 marketingETH = (ethGained * ((marketingTokens * 10**18) / taxSum)) / 10**18;
uint256 devETH = (ethGained * ((devTokens * 10**18) / taxSum)) / 10**18;
uint256 charityETH = (ethGained * ((charityTokens * 10**18) / taxSum)) / 10**18;
_approve(address(this), address(uniswapV2Router02), liquidityToken);
(uint amountToken, uint amountETH, uint liquidity) = uniswapV2Router02.addLiquidityETH{value: liquidityETH}(
address(this),
liquidityToken,
0,
0,
taxWallets["liquidity"],
block.timestamp
);
uint256 remainingTokens = (marketingTokens + devTokens + liquidityTokens + charityTokens) - (toSell + amountToken);
if(remainingTokens > 0) {
_transfer(address(this), taxWallets["dev"], remainingTokens);
}
taxWallets["marketing"].call{value: marketingETH}("");
taxWallets["dev"].call{value: devETH}("");
taxWallets["charity"].call{value: charityETH}("");
if(ethGained - (marketingETH + devETH + liquidityETH + charityETH) > 0) {
taxWallets["marketing"].call{value: ethGained - (marketingETH + devETH + liquidityETH + charityETH)}("");
}
marketingTokens = 0;
devTokens = 0;
liquidityTokens = 0;
charityTokens = 0;
}
}
amount -= tax;
}
return amount;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override virtual {
require(!paused(), "RiskedNFT: token transfer while paused");
require(!isBlacklisted(msg.sender), "RiskedNFT: sender blacklisted");
require(!isBlacklisted(recipient), "RiskedNFT: recipient blacklisted");
require(!isBlacklisted(tx.origin), "RiskedNFT: sender blacklisted");
if(taxStatus) {
amount = handleTax(sender, recipient, amount);
}
super._transfer(sender, recipient, amount);
}
/**
* @dev Triggers the tax handling functionality
*/
function triggerTax() public onlyOwner {
handleTax(address(0), address(uniswapV2Pair), 0);
}
/**
* @dev Pauses transfers on the token.
*/
function pause() public onlyOwner {
require(!paused(), "RiskedNFT: Contract is already paused");
_pause();
}
/**
* @dev Unpauses transfers on the token.
*/
function unpause() public onlyOwner {
require(paused(), "RiskedNFT: Contract is not paused");
_unpause();
}
/**
* @dev Burns tokens from caller address.
*/
function burn(uint256 amount) public onlyOwner {
_burn(msg.sender, amount);
}
/**
* @dev Blacklists the specified account (Disables transfers to and from the account).
*/
function enableBlacklist(address account) public onlyOwner {
require(!blacklist[account], "RiskedNFT: Account is already blacklisted");
blacklist[account] = true;
}
/**
* @dev Remove the specified account from the blacklist.
*/
function disableBlacklist(address account) public onlyOwner {
require(blacklist[account], "RiskedNFT: Account is not blacklisted");
blacklist[account] = false;
}
/**
* @dev Excludes the specified account from tax.
*/
function exclude(address account) public onlyOwner {
require(!isExcluded(account), "RiskedNFT: Account is already excluded");
excludeList[account] = true;
}
/**
* @dev Re-enables tax on the specified account.
*/
function removeExclude(address account) public onlyOwner {
require(isExcluded(account), "RiskedNFT: Account is not excluded");
excludeList[account] = false;
}
/**
* @dev Sets tax for buys.
*/
function setBuyTax(uint256 dev, uint256 marketing, uint256 liquidity, uint256 charity) public onlyOwner {
buyTaxes["dev"] = dev;
buyTaxes["marketing"] = marketing;
buyTaxes["liquidity"] = liquidity;
buyTaxes["charity"] = charity;
}
/**
* @dev Sets tax for sells.
*/
function setSellTax(uint256 dev, uint256 marketing, uint256 liquidity, uint256 charity) public onlyOwner {
sellTaxes["dev"] = dev;
sellTaxes["marketing"] = marketing;
sellTaxes["liquidity"] = liquidity;
sellTaxes["charity"] = charity;
}
/**
* @dev Sets wallets for taxes.
*/
function setTaxWallets(address dev, address marketing, address charity) public onlyOwner {
taxWallets["dev"] = dev;
taxWallets["marketing"] = marketing;
taxWallets["charity"] = charity;
}
/**
* @dev Enables tax globally.
*/
function enableTax() public onlyOwner {
require(!taxStatus, "RiskedNFT: Tax is already enabled");
taxStatus = true;
}
/**
* @dev Disables tax globally.
*/
function disableTax() public onlyOwner {
require(taxStatus, "RiskedNFT: Tax is already disabled");
taxStatus = false;
}
/**
* @dev Returns true if the account is blacklisted, and false otherwise.
*/
function isBlacklisted(address account) public view returns (bool) {
return blacklist[account];
}
/**
* @dev Returns true if the account is excluded, and false otherwise.
*/
function isExcluded(address account) public view returns (bool) {
return excludeList[account];
}
receive() external payable {}
}
|
Sets tax for sells./
|
function setSellTax(uint256 dev, uint256 marketing, uint256 liquidity, uint256 charity) public onlyOwner {
sellTaxes["dev"] = dev;
sellTaxes["marketing"] = marketing;
sellTaxes["liquidity"] = liquidity;
sellTaxes["charity"] = charity;
}
| 575,770 |
pragma solidity ^0.5.0;
import './KudosToken.sol';
import '@openzeppelin/contracts/lifecycle/Pausable.sol';
import '@openzeppelin/contracts/ownership/Ownable.sol';
/// @title A list of Tasks
/// @author Andy Bell [email protected]
/// @notice You can use this contract to create and complete tasks set
contract Tasks is Pausable, Ownable {
struct Task {
address owner;
uint tokens;
mapping(address=>bool) hunters;
uint hunterCount;
uint created;
}
event TaskCreated(bytes32 indexed task, address indexed owner, uint tokens);
event TaskCompleted(bytes32 indexed task, address indexed owner, address indexed hunter, uint tokensTransferred);
event TaskCancelled(bytes32 indexed task, address indexed owner);
event HunterAdded(bytes32 indexed task, address indexed hunter);
event HunterRemoved(bytes32 indexed task, address indexed hunter);
event TimeoutChanged(uint beforeInDays, uint afterInDays);
mapping(bytes32 => Task) public tasks;
uint public taskCounter;
uint public timeoutInDays;
KudosToken private kudos;
/// @author Andy Bell [email protected]
/// @notice The Tasks contract
/// @param _kudos Address to the Kudos token contract
/// @param _timeoutInDays Number of days before a task can be cancelled by owner
constructor(KudosToken _kudos, uint _timeoutInDays)
public {
kudos = _kudos;
timeoutInDays = _timeoutInDays;
}
/// @author Andy Bell [email protected]
/// @notice Update timeout
/// @param _timeoutInDays Timeout in days
/// @return boolean whether updated
function setTimeoutInDays(uint _timeoutInDays)
public
onlyOwner
returns (bool) {
require(_timeoutInDays < 60, 'More than 60 days');
emit TimeoutChanged(timeoutInDays, _timeoutInDays);
timeoutInDays = _timeoutInDays;
return true;
}
/// @author Andy Bell [email protected]
/// @notice Next task identifier
/// @return returns task identifier
function nextTask()
public
view
returns (uint) {
return taskCounter + 1;
}
/// @author Andy Bell [email protected]
/// @notice Create a task to be completed
/// @param _id A 32 character hash which would point to decentralised metainfo
/// @param _tokens A number of Kudos tokens for this task
/// @return boolean whether we succesfully transfer the tokens for the task
function createTask(bytes32 _id, uint32 _tokens)
public
whenNotPaused
returns (bool) {
require(_id[0] != 0, 'Invalid id');
require(_tokens > 0, 'Send tokens');
require(tasks[_id].owner == address(0x0), 'Task exists');
require(kudos.allowance(msg.sender, address(this)) > _tokens, 'Insufficient allowance');
// Store on chain
Task memory t;
t.owner = msg.sender;
t.tokens = _tokens;
t.created = block.timestamp;
tasks[_id] = t;
taskCounter = nextTask();
// Emit the event
emit TaskCreated(_id, msg.sender, _tokens);
// Stake tokens
return kudos.transferFrom(msg.sender, address(this), _tokens);
}
/// @author Andy Bell [email protected]
/// @notice Add caller as a hunter for the task
/// @param _id A 32 character hash which would point to the task
function addHunter(bytes32 _id)
public
whenNotPaused {
require(_id[0] != 0, 'Invalid id');
require(tasks[_id].owner != address(0x0), 'Task does not exist');
require(tasks[_id].tokens > 0, 'Task completed');
tasks[_id].hunters[msg.sender] = true;
tasks[_id].hunterCount = tasks[_id].hunterCount + 1;
emit HunterAdded(_id, msg.sender);
}
/// @author Andy Bell [email protected]
/// @notice Remove caller as a hunter for the task
/// @param _id A 32 character hash which would point to the task
function removeHunter(bytes32 _id)
public {
require(_id[0] != 0, 'Invalid id');
require(tasks[_id].owner != address(0x0), 'Task does not exist');
require(tasks[_id].hunters[msg.sender], 'Hunter does not exist');
tasks[_id].hunters[msg.sender] = false;
tasks[_id].hunterCount = tasks[_id].hunterCount - 1;
emit HunterRemoved(_id, msg.sender);
}
/// @author Andy Bell [email protected]
/// @notice Complete a task
/// @dev Only the owner can complete a task
/// @param _id A 32 character hash which would point to the task
/// @param _winner Address of the hunter
function completeTask(bytes32 _id, address _winner)
public
whenNotPaused {
Task storage t = tasks[_id];
require(t.owner == msg.sender, 'Invalid task');
require(_winner != address(0x0), 'Invalid hunter');
require(t.hunters[_winner], 'No hunters');
require(t.tokens > 0, 'Task completed');
uint tokensToTransfer = t.tokens;
tasks[_id].tokens = 0;
if (kudos.transfer(_winner, tokensToTransfer)) {
emit TaskCompleted(_id, t.owner, _winner, tokensToTransfer);
} else {
// Rewind. I am thinking if we return false it is a revert which would wind this back anyhow.
// TODO - check this and remove line below if not needed
tasks[_id].tokens = tokensToTransfer;
}
}
/// @author Andy Bell [email protected]
/// @notice Cancel a task
/// @dev Only the owner can cancel the task
/// @param _id A 32 character hash which would point to the task
function cancelTask(bytes32 _id)
public {
require(_id[0] != 0, 'Invalid id');
require(tasks[_id].owner == msg.sender, 'Invalid task');
bool expired = tasks[_id].created + (timeoutInDays * 1 days) < block.timestamp;
require(expired || tasks[_id].hunterCount == 0, 'Unable as still valid');
// Cancel task
uint tokensToTransfer = tasks[_id].tokens;
tasks[_id].tokens = 0;
emit TaskCancelled(_id, msg.sender);
kudos.transfer(msg.sender, tokensToTransfer);
}
}
|
Andy Bell [email protected] Cancel a task Only the owner can cancel the task _id A 32 character hash which would point to the task Cancel task
|
function cancelTask(bytes32 _id)
public {
require(_id[0] != 0, 'Invalid id');
require(tasks[_id].owner == msg.sender, 'Invalid task');
bool expired = tasks[_id].created + (timeoutInDays * 1 days) < block.timestamp;
require(expired || tasks[_id].hunterCount == 0, 'Unable as still valid');
uint tokensToTransfer = tasks[_id].tokens;
tasks[_id].tokens = 0;
emit TaskCancelled(_id, msg.sender);
kudos.transfer(msg.sender, tokensToTransfer);
}
| 12,785,656 |
./partial_match/1/0xbAF9Fa296e7D27d60BBcC10A940d5d60DDE16408/sources/YearlyLottery.sol
|
find participant who has winning ticket to start: _begin is 0, _end is last index in ticketsInterval array
|
function getWinner(
uint _round,
uint _beginInterval,
uint _endInterval,
uint _winningTicket
)
internal
returns (address)
{
if (_beginInterval == _endInterval) {
return rounds[_round].tickets[_beginInterval].participant;
}
uint len = _endInterval.add(1).sub(_beginInterval);
uint mid = _beginInterval.add((len.div(2))).sub(1);
TicketsInterval memory interval = rounds[_round].tickets[mid];
if (_winningTicket < interval.firstTicket) {
return getWinner(_round, _beginInterval, mid, _winningTicket);
return getWinner(_round, mid.add(1), _endInterval, _winningTicket);
return interval.participant;
}
}
| 15,644,760 |
/**
*Submitted for verification at Etherscan.io on 2021-05-03
*/
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: @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: @openzeppelin/contracts/utils/ReentrancyGuard.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/utils/Pausable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view 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());
}
}
// File: contracts/tokens/EIP20NonStandardInterface.sol
pragma solidity 0.7.6;
/// @title EIP20NonStandardInterface
/// @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
/// See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
interface EIP20NonStandardInterface {
/// @notice Get the total number of tokens in circulation
/// @return The supply of tokens
function totalSupply() external view returns (uint256);
/// @notice Gets the balance of the specified address
/// @param owner The address from which the balance will be retrieved
/// @return balance The balance
function balanceOf(address owner) external view returns (uint256 balance);
//
// !!!!!!!!!!!!!!
// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
// !!!!!!!!!!!!!!
//
/// @notice Transfer `amount` tokens from `msg.sender` to `dst`
/// @param dst The address of the destination account
/// @param amount The number of tokens to transfer
function transfer(address dst, uint256 amount) external;
//
// !!!!!!!!!!!!!!
// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
// !!!!!!!!!!!!!!
//
/// @notice Transfer `amount` tokens from `src` to `dst`
/// @param src The address of the source account
/// @param dst The address of the destination account
/// @param amount The number of tokens to transfer
function transferFrom(
address src,
address dst,
uint256 amount
) external;
/// @notice Approve `spender` to transfer up to `amount` from `src`
/// @dev This will overwrite the approval amount for `spender`
/// and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
/// @param spender The address of the account which may transfer tokens
/// @param amount The number of tokens that are approved
/// @return success Whether or not the approval succeeded
function approve(address spender, uint256 amount)
external
returns (bool success);
/// @notice Get the current allowance from `owner` for `spender`
/// @param owner The address of the account which owns the tokens to be spent
/// @param spender The address of the account which may transfer tokens
/// @return remaining The number of tokens allowed to be spent
function allowance(address owner, address spender)
external
view
returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(
address indexed owner,
address indexed spender,
uint256 amount
);
}
// File: contracts/IDerivativeSpecification.sol
pragma solidity 0.7.6;
/// @title Derivative Specification interface
/// @notice Immutable collection of derivative attributes
/// @dev Created by the derivative's author and published to the DerivativeSpecificationRegistry
interface IDerivativeSpecification {
/// @notice Proof of a derivative specification
/// @dev Verifies that contract is a derivative specification
/// @return true if contract is a derivative specification
function isDerivativeSpecification() external pure returns (bool);
/// @notice Set of oracles that are relied upon to measure changes in the state of the world
/// between the start and the end of the Live period
/// @dev Should be resolved through OracleRegistry contract
/// @return oracle symbols
function oracleSymbols() external view returns (bytes32[] memory);
/// @notice Algorithm that, for the type of oracle used by the derivative,
/// finds the value closest to a given timestamp
/// @dev Should be resolved through OracleIteratorRegistry contract
/// @return oracle iterator symbols
function oracleIteratorSymbols() external view returns (bytes32[] memory);
/// @notice Type of collateral that users submit to mint the derivative
/// @dev Should be resolved through CollateralTokenRegistry contract
/// @return collateral token symbol
function collateralTokenSymbol() external view returns (bytes32);
/// @notice Mapping from the change in the underlying variable (as defined by the oracle)
/// and the initial collateral split to the final collateral split
/// @dev Should be resolved through CollateralSplitRegistry contract
/// @return collateral split symbol
function collateralSplitSymbol() external view returns (bytes32);
/// @notice Lifecycle parameter that define the length of the derivative's Live period.
/// @dev Set in seconds
/// @return live period value
function livePeriod() external view returns (uint256);
/// @notice Parameter that determines starting nominal value of primary asset
/// @dev Units of collateral theoretically swappable for 1 unit of primary asset
/// @return primary nominal value
function primaryNominalValue() external view returns (uint256);
/// @notice Parameter that determines starting nominal value of complement asset
/// @dev Units of collateral theoretically swappable for 1 unit of complement asset
/// @return complement nominal value
function complementNominalValue() external view returns (uint256);
/// @notice Minting fee rate due to the author of the derivative specification.
/// @dev Percentage fee multiplied by 10 ^ 12
/// @return author fee
function authorFee() external view returns (uint256);
/// @notice Symbol of the derivative
/// @dev Should be resolved through DerivativeSpecificationRegistry contract
/// @return derivative specification symbol
function symbol() external view returns (string memory);
/// @notice Return optional long name of the derivative
/// @dev Isn't used directly in the protocol
/// @return long name
function name() external view returns (string memory);
/// @notice Optional URI to the derivative specs
/// @dev Isn't used directly in the protocol
/// @return URI to the derivative specs
function baseURI() external view returns (string memory);
/// @notice Derivative spec author
/// @dev Used to set and receive author's fee
/// @return address of the author
function author() external view returns (address);
}
// File: contracts/collateralSplits/ICollateralSplit.sol
pragma solidity 0.7.6;
/// @title Collateral Split interface
/// @notice Contains mathematical functions used to calculate relative claim
/// on collateral of primary and complement assets after settlement.
/// @dev Created independently from specification and published to the CollateralSplitRegistry
interface ICollateralSplit {
/// @notice Proof of collateral split contract
/// @dev Verifies that contract is a collateral split contract
/// @return true if contract is a collateral split contract
function isCollateralSplit() external pure returns (bool);
/// @notice Symbol of the collateral split
/// @dev Should be resolved through CollateralSplitRegistry contract
/// @return collateral split specification symbol
function symbol() external pure returns (string memory);
/// @notice Calcs primary asset class' share of collateral at settlement.
/// @dev Returns ranged value between 0 and 1 multiplied by 10 ^ 12
/// @param _underlyingStarts underlying values in the start of Live period
/// @param _underlyingEndRoundHints specify for each oracle round of the end of Live period
/// @return _split primary asset class' share of collateral at settlement
/// @return _underlyingEnds underlying values in the end of Live period
function split(
address[] calldata _oracles,
address[] calldata _oracleIterators,
int256[] calldata _underlyingStarts,
uint256 _settleTime,
uint256[] calldata _underlyingEndRoundHints
) external view returns (uint256 _split, int256[] memory _underlyingEnds);
}
// File: contracts/tokens/IERC20MintedBurnable.sol
pragma solidity 0.7.6;
interface IERC20MintedBurnable is IERC20 {
function mint(address to, uint256 amount) external;
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
}
// File: contracts/tokens/ITokenBuilder.sol
pragma solidity 0.7.6;
interface ITokenBuilder {
function isTokenBuilder() external pure returns (bool);
function buildTokens(
IDerivativeSpecification derivative,
uint256 settlement,
address _collateralToken
) external returns (IERC20MintedBurnable, IERC20MintedBurnable);
}
// File: contracts/IFeeLogger.sol
pragma solidity 0.7.6;
interface IFeeLogger {
function log(
address _liquidityProvider,
address _collateral,
uint256 _protocolFee,
address _author
) external;
}
// File: contracts/IPausableVault.sol
pragma solidity 0.7.6;
interface IPausableVault {
function pause() external;
function unpause() external;
}
// File: contracts/Vault.sol
pragma solidity 0.7.6;
/// @title Derivative implementation Vault
/// @notice A smart contract that references derivative specification and enables users to mint and redeem the derivative
contract Vault is Ownable, Pausable, IPausableVault, ReentrancyGuard {
using SafeMath for uint256;
using SafeMath for uint8;
uint256 public constant FRACTION_MULTIPLIER = 10**12;
enum State { Created, Live, Settled }
event StateChanged(State oldState, State newState);
event LiveStateSet(address primaryToken, address complementToken);
event SettledStateSet(
int256[] underlyingStarts,
int256[] underlyingEnds,
uint256 primaryConversion,
uint256 complementConversion
);
event Minted(address indexed recipient, uint256 minted, uint256 collateral, uint256 fee);
event Refunded(address indexed recipient, uint256 tokenAmount, uint256 collateral);
event Redeemed(
address indexed recipient,
address tokenAddress,
uint256 tokenAmount,
uint256 conversion,
uint256 collateral
);
/// @notice start of live period
uint256 public liveTime;
/// @notice end of live period
uint256 public settleTime;
/// @notice redeem function can only be called after the end of the Live period + delay
uint256 public settlementDelay;
/// @notice underlying value at the start of live period
int256[] public underlyingStarts;
/// @notice underlying value at the end of live period
int256[] public underlyingEnds;
/// @notice primary token conversion rate multiplied by 10 ^ 12
uint256 public primaryConversion;
/// @notice complement token conversion rate multiplied by 10 ^ 12
uint256 public complementConversion;
/// @notice protocol fee multiplied by 10 ^ 12
uint256 public protocolFee;
/// @notice limit on author fee multiplied by 10 ^ 12
uint256 public authorFeeLimit;
// @notice protocol's fee receiving wallet
address public feeWallet;
// @notice current state of the vault
State public state;
// @notice derivative specification address
IDerivativeSpecification public derivativeSpecification;
// @notice collateral token address
IERC20 public collateralToken;
// @notice oracle address
address[] public oracles;
address[] public oracleIterators;
// @notice collateral split address
ICollateralSplit public collateralSplit;
// @notice derivative's token builder strategy address
ITokenBuilder public tokenBuilder;
IFeeLogger public feeLogger;
// @notice primary token address
IERC20MintedBurnable public primaryToken;
// @notice complement token address
IERC20MintedBurnable public complementToken;
constructor(
uint256 _liveTime,
uint256 _protocolFee,
address _feeWallet,
address _derivativeSpecification,
address _collateralToken,
address[] memory _oracles,
address[] memory _oracleIterators,
address _collateralSplit,
address _tokenBuilder,
address _feeLogger,
uint256 _authorFeeLimit,
uint256 _settlementDelay
) public {
require(_liveTime > 0, "Live zero");
require(_liveTime <= block.timestamp, "Live in future");
liveTime = _liveTime;
protocolFee = _protocolFee;
require(_feeWallet != address(0), "Fee wallet");
feeWallet = _feeWallet;
require(_derivativeSpecification != address(0), "Derivative");
derivativeSpecification = IDerivativeSpecification(
_derivativeSpecification
);
require(_collateralToken != address(0), "Collateral token");
collateralToken = IERC20(_collateralToken);
require(_oracles.length > 0, "Oracles");
require(_oracles[0] != address(0), "First oracle is absent");
oracles = _oracles;
require(_oracleIterators.length > 0, "OracleIterators");
require(
_oracleIterators[0] != address(0),
"First oracle iterator is absent"
);
oracleIterators = _oracleIterators;
require(_collateralSplit != address(0), "Collateral split");
collateralSplit = ICollateralSplit(_collateralSplit);
require(_tokenBuilder != address(0), "Token builder");
tokenBuilder = ITokenBuilder(_tokenBuilder);
require(_feeLogger != address(0), "Fee logger");
feeLogger = IFeeLogger(_feeLogger);
authorFeeLimit = _authorFeeLimit;
settleTime = liveTime + derivativeSpecification.livePeriod();
require(block.timestamp < settleTime, "Settled time");
settlementDelay = _settlementDelay;
}
function pause() external override onlyOwner() {
_pause();
}
function unpause() external override onlyOwner() {
_unpause();
}
/// @notice Initialize vault by creating derivative token and switching to Live state
/// @dev Extracted from constructor to reduce contract gas creation amount
function initialize(int256[] calldata _underlyingStarts) external {
require(state == State.Created, "Incorrect state.");
underlyingStarts = _underlyingStarts;
changeState(State.Live);
(primaryToken, complementToken) = tokenBuilder.buildTokens(
derivativeSpecification,
settleTime,
address(collateralToken)
);
emit LiveStateSet(address(primaryToken), address(complementToken));
}
function changeState(State _newState) internal {
state = _newState;
emit StateChanged(state, _newState);
}
/// @notice Switch to Settled state if appropriate time threshold is passed and
/// set underlyingStarts value and set underlyingEnds value,
/// calculate primaryConversion and complementConversion params
/// @dev Reverts if underlyingEnds are not available
/// Vault cannot settle when it paused
function settle(uint256[] calldata _underlyingEndRoundHints)
public
whenNotPaused()
{
require(state == State.Live, "Incorrect state");
require(
block.timestamp >= (settleTime + settlementDelay),
"Incorrect time"
);
changeState(State.Settled);
uint256 split;
(split, underlyingEnds) = collateralSplit.split(
oracles,
oracleIterators,
underlyingStarts,
settleTime,
_underlyingEndRoundHints
);
split = range(split);
uint256 collectedCollateral = collateralToken.balanceOf(address(this));
uint256 mintedPrimaryTokenAmount = primaryToken.totalSupply();
if (mintedPrimaryTokenAmount > 0) {
uint256 primaryCollateralPortion = collectedCollateral.mul(split);
primaryConversion = primaryCollateralPortion.div(
mintedPrimaryTokenAmount
);
complementConversion = collectedCollateral
.mul(FRACTION_MULTIPLIER)
.sub(primaryCollateralPortion)
.div(mintedPrimaryTokenAmount);
}
emit SettledStateSet(
underlyingStarts,
underlyingEnds,
primaryConversion,
complementConversion
);
}
function range(uint256 _split) public pure returns (uint256) {
if (_split > FRACTION_MULTIPLIER) {
return FRACTION_MULTIPLIER;
}
return _split;
}
function performMint(address _recipient, uint256 _collateralAmount)
internal
{
require(state == State.Live, "Live is over");
require(_collateralAmount > 0, "Zero amount");
_collateralAmount = doTransferIn(msg.sender, _collateralAmount);
uint256 feeAmount = withdrawFee(_collateralAmount);
uint256 netAmount = _collateralAmount.sub(feeAmount);
uint256 tokenAmount = denominate(netAmount);
primaryToken.mint(_recipient, tokenAmount);
complementToken.mint(_recipient, tokenAmount);
emit Minted(_recipient, tokenAmount, _collateralAmount, feeAmount);
}
function mintTo(address _recipient, uint256 _collateralAmount)
external
nonReentrant()
{
performMint(_recipient, _collateralAmount);
}
/// @notice Mints primary and complement derivative tokens
/// @dev Checks and switches to the right state and does nothing if vault is not in Live state
function mint(uint256 _collateralAmount) external nonReentrant() {
performMint(msg.sender, _collateralAmount);
}
function performRefund(address _recipient, uint256 _tokenAmount) internal {
require(_tokenAmount > 0, "Zero amount");
require(
_tokenAmount <= primaryToken.balanceOf(msg.sender),
"Insufficient primary amount"
);
require(
_tokenAmount <= complementToken.balanceOf(msg.sender),
"Insufficient complement amount"
);
primaryToken.burnFrom(msg.sender, _tokenAmount);
complementToken.burnFrom(msg.sender, _tokenAmount);
uint256 unDenominated = unDenominate(_tokenAmount);
emit Refunded(_recipient, _tokenAmount, unDenominated);
doTransferOut(_recipient, unDenominated);
}
/// @notice Refund equal amounts of derivative tokens for collateral at any time
function refund(uint256 _tokenAmount) external nonReentrant() {
performRefund(msg.sender, _tokenAmount);
}
function refundTo(address _recipient, uint256 _tokenAmount)
external
nonReentrant()
{
performRefund(_recipient, _tokenAmount);
}
function performRedeem(
address _recipient,
uint256 _primaryTokenAmount,
uint256 _complementTokenAmount,
uint256[] calldata _underlyingEndRoundHints
) internal {
require(
_primaryTokenAmount > 0 || _complementTokenAmount > 0,
"Both tokens zero amount"
);
require(
_primaryTokenAmount <= primaryToken.balanceOf(msg.sender),
"Insufficient primary amount"
);
require(
_complementTokenAmount <= complementToken.balanceOf(msg.sender),
"Insufficient complement amount"
);
if (
block.timestamp >= (settleTime + settlementDelay) &&
state == State.Live
) {
settle(_underlyingEndRoundHints);
}
if (state == State.Settled) {
uint collateral = redeemAsymmetric(
_recipient,
primaryToken,
_primaryTokenAmount,
primaryConversion
);
collateral = redeemAsymmetric(
_recipient,
complementToken,
_complementTokenAmount,
complementConversion
).add(collateral);
if (collateral > 0) {
doTransferOut(_recipient, collateral);
}
}
}
function redeemTo(
address _recipient,
uint256 _primaryTokenAmount,
uint256 _complementTokenAmount,
uint256[] calldata _underlyingEndRoundHints
) external nonReentrant() {
performRedeem(
_recipient,
_primaryTokenAmount,
_complementTokenAmount,
_underlyingEndRoundHints
);
}
/// @notice Redeems unequal amounts previously calculated conversions if the vault is in Settled state
function redeem(
uint256 _primaryTokenAmount,
uint256 _complementTokenAmount,
uint256[] calldata _underlyingEndRoundHints
) external nonReentrant() {
performRedeem(
msg.sender,
_primaryTokenAmount,
_complementTokenAmount,
_underlyingEndRoundHints
);
}
function redeemAsymmetric(
address _recipient,
IERC20MintedBurnable _derivativeToken,
uint256 _amount,
uint256 _conversion
) internal returns(uint256 collateral){
if (_amount == 0) {
return 0;
}
_derivativeToken.burnFrom(msg.sender, _amount);
collateral = _amount.mul(_conversion) / FRACTION_MULTIPLIER;
emit Redeemed(_recipient, address(_derivativeToken),_amount, _conversion, collateral);
}
function denominate(uint256 _collateralAmount)
internal
view
returns (uint256)
{
return
_collateralAmount.div(
derivativeSpecification.primaryNominalValue() +
derivativeSpecification.complementNominalValue()
);
}
function unDenominate(uint256 _tokenAmount)
internal
view
returns (uint256)
{
return
_tokenAmount.mul(
derivativeSpecification.primaryNominalValue() +
derivativeSpecification.complementNominalValue()
);
}
function withdrawFee(uint256 _amount) internal returns (uint256) {
uint256 protocolFeeAmount =
calcAndTransferFee(_amount, payable(feeWallet), protocolFee);
feeLogger.log(
msg.sender,
address(collateralToken),
protocolFeeAmount,
derivativeSpecification.author()
);
uint256 authorFee = derivativeSpecification.authorFee();
if (authorFee > authorFeeLimit) {
authorFee = authorFeeLimit;
}
uint256 authorFeeAmount =
calcAndTransferFee(
_amount,
payable(derivativeSpecification.author()),
authorFee
);
return protocolFeeAmount.add(authorFeeAmount);
}
function calcAndTransferFee(
uint256 _amount,
address payable _beneficiary,
uint256 _fee
) internal returns (uint256 _feeAmount) {
_feeAmount = _amount.mul(_fee).div(FRACTION_MULTIPLIER);
if (_feeAmount > 0) {
doTransferOut(_beneficiary, _feeAmount);
}
}
/// @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
/// This will revert due to insufficient balance or insufficient allowance.
/// This function returns the actual amount received,
/// which may be less than `amount` if there is a fee attached to the transfer.
/// @notice This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
/// See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
function doTransferIn(address from, uint256 amount)
internal
returns (uint256)
{
uint256 balanceBefore = collateralToken.balanceOf(address(this));
EIP20NonStandardInterface(address(collateralToken)).transferFrom(
from,
address(this),
amount
);
bool success;
assembly {
switch returndatasize()
case 0 {
// This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 {
// This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default {
// This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_IN_FAILED");
// Calculate the amount that was *actually* transferred
uint256 balanceAfter = collateralToken.balanceOf(address(this));
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
/// @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
/// error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
/// insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
/// it is >= amount, this should not revert in normal conditions.
/// @notice This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
/// See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
function doTransferOut(address to, uint256 amount) internal {
EIP20NonStandardInterface(address(collateralToken)).transfer(
to,
amount
);
bool success;
assembly {
switch returndatasize()
case 0 {
// This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 {
// This is a complaint ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default {
// This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_OUT_FAILED");
}
}
// File: contracts/IVaultBuilder.sol
pragma solidity 0.7.6;
interface IVaultBuilder {
function buildVault(
uint256 _liveTime,
uint256 _protocolFee,
address _feeWallet,
address _derivativeSpecification,
address _collateralToken,
address[] calldata _oracles,
address[] calldata _oracleIterators,
address _collateralSplit,
address _tokenBuilder,
address _feeLogger,
uint256 _authorFeeLimit,
uint256 _settlementDelay
) external returns (address);
}
// File: contracts/VaultBuilder.sol
// "SPDX-License-Identifier: GPL-3.0-or-later"
pragma solidity 0.7.6;
contract VaultBuilder is IVaultBuilder {
function buildVault(
uint256 _liveTime,
uint256 _protocolFee,
address _feeWallet,
address _derivativeSpecification,
address _collateralToken,
address[] memory _oracles,
address[] memory _oracleIterators,
address _collateralSplit,
address _tokenBuilder,
address _feeLogger,
uint256 _authorFeeLimit,
uint256 _settlementDelay
) public override returns (address) {
Vault vault =
new Vault(
_liveTime,
_protocolFee,
_feeWallet,
_derivativeSpecification,
_collateralToken,
_oracles,
_oracleIterators,
_collateralSplit,
_tokenBuilder,
_feeLogger,
_authorFeeLimit,
_settlementDelay
);
vault.transferOwnership(msg.sender);
return address(vault);
}
}
|
Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. This will revert due to insufficient balance or insufficient allowance. This function returns the actual amount received, which may be less than `amount` if there is a fee attached to the transfer. This wrapper safely handles non-standard ERC-20 tokens that do not return a value. See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca This is a non-standard ERC-20 This is a compliant ERC-20 This is an excessively non-compliant ERC-20, revert.
|
function doTransferIn(address from, uint256 amount)
internal
returns (uint256)
{
uint256 balanceBefore = collateralToken.balanceOf(address(this));
EIP20NonStandardInterface(address(collateralToken)).transferFrom(
from,
address(this),
amount
);
bool success;
assembly {
switch returndatasize()
case 0 {
}
case 32 {
returndatacopy(0, 0, 32)
}
default {
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_IN_FAILED");
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
}
| 2,400,512 |
./full_match/3/0x38C8705229b367C0292FaE9AC40251A37ceC7096/sources/browser/Token.sol
|
emit Transfer(,owner,_minteAmount);
|
function mintToken(address _target,uint256 _minteAmount) public onlyOwner {
balances[_target]+=_minteAmount;
_totalSupply +=_minteAmount;
emit Transfer(owner,_target,_minteAmount);
}
| 8,085,826 |
/**
*Submitted for verification at Etherscan.io on 2020-09-18
*/
/**
*Submitted for verification at Etherscan.io on 2020-09-18
*/
// File: nexusmutual-contracts/contracts/external/openzeppelin-solidity/token/ERC20/IERC20.sol
pragma solidity 0.5.7;
/**
* @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: nexusmutual-contracts/contracts/external/openzeppelin-solidity/math/SafeMath.sol
pragma solidity 0.5.7;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
//require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
//require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: nexusmutual-contracts/contracts/NXMToken.sol
/* Copyright (C) 2017 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity 0.5.7;
contract NXMToken is IERC20 {
using SafeMath for uint256;
event WhiteListed(address indexed member);
event BlackListed(address indexed member);
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
mapping (address => bool) public whiteListed;
mapping(address => uint) public isLockedForMV;
uint256 private _totalSupply;
string public name = "NXM";
string public symbol = "NXM";
uint8 public decimals = 18;
address public operator;
modifier canTransfer(address _to) {
require(whiteListed[_to]);
_;
}
modifier onlyOperator() {
if (operator != address(0))
require(msg.sender == operator);
_;
}
constructor(address _founderAddress, uint _initialSupply) public {
_mint(_founderAddress, _initialSupply);
}
/**
* @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 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 Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
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 Adds a user to whitelist
* @param _member address to add to whitelist
*/
function addToWhiteList(address _member) public onlyOperator returns (bool) {
whiteListed[_member] = true;
emit WhiteListed(_member);
return true;
}
/**
* @dev removes a user from whitelist
* @param _member address to remove from whitelist
*/
function removeFromWhiteList(address _member) public onlyOperator returns (bool) {
whiteListed[_member] = false;
emit BlackListed(_member);
return true;
}
/**
* @dev change operator address
* @param _newOperator address of new operator
*/
function changeOperator(address _newOperator) public onlyOperator returns (bool) {
operator = _newOperator;
return true;
}
/**
* @dev burns an amount of the tokens of the message sender
* account.
* @param amount The amount that will be burnt.
*/
function burn(uint256 amount) public returns (bool) {
_burn(msg.sender, amount);
return true;
}
/**
* @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 returns (bool) {
_burnFrom(from, value);
return true;
}
/**
* @dev function that mints an amount of the token and assigns it to
* an account.
* @param account The account that will receive the created tokens.
* @param amount The amount that will be created.
*/
function mint(address account, uint256 amount) public onlyOperator {
_mint(account, amount);
}
/**
* @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 canTransfer(to) returns (bool) {
require(isLockedForMV[msg.sender] < now); // if not voted under governance
require(value <= _balances[msg.sender]);
_transfer(to, value);
return true;
}
/**
* @dev Transfer tokens to the operator from the specified address
* @param from The address to transfer from.
* @param value The amount to be transferred.
*/
function operatorTransfer(address from, uint256 value) public onlyOperator returns (bool) {
require(value <= _balances[from]);
_transferFrom(from, operator, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
canTransfer(to)
returns (bool)
{
require(isLockedForMV[from] < now); // if not voted under governance
require(value <= _balances[from]);
require(value <= _allowed[from][msg.sender]);
_transferFrom(from, to, value);
return true;
}
/**
* @dev Lock the user's tokens
* @param _of user's address.
*/
function lockForMemberVote(address _of, uint _days) public onlyOperator {
if (_days.add(now) > isLockedForMV[_of])
isLockedForMV[_of] = _days.add(now);
}
/**
* @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) internal {
_balances[msg.sender] = _balances[msg.sender].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(msg.sender, to, value);
}
/**
* @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
)
internal
{
_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);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param amount The amount that will be created.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burn(address account, uint256 amount) internal {
require(amount <= _balances[account]);
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @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.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][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[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
}
// File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IProposalCategory.sol
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity 0.5.7;
contract IProposalCategory {
event Category(
uint indexed categoryId,
string categoryName,
string actionHash
);
/// @dev Adds new category
/// @param _name Category name
/// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
/// @param _allowedToCreateProposal Member roles allowed to create the proposal
/// @param _majorityVotePerc Majority Vote threshold for Each voting layer
/// @param _quorumPerc minimum threshold percentage required in voting to calculate result
/// @param _closingTime Vote closing time for Each voting layer
/// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
/// @param _contractAddress address of contract to call after proposal is accepted
/// @param _contractName name of contract to be called after proposal is accepted
/// @param _incentives rewards to distributed after proposal is accepted
function addCategory(
string calldata _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] calldata _allowedToCreateProposal,
uint _closingTime,
string calldata _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] calldata _incentives
)
external;
/// @dev gets category details
function category(uint _categoryId)
external
view
returns(
uint categoryId,
uint memberRoleToVote,
uint majorityVotePerc,
uint quorumPerc,
uint[] memory allowedToCreateProposal,
uint closingTime,
uint minStake
);
///@dev gets category action details
function categoryAction(uint _categoryId)
external
view
returns(
uint categoryId,
address contractAddress,
bytes2 contractName,
uint defaultIncentive
);
/// @dev Gets Total number of categories added till now
function totalCategories() external view returns(uint numberOfCategories);
/// @dev Updates category details
/// @param _categoryId Category id that needs to be updated
/// @param _name Category name
/// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
/// @param _allowedToCreateProposal Member roles allowed to create the proposal
/// @param _majorityVotePerc Majority Vote threshold for Each voting layer
/// @param _quorumPerc minimum threshold percentage required in voting to calculate result
/// @param _closingTime Vote closing time for Each voting layer
/// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
/// @param _contractAddress address of contract to call after proposal is accepted
/// @param _contractName name of contract to be called after proposal is accepted
/// @param _incentives rewards to distributed after proposal is accepted
function updateCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
)
public;
}
// File: nexusmutual-contracts/contracts/external/govblocks-protocol/Governed.sol
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity 0.5.7;
contract IMaster {
function getLatestAddress(bytes2 _module) public view returns(address);
}
contract Governed {
address public masterAddress; // Name of the dApp, needs to be set by contracts inheriting this contract
/// @dev modifier that allows only the authorized addresses to execute the function
modifier onlyAuthorizedToGovern() {
IMaster ms = IMaster(masterAddress);
require(ms.getLatestAddress("GV") == msg.sender, "Not authorized");
_;
}
/// @dev checks if an address is authorized to govern
function isAuthorizedToGovern(address _toCheck) public view returns(bool) {
IMaster ms = IMaster(masterAddress);
return (ms.getLatestAddress("GV") == _toCheck);
}
}
// File: nexusmutual-contracts/contracts/INXMMaster.sol
/* Copyright (C) 2017 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity 0.5.7;
contract INXMMaster {
address public tokenAddress;
address public owner;
uint public pauseTime;
function delegateCallBack(bytes32 myid) external;
function masterInitialized() public view returns(bool);
function isInternal(address _add) public view returns(bool);
function isPause() public view returns(bool check);
function isOwner(address _add) public view returns(bool);
function isMember(address _add) public view returns(bool);
function checkIsAuthToGoverned(address _add) public view returns(bool);
function updatePauseTime(uint _time) public;
function dAppLocker() public view returns(address _add);
function dAppToken() public view returns(address _add);
function getLatestAddress(bytes2 _contractName) public view returns(address payable contractAddress);
}
// File: nexusmutual-contracts/contracts/Iupgradable.sol
pragma solidity 0.5.7;
contract Iupgradable {
INXMMaster public ms;
address public nxMasterAddress;
modifier onlyInternal {
require(ms.isInternal(msg.sender));
_;
}
modifier isMemberAndcheckPause {
require(ms.isPause() == false && ms.isMember(msg.sender) == true);
_;
}
modifier onlyOwner {
require(ms.isOwner(msg.sender));
_;
}
modifier checkPause {
require(ms.isPause() == false);
_;
}
modifier isMember {
require(ms.isMember(msg.sender), "Not member");
_;
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public;
/**
* @dev change master address
* @param _masterAddress is the new address
*/
function changeMasterAddress(address _masterAddress) public {
if (address(ms) != address(0)) {
require(address(ms) == msg.sender, "Not master");
}
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
}
// File: nexusmutual-contracts/contracts/interfaces/IPooledStaking.sol
pragma solidity ^0.5.7;
interface IPooledStaking {
function accumulateReward(address contractAddress, uint amount) external;
function pushBurn(address contractAddress, uint amount) external;
function hasPendingActions() external view returns (bool);
function contractStake(address contractAddress) external view returns (uint);
function stakerReward(address staker) external view returns (uint);
function stakerDeposit(address staker) external view returns (uint);
function stakerContractStake(address staker, address contractAddress) external view returns (uint);
function withdraw(uint amount) external;
function stakerMaxWithdrawable(address stakerAddress) external view returns (uint);
function withdrawReward(address stakerAddress) external;
}
// File: nexusmutual-contracts/contracts/TokenFunctions.sol
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity 0.5.7;
contract TokenFunctions is Iupgradable {
using SafeMath for uint;
MCR internal m1;
MemberRoles internal mr;
NXMToken public tk;
TokenController internal tc;
TokenData internal td;
QuotationData internal qd;
ClaimsReward internal cr;
Governance internal gv;
PoolData internal pd;
IPooledStaking pooledStaking;
event BurnCATokens(uint claimId, address addr, uint amount);
/**
* @dev Rewards stakers on purchase of cover on smart contract.
* @param _contractAddress smart contract address.
* @param _coverPriceNXM cover price in NXM.
*/
function pushStakerRewards(address _contractAddress, uint _coverPriceNXM) external onlyInternal {
uint rewardValue = _coverPriceNXM.mul(td.stakerCommissionPer()).div(100);
pooledStaking.accumulateReward(_contractAddress, rewardValue);
}
/**
* @dev Deprecated in favor of burnStakedTokens
*/
function burnStakerLockedToken(uint, bytes4, uint) external {
// noop
}
/**
* @dev Burns tokens staked on smart contract covered by coverId. Called when a payout is succesfully executed.
* @param coverId cover id
* @param coverCurrency cover currency
* @param sumAssured amount of $curr to burn
*/
function burnStakedTokens(uint coverId, bytes4 coverCurrency, uint sumAssured) external onlyInternal {
(, address scAddress) = qd.getscAddressOfCover(coverId);
uint tokenPrice = m1.calculateTokenPrice(coverCurrency);
uint burnNXMAmount = sumAssured.mul(1e18).div(tokenPrice);
pooledStaking.pushBurn(scAddress, burnNXMAmount);
}
/**
* @dev Gets the total staked NXM tokens against
* Smart contract by all stakers
* @param _stakedContractAddress smart contract address.
* @return amount total staked NXM tokens.
*/
function deprecated_getTotalStakedTokensOnSmartContract(
address _stakedContractAddress
)
external
view
returns(uint)
{
uint stakedAmount = 0;
address stakerAddress;
uint staketLen = td.getStakedContractStakersLength(_stakedContractAddress);
for (uint i = 0; i < staketLen; i++) {
stakerAddress = td.getStakedContractStakerByIndex(_stakedContractAddress, i);
uint stakerIndex = td.getStakedContractStakerIndex(
_stakedContractAddress, i);
uint currentlyStaked;
(, currentlyStaked) = _deprecated_unlockableBeforeBurningAndCanBurn(stakerAddress,
_stakedContractAddress, stakerIndex);
stakedAmount = stakedAmount.add(currentlyStaked);
}
return stakedAmount;
}
/**
* @dev Returns amount of NXM Tokens locked as Cover Note for given coverId.
* @param _of address of the coverHolder.
* @param _coverId coverId of the cover.
*/
function getUserLockedCNTokens(address _of, uint _coverId) external view returns(uint) {
return _getUserLockedCNTokens(_of, _coverId);
}
/**
* @dev to get the all the cover locked tokens of a user
* @param _of is the user address in concern
* @return amount locked
*/
function getUserAllLockedCNTokens(address _of) external view returns(uint amount) {
for (uint i = 0; i < qd.getUserCoverLength(_of); i++) {
amount = amount.add(_getUserLockedCNTokens(_of, qd.getAllCoversOfUser(_of)[i]));
}
}
/**
* @dev Returns amount of NXM Tokens locked as Cover Note against given coverId.
* @param _coverId coverId of the cover.
*/
function getLockedCNAgainstCover(uint _coverId) external view returns(uint) {
return _getLockedCNAgainstCover(_coverId);
}
/**
* @dev Returns total amount of staked NXM Tokens on all smart contracts.
* @param _stakerAddress address of the Staker.
*/
function deprecated_getStakerAllLockedTokens(address _stakerAddress) external view returns (uint amount) {
uint stakedAmount = 0;
address scAddress;
uint scIndex;
for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) {
scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i);
scIndex = td.getStakerStakedContractIndex(_stakerAddress, i);
uint currentlyStaked;
(, currentlyStaked) = _deprecated_unlockableBeforeBurningAndCanBurn(_stakerAddress, scAddress, i);
stakedAmount = stakedAmount.add(currentlyStaked);
}
amount = stakedAmount;
}
/**
* @dev Returns total unlockable amount of staked NXM Tokens on all smart contract .
* @param _stakerAddress address of the Staker.
*/
function deprecated_getStakerAllUnlockableStakedTokens(
address _stakerAddress
)
external
view
returns (uint amount)
{
uint unlockableAmount = 0;
address scAddress;
uint scIndex;
for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) {
scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i);
scIndex = td.getStakerStakedContractIndex(_stakerAddress, i);
unlockableAmount = unlockableAmount.add(
_deprecated_getStakerUnlockableTokensOnSmartContract(_stakerAddress, scAddress,
scIndex));
}
amount = unlockableAmount;
}
/**
* @dev Change Dependent Contract Address
*/
function changeDependentContractAddress() public {
tk = NXMToken(ms.tokenAddress());
td = TokenData(ms.getLatestAddress("TD"));
tc = TokenController(ms.getLatestAddress("TC"));
cr = ClaimsReward(ms.getLatestAddress("CR"));
qd = QuotationData(ms.getLatestAddress("QD"));
m1 = MCR(ms.getLatestAddress("MC"));
gv = Governance(ms.getLatestAddress("GV"));
mr = MemberRoles(ms.getLatestAddress("MR"));
pd = PoolData(ms.getLatestAddress("PD"));
pooledStaking = IPooledStaking(ms.getLatestAddress("PS"));
}
/**
* @dev Gets the Token price in a given currency
* @param curr Currency name.
* @return price Token Price.
*/
function getTokenPrice(bytes4 curr) public view returns(uint price) {
price = m1.calculateTokenPrice(curr);
}
/**
* @dev Set the flag to check if cover note is deposited against the cover id
* @param coverId Cover Id.
*/
function depositCN(uint coverId) public onlyInternal returns (bool success) {
require(_getLockedCNAgainstCover(coverId) > 0, "No cover note available");
td.setDepositCN(coverId, true);
success = true;
}
/**
* @param _of address of Member
* @param _coverId Cover Id
* @param _lockTime Pending Time + Cover Period 7*1 days
*/
function extendCNEPOff(address _of, uint _coverId, uint _lockTime) public onlyInternal {
uint timeStamp = now.add(_lockTime);
uint coverValidUntil = qd.getValidityOfCover(_coverId);
if (timeStamp >= coverValidUntil) {
bytes32 reason = keccak256(abi.encodePacked("CN", _of, _coverId));
tc.extendLockOf(_of, reason, timeStamp);
}
}
/**
* @dev to burn the deposited cover tokens
* @param coverId is id of cover whose tokens have to be burned
* @return the status of the successful burning
*/
function burnDepositCN(uint coverId) public onlyInternal returns (bool success) {
address _of = qd.getCoverMemberAddress(coverId);
uint amount;
(amount, ) = td.depositedCN(coverId);
amount = (amount.mul(50)).div(100);
bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId));
tc.burnLockedTokens(_of, reason, amount);
success = true;
}
/**
* @dev Unlocks covernote locked against a given cover
* @param coverId id of cover
*/
function unlockCN(uint coverId) public onlyInternal {
(, bool isDeposited) = td.depositedCN(coverId);
require(!isDeposited,"Cover note is deposited and can not be released");
uint lockedCN = _getLockedCNAgainstCover(coverId);
if (lockedCN != 0) {
address coverHolder = qd.getCoverMemberAddress(coverId);
bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, coverId));
tc.releaseLockedTokens(coverHolder, reason, lockedCN);
}
}
/**
* @dev Burns tokens used for fraudulent voting against a claim
* @param claimid Claim Id.
* @param _value number of tokens to be burned
* @param _of Claim Assessor's address.
*/
function burnCAToken(uint claimid, uint _value, address _of) public {
require(ms.checkIsAuthToGoverned(msg.sender));
tc.burnLockedTokens(_of, "CLA", _value);
emit BurnCATokens(claimid, _of, _value);
}
/**
* @dev to lock cover note tokens
* @param coverNoteAmount is number of tokens to be locked
* @param coverPeriod is cover period in concern
* @param coverId is the cover id of cover in concern
* @param _of address whose tokens are to be locked
*/
function lockCN(
uint coverNoteAmount,
uint coverPeriod,
uint coverId,
address _of
)
public
onlyInternal
{
uint validity = (coverPeriod * 1 days).add(td.lockTokenTimeAfterCoverExp());
bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId));
td.setDepositCNAmount(coverId, coverNoteAmount);
tc.lockOf(_of, reason, coverNoteAmount, validity);
}
/**
* @dev to check if a member is locked for member vote
* @param _of is the member address in concern
* @return the boolean status
*/
function isLockedForMemberVote(address _of) public view returns(bool) {
return now < tk.isLockedForMV(_of);
}
/**
* @dev Internal function to gets amount of locked NXM tokens,
* staked against smartcontract by index
* @param _stakerAddress address of user
* @param _stakedContractAddress staked contract address
* @param _stakedContractIndex index of staking
*/
function deprecated_getStakerLockedTokensOnSmartContract (
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns
(uint amount)
{
amount = _deprecated_getStakerLockedTokensOnSmartContract(_stakerAddress,
_stakedContractAddress, _stakedContractIndex);
}
/**
* @dev Function to gets unlockable amount of locked NXM
* tokens, staked against smartcontract by index
* @param stakerAddress address of staker
* @param stakedContractAddress staked contract address
* @param stakerIndex index of staking
*/
function deprecated_getStakerUnlockableTokensOnSmartContract (
address stakerAddress,
address stakedContractAddress,
uint stakerIndex
)
public
view
returns (uint)
{
return _deprecated_getStakerUnlockableTokensOnSmartContract(stakerAddress, stakedContractAddress,
td.getStakerStakedContractIndex(stakerAddress, stakerIndex));
}
/**
* @dev releases unlockable staked tokens to staker
*/
function deprecated_unlockStakerUnlockableTokens(address _stakerAddress) public checkPause {
uint unlockableAmount;
address scAddress;
bytes32 reason;
uint scIndex;
for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) {
scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i);
scIndex = td.getStakerStakedContractIndex(_stakerAddress, i);
unlockableAmount = _deprecated_getStakerUnlockableTokensOnSmartContract(
_stakerAddress, scAddress,
scIndex);
td.setUnlockableBeforeLastBurnTokens(_stakerAddress, i, 0);
td.pushUnlockedStakedTokens(_stakerAddress, i, unlockableAmount);
reason = keccak256(abi.encodePacked("UW", _stakerAddress, scAddress, scIndex));
tc.releaseLockedTokens(_stakerAddress, reason, unlockableAmount);
}
}
/**
* @dev to get tokens of staker locked before burning that are allowed to burn
* @param stakerAdd is the address of the staker
* @param stakedAdd is the address of staked contract in concern
* @param stakerIndex is the staker index in concern
* @return amount of unlockable tokens
* @return amount of tokens that can burn
*/
function _deprecated_unlockableBeforeBurningAndCanBurn(
address stakerAdd,
address stakedAdd,
uint stakerIndex
)
public
view
returns
(uint amount, uint canBurn) {
uint dateAdd;
uint initialStake;
uint totalBurnt;
uint ub;
(, , dateAdd, initialStake, , totalBurnt, ub) = td.stakerStakedContracts(stakerAdd, stakerIndex);
canBurn = _deprecated_calculateStakedTokens(initialStake, now.sub(dateAdd).div(1 days), td.scValidDays());
// Can't use SafeMaths for int.
int v = int(initialStake - (canBurn) - (totalBurnt) - (
td.getStakerUnlockedStakedTokens(stakerAdd, stakerIndex)) - (ub));
uint currentLockedTokens = _deprecated_getStakerLockedTokensOnSmartContract(
stakerAdd, stakedAdd, td.getStakerStakedContractIndex(stakerAdd, stakerIndex));
if (v < 0) {
v = 0;
}
amount = uint(v);
if (canBurn > currentLockedTokens.sub(amount).sub(ub)) {
canBurn = currentLockedTokens.sub(amount).sub(ub);
}
}
/**
* @dev to get tokens of staker that are unlockable
* @param _stakerAddress is the address of the staker
* @param _stakedContractAddress is the address of staked contract in concern
* @param _stakedContractIndex is the staked contract index in concern
* @return amount of unlockable tokens
*/
function _deprecated_getStakerUnlockableTokensOnSmartContract (
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns
(uint amount)
{
uint initialStake;
uint stakerIndex = td.getStakedContractStakerIndex(
_stakedContractAddress, _stakedContractIndex);
uint burnt;
(, , , initialStake, , burnt,) = td.stakerStakedContracts(_stakerAddress, stakerIndex);
uint alreadyUnlocked = td.getStakerUnlockedStakedTokens(_stakerAddress, stakerIndex);
uint currentStakedTokens;
(, currentStakedTokens) = _deprecated_unlockableBeforeBurningAndCanBurn(_stakerAddress,
_stakedContractAddress, stakerIndex);
amount = initialStake.sub(currentStakedTokens).sub(alreadyUnlocked).sub(burnt);
}
/**
* @dev Internal function to get the amount of locked NXM tokens,
* staked against smartcontract by index
* @param _stakerAddress address of user
* @param _stakedContractAddress staked contract address
* @param _stakedContractIndex index of staking
*/
function _deprecated_getStakerLockedTokensOnSmartContract (
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex
)
internal
view
returns
(uint amount)
{
bytes32 reason = keccak256(abi.encodePacked("UW", _stakerAddress,
_stakedContractAddress, _stakedContractIndex));
amount = tc.tokensLocked(_stakerAddress, reason);
}
/**
* @dev Returns amount of NXM Tokens locked as Cover Note for given coverId.
* @param _coverId coverId of the cover.
*/
function _getLockedCNAgainstCover(uint _coverId) internal view returns(uint) {
address coverHolder = qd.getCoverMemberAddress(_coverId);
bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, _coverId));
return tc.tokensLockedAtTime(coverHolder, reason, now);
}
/**
* @dev Returns amount of NXM Tokens locked as Cover Note for given coverId.
* @param _of address of the coverHolder.
* @param _coverId coverId of the cover.
*/
function _getUserLockedCNTokens(address _of, uint _coverId) internal view returns(uint) {
bytes32 reason = keccak256(abi.encodePacked("CN", _of, _coverId));
return tc.tokensLockedAtTime(_of, reason, now);
}
/**
* @dev Internal function to gets remaining amount of staked NXM tokens,
* against smartcontract by index
* @param _stakeAmount address of user
* @param _stakeDays staked contract address
* @param _validDays index of staking
*/
function _deprecated_calculateStakedTokens(
uint _stakeAmount,
uint _stakeDays,
uint _validDays
)
internal
pure
returns (uint amount)
{
if (_validDays > _stakeDays) {
uint rf = ((_validDays.sub(_stakeDays)).mul(100000)).div(_validDays);
amount = (rf.mul(_stakeAmount)).div(100000);
} else {
amount = 0;
}
}
/**
* @dev Gets the total staked NXM tokens against Smart contract
* by all stakers
* @param _stakedContractAddress smart contract address.
* @return amount total staked NXM tokens.
*/
function _deprecated_burnStakerTokenLockedAgainstSmartContract(
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex,
uint _amount
)
internal
{
uint stakerIndex = td.getStakedContractStakerIndex(
_stakedContractAddress, _stakedContractIndex);
td.pushBurnedTokens(_stakerAddress, stakerIndex, _amount);
bytes32 reason = keccak256(abi.encodePacked("UW", _stakerAddress,
_stakedContractAddress, _stakedContractIndex));
tc.burnLockedTokens(_stakerAddress, reason, _amount);
}
}
// File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IMemberRoles.sol
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity 0.5.7;
contract IMemberRoles {
event MemberRole(uint256 indexed roleId, bytes32 roleName, string roleDescription);
/// @dev Adds new member role
/// @param _roleName New role name
/// @param _roleDescription New description hash
/// @param _authorized Authorized member against every role id
function addRole(bytes32 _roleName, string memory _roleDescription, address _authorized) public;
/// @dev Assign or Delete a member from specific role.
/// @param _memberAddress Address of Member
/// @param _roleId RoleId to update
/// @param _active active is set to be True if we want to assign this role to member, False otherwise!
function updateRole(address _memberAddress, uint _roleId, bool _active) public;
/// @dev Change Member Address who holds the authority to Add/Delete any member from specific role.
/// @param _roleId roleId to update its Authorized Address
/// @param _authorized New authorized address against role id
function changeAuthorized(uint _roleId, address _authorized) public;
/// @dev Return number of member roles
function totalRoles() public view returns(uint256);
/// @dev Gets the member addresses assigned by a specific role
/// @param _memberRoleId Member role id
/// @return roleId Role id
/// @return allMemberAddress Member addresses of specified role id
function members(uint _memberRoleId) public view returns(uint, address[] memory allMemberAddress);
/// @dev Gets all members' length
/// @param _memberRoleId Member role id
/// @return memberRoleData[_memberRoleId].memberAddress.length Member length
function numberOfMembers(uint _memberRoleId) public view returns(uint);
/// @dev Return member address who holds the right to add/remove any member from specific role.
function authorized(uint _memberRoleId) public view returns(address);
/// @dev Get All role ids array that has been assigned to a member so far.
function roles(address _memberAddress) public view returns(uint[] memory assignedRoles);
/// @dev Returns true if the given role id is assigned to a member.
/// @param _memberAddress Address of member
/// @param _roleId Checks member's authenticity with the roleId.
/// i.e. Returns true if this roleId is assigned to member
function checkRole(address _memberAddress, uint _roleId) public view returns(bool);
}
// File: nexusmutual-contracts/contracts/external/ERC1132/IERC1132.sol
pragma solidity 0.5.7;
/**
* @title ERC1132 interface
* @dev see https://github.com/ethereum/EIPs/issues/1132
*/
contract IERC1132 {
/**
* @dev Reasons why a user's tokens have been locked
*/
mapping(address => bytes32[]) public lockReason;
/**
* @dev locked token structure
*/
struct LockToken {
uint256 amount;
uint256 validity;
bool claimed;
}
/**
* @dev Holds number & validity of tokens locked for a given reason for
* a specified address
*/
mapping(address => mapping(bytes32 => LockToken)) public locked;
/**
* @dev Records data of all the tokens Locked
*/
event Locked(
address indexed _of,
bytes32 indexed _reason,
uint256 _amount,
uint256 _validity
);
/**
* @dev Records data of all the tokens unlocked
*/
event Unlocked(
address indexed _of,
bytes32 indexed _reason,
uint256 _amount
);
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function lock(bytes32 _reason, uint256 _amount, uint256 _time)
public returns (bool);
/**
* @dev Returns tokens locked for a specified address for a
* specified reason
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function tokensLocked(address _of, bytes32 _reason)
public view returns (uint256 amount);
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specific time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time)
public view returns (uint256 amount);
/**
* @dev Returns total tokens held by an address (locked + transferable)
* @param _of The address to query the total balance of
*/
function totalBalanceOf(address _of)
public view returns (uint256 amount);
/**
* @dev Extends lock for a specified reason and time
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function extendLock(bytes32 _reason, uint256 _time)
public returns (bool);
/**
* @dev Increase number of tokens locked for a specified reason
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be increased
*/
function increaseLockAmount(bytes32 _reason, uint256 _amount)
public returns (bool);
/**
* @dev Returns unlockable tokens for a specified address for a specified reason
* @param _of The address to query the the unlockable token count of
* @param _reason The reason to query the unlockable tokens for
*/
function tokensUnlockable(address _of, bytes32 _reason)
public view returns (uint256 amount);
/**
* @dev Unlocks the unlockable tokens of a specified address
* @param _of Address of user, claiming back unlockable tokens
*/
function unlock(address _of)
public returns (uint256 unlockableTokens);
/**
* @dev Gets the unlockable tokens of a specified address
* @param _of The address to query the the unlockable token count of
*/
function getUnlockableTokens(address _of)
public view returns (uint256 unlockableTokens);
}
// File: nexusmutual-contracts/contracts/TokenController.sol
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity 0.5.7;
contract TokenController is IERC1132, Iupgradable {
using SafeMath for uint256;
event Burned(address indexed member, bytes32 lockedUnder, uint256 amount);
NXMToken public token;
IPooledStaking public pooledStaking;
uint public minCALockTime = uint(30).mul(1 days);
bytes32 private constant CLA = bytes32("CLA");
/**
* @dev Just for interface
*/
function changeDependentContractAddress() public {
token = NXMToken(ms.tokenAddress());
pooledStaking = IPooledStaking(ms.getLatestAddress('PS'));
}
/**
* @dev to change the operator address
* @param _newOperator is the new address of operator
*/
function changeOperator(address _newOperator) public onlyInternal {
token.changeOperator(_newOperator);
}
/**
* @dev Proxies token transfer through this contract to allow staking when members are locked for voting
* @param _from Source address
* @param _to Destination address
* @param _value Amount to transfer
*/
function operatorTransfer(address _from, address _to, uint _value) onlyInternal external returns (bool) {
require(msg.sender == address(pooledStaking), "Call is only allowed from PooledStaking address");
require(token.operatorTransfer(_from, _value), "Operator transfer failed");
require(token.transfer(_to, _value), "Internal transfer failed");
return true;
}
/**
* @dev Locks a specified amount of tokens,
* for CLA reason and for a specified time
* @param _reason The reason to lock tokens, currently restricted to CLA
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function lock(bytes32 _reason, uint256 _amount, uint256 _time) public checkPause returns (bool)
{
require(_reason == CLA,"Restricted to reason CLA");
require(minCALockTime <= _time,"Should lock for minimum time");
// If tokens are already locked, then functions extendLock or
// increaseLockAmount should be used to make any changes
_lock(msg.sender, _reason, _amount, _time);
return true;
}
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
* @param _of address whose tokens are to be locked
*/
function lockOf(address _of, bytes32 _reason, uint256 _amount, uint256 _time)
public
onlyInternal
returns (bool)
{
// If tokens are already locked, then functions extendLock or
// increaseLockAmount should be used to make any changes
_lock(_of, _reason, _amount, _time);
return true;
}
/**
* @dev Extends lock for reason CLA for a specified time
* @param _reason The reason to lock tokens, currently restricted to CLA
* @param _time Lock extension time in seconds
*/
function extendLock(bytes32 _reason, uint256 _time)
public
checkPause
returns (bool)
{
require(_reason == CLA,"Restricted to reason CLA");
_extendLock(msg.sender, _reason, _time);
return true;
}
/**
* @dev Extends lock for a specified reason and time
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function extendLockOf(address _of, bytes32 _reason, uint256 _time)
public
onlyInternal
returns (bool)
{
_extendLock(_of, _reason, _time);
return true;
}
/**
* @dev Increase number of tokens locked for a CLA reason
* @param _reason The reason to lock tokens, currently restricted to CLA
* @param _amount Number of tokens to be increased
*/
function increaseLockAmount(bytes32 _reason, uint256 _amount)
public
checkPause
returns (bool)
{
require(_reason == CLA,"Restricted to reason CLA");
require(_tokensLocked(msg.sender, _reason) > 0);
token.operatorTransfer(msg.sender, _amount);
locked[msg.sender][_reason].amount = locked[msg.sender][_reason].amount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
emit Locked(msg.sender, _reason, _amount, locked[msg.sender][_reason].validity);
return true;
}
/**
* @dev burns tokens of an address
* @param _of is the address to burn tokens of
* @param amount is the amount to burn
* @return the boolean status of the burning process
*/
function burnFrom (address _of, uint amount) public onlyInternal returns (bool) {
return token.burnFrom(_of, amount);
}
/**
* @dev Burns locked tokens of a user
* @param _of address whose tokens are to be burned
* @param _reason lock reason for which tokens are to be burned
* @param _amount amount of tokens to burn
*/
function burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal {
_burnLockedTokens(_of, _reason, _amount);
}
/**
* @dev reduce lock duration for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock reduction time in seconds
*/
function reduceLock(address _of, bytes32 _reason, uint256 _time) public onlyInternal {
_reduceLock(_of, _reason, _time);
}
/**
* @dev Released locked tokens of an address locked for a specific reason
* @param _of address whose tokens are to be released from lock
* @param _reason reason of the lock
* @param _amount amount of tokens to release
*/
function releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount)
public
onlyInternal
{
_releaseLockedTokens(_of, _reason, _amount);
}
/**
* @dev Adds an address to whitelist maintained in the contract
* @param _member address to add to whitelist
*/
function addToWhitelist(address _member) public onlyInternal {
token.addToWhiteList(_member);
}
/**
* @dev Removes an address from the whitelist in the token
* @param _member address to remove
*/
function removeFromWhitelist(address _member) public onlyInternal {
token.removeFromWhiteList(_member);
}
/**
* @dev Mints new token for an address
* @param _member address to reward the minted tokens
* @param _amount number of tokens to mint
*/
function mint(address _member, uint _amount) public onlyInternal {
token.mint(_member, _amount);
}
/**
* @dev Lock the user's tokens
* @param _of user's address.
*/
function lockForMemberVote(address _of, uint _days) public onlyInternal {
token.lockForMemberVote(_of, _days);
}
/**
* @dev Unlocks the unlockable tokens against CLA of a specified address
* @param _of Address of user, claiming back unlockable tokens against CLA
*/
function unlock(address _of)
public
checkPause
returns (uint256 unlockableTokens)
{
unlockableTokens = _tokensUnlockable(_of, CLA);
if (unlockableTokens > 0) {
locked[_of][CLA].claimed = true;
emit Unlocked(_of, CLA, unlockableTokens);
require(token.transfer(_of, unlockableTokens));
}
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "MNCLT") {
minCALockTime = val.mul(1 days);
} else {
revert("Invalid param code");
}
}
/**
* @dev Gets the validity of locked tokens of a specified address
* @param _of The address to query the validity
* @param reason reason for which tokens were locked
*/
function getLockedTokensValidity(address _of, bytes32 reason)
public
view
returns (uint256 validity)
{
validity = locked[_of][reason].validity;
}
/**
* @dev Gets the unlockable tokens of a specified address
* @param _of The address to query the the unlockable token count of
*/
function getUnlockableTokens(address _of)
public
view
returns (uint256 unlockableTokens)
{
for (uint256 i = 0; i < lockReason[_of].length; i++) {
unlockableTokens = unlockableTokens.add(_tokensUnlockable(_of, lockReason[_of][i]));
}
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function tokensLocked(address _of, bytes32 _reason)
public
view
returns (uint256 amount)
{
return _tokensLocked(_of, _reason);
}
/**
* @dev Returns unlockable tokens for a specified address for a specified reason
* @param _of The address to query the the unlockable token count of
* @param _reason The reason to query the unlockable tokens for
*/
function tokensUnlockable(address _of, bytes32 _reason)
public
view
returns (uint256 amount)
{
return _tokensUnlockable(_of, _reason);
}
function totalSupply() public view returns (uint256)
{
return token.totalSupply();
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specific time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time)
public
view
returns (uint256 amount)
{
return _tokensLockedAtTime(_of, _reason, _time);
}
/**
* @dev Returns the total amount of tokens held by an address:
* transferable + locked + staked for pooled staking - pending burns.
* Used by Claims and Governance in member voting to calculate the user's vote weight.
*
* @param _of The address to query the total balance of
* @param _of The address to query the total balance of
*/
function totalBalanceOf(address _of) public view returns (uint256 amount) {
amount = token.balanceOf(_of);
for (uint256 i = 0; i < lockReason[_of].length; i++) {
amount = amount.add(_tokensLocked(_of, lockReason[_of][i]));
}
uint stakerReward = pooledStaking.stakerReward(_of);
uint stakerDeposit = pooledStaking.stakerDeposit(_of);
amount = amount.add(stakerDeposit).add(stakerReward);
}
/**
* @dev Returns the total locked tokens at time
* Returns the total amount of locked and staked tokens at a given time. Used by MemberRoles to check eligibility
* for withdraw / switch membership. Includes tokens locked for Claim Assessment and staked for Risk Assessment.
* Does not take into account pending burns.
*
* @param _of member whose locked tokens are to be calculate
* @param _time timestamp when the tokens should be locked
*/
function totalLockedBalance(address _of, uint256 _time) public view returns (uint256 amount) {
for (uint256 i = 0; i < lockReason[_of].length; i++) {
amount = amount.add(_tokensLockedAtTime(_of, lockReason[_of][i], _time));
}
amount = amount.add(pooledStaking.stakerDeposit(_of));
}
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
* @param _of address whose tokens are to be locked
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function _lock(address _of, bytes32 _reason, uint256 _amount, uint256 _time) internal {
require(_tokensLocked(_of, _reason) == 0);
require(_amount != 0);
if (locked[_of][_reason].amount == 0) {
lockReason[_of].push(_reason);
}
require(token.operatorTransfer(_of, _amount));
uint256 validUntil = now.add(_time); //solhint-disable-line
locked[_of][_reason] = LockToken(_amount, validUntil, false);
emit Locked(_of, _reason, _amount, validUntil);
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function _tokensLocked(address _of, bytes32 _reason)
internal
view
returns (uint256 amount)
{
if (!locked[_of][_reason].claimed) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specific time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function _tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time)
internal
view
returns (uint256 amount)
{
if (locked[_of][_reason].validity > _time) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Extends lock for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function _extendLock(address _of, bytes32 _reason, uint256 _time) internal {
require(_tokensLocked(_of, _reason) > 0);
emit Unlocked(_of, _reason, locked[_of][_reason].amount);
locked[_of][_reason].validity = locked[_of][_reason].validity.add(_time);
emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity);
}
/**
* @dev reduce lock duration for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock reduction time in seconds
*/
function _reduceLock(address _of, bytes32 _reason, uint256 _time) internal {
require(_tokensLocked(_of, _reason) > 0);
emit Unlocked(_of, _reason, locked[_of][_reason].amount);
locked[_of][_reason].validity = locked[_of][_reason].validity.sub(_time);
emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity);
}
/**
* @dev Returns unlockable tokens for a specified address for a specified reason
* @param _of The address to query the the unlockable token count of
* @param _reason The reason to query the unlockable tokens for
*/
function _tokensUnlockable(address _of, bytes32 _reason) internal view returns (uint256 amount)
{
if (locked[_of][_reason].validity <= now && !locked[_of][_reason].claimed) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Burns locked tokens of a user
* @param _of address whose tokens are to be burned
* @param _reason lock reason for which tokens are to be burned
* @param _amount amount of tokens to burn
*/
function _burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal {
uint256 amount = _tokensLocked(_of, _reason);
require(amount >= _amount);
if (amount == _amount) {
locked[_of][_reason].claimed = true;
}
locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount);
if (locked[_of][_reason].amount == 0) {
_removeReason(_of, _reason);
}
token.burn(_amount);
emit Burned(_of, _reason, _amount);
}
/**
* @dev Released locked tokens of an address locked for a specific reason
* @param _of address whose tokens are to be released from lock
* @param _reason reason of the lock
* @param _amount amount of tokens to release
*/
function _releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal
{
uint256 amount = _tokensLocked(_of, _reason);
require(amount >= _amount);
if (amount == _amount) {
locked[_of][_reason].claimed = true;
}
locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount);
if (locked[_of][_reason].amount == 0) {
_removeReason(_of, _reason);
}
require(token.transfer(_of, _amount));
emit Unlocked(_of, _reason, _amount);
}
function _removeReason(address _of, bytes32 _reason) internal {
uint len = lockReason[_of].length;
for (uint i = 0; i < len; i++) {
if (lockReason[_of][i] == _reason) {
lockReason[_of][i] = lockReason[_of][len.sub(1)];
lockReason[_of].pop();
break;
}
}
}
}
// File: nexusmutual-contracts/contracts/ClaimsData.sol
/* Copyright (C) 2017 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity 0.5.7;
contract ClaimsData is Iupgradable {
using SafeMath for uint;
struct Claim {
uint coverId;
uint dateUpd;
}
struct Vote {
address voter;
uint tokens;
uint claimId;
int8 verdict;
bool rewardClaimed;
}
struct ClaimsPause {
uint coverid;
uint dateUpd;
bool submit;
}
struct ClaimPauseVoting {
uint claimid;
uint pendingTime;
bool voting;
}
struct RewardDistributed {
uint lastCAvoteIndex;
uint lastMVvoteIndex;
}
struct ClaimRewardDetails {
uint percCA;
uint percMV;
uint tokenToBeDist;
}
struct ClaimTotalTokens {
uint accept;
uint deny;
}
struct ClaimRewardStatus {
uint percCA;
uint percMV;
}
ClaimRewardStatus[] internal rewardStatus;
Claim[] internal allClaims;
Vote[] internal allvotes;
ClaimsPause[] internal claimPause;
ClaimPauseVoting[] internal claimPauseVotingEP;
mapping(address => RewardDistributed) internal voterVoteRewardReceived;
mapping(uint => ClaimRewardDetails) internal claimRewardDetail;
mapping(uint => ClaimTotalTokens) internal claimTokensCA;
mapping(uint => ClaimTotalTokens) internal claimTokensMV;
mapping(uint => int8) internal claimVote;
mapping(uint => uint) internal claimsStatus;
mapping(uint => uint) internal claimState12Count;
mapping(uint => uint[]) internal claimVoteCA;
mapping(uint => uint[]) internal claimVoteMember;
mapping(address => uint[]) internal voteAddressCA;
mapping(address => uint[]) internal voteAddressMember;
mapping(address => uint[]) internal allClaimsByAddress;
mapping(address => mapping(uint => uint)) internal userClaimVoteCA;
mapping(address => mapping(uint => uint)) internal userClaimVoteMember;
mapping(address => uint) public userClaimVotePausedOn;
uint internal claimPauseLastsubmit;
uint internal claimStartVotingFirstIndex;
uint public pendingClaimStart;
uint public claimDepositTime;
uint public maxVotingTime;
uint public minVotingTime;
uint public payoutRetryTime;
uint public claimRewardPerc;
uint public minVoteThreshold;
uint public maxVoteThreshold;
uint public majorityConsensus;
uint public pauseDaysCA;
event ClaimRaise(
uint indexed coverId,
address indexed userAddress,
uint claimId,
uint dateSubmit
);
event VoteCast(
address indexed userAddress,
uint indexed claimId,
bytes4 indexed typeOf,
uint tokens,
uint submitDate,
int8 verdict
);
constructor() public {
pendingClaimStart = 1;
maxVotingTime = 48 * 1 hours;
minVotingTime = 12 * 1 hours;
payoutRetryTime = 24 * 1 hours;
allvotes.push(Vote(address(0), 0, 0, 0, false));
allClaims.push(Claim(0, 0));
claimDepositTime = 7 days;
claimRewardPerc = 20;
minVoteThreshold = 5;
maxVoteThreshold = 10;
majorityConsensus = 70;
pauseDaysCA = 3 days;
_addRewardIncentive();
}
/**
* @dev Updates the pending claim start variable,
* the lowest claim id with a pending decision/payout.
*/
function setpendingClaimStart(uint _start) external onlyInternal {
require(pendingClaimStart <= _start);
pendingClaimStart = _start;
}
/**
* @dev Updates the max vote index for which claim assessor has received reward
* @param _voter address of the voter.
* @param caIndex last index till which reward was distributed for CA
*/
function setRewardDistributedIndexCA(address _voter, uint caIndex) external onlyInternal {
voterVoteRewardReceived[_voter].lastCAvoteIndex = caIndex;
}
/**
* @dev Used to pause claim assessor activity for 3 days
* @param user Member address whose claim voting ability needs to be paused
*/
function setUserClaimVotePausedOn(address user) external {
require(ms.checkIsAuthToGoverned(msg.sender));
userClaimVotePausedOn[user] = now;
}
/**
* @dev Updates the max vote index for which member has received reward
* @param _voter address of the voter.
* @param mvIndex last index till which reward was distributed for member
*/
function setRewardDistributedIndexMV(address _voter, uint mvIndex) external onlyInternal {
voterVoteRewardReceived[_voter].lastMVvoteIndex = mvIndex;
}
/**
* @param claimid claim id.
* @param percCA reward Percentage reward for claim assessor
* @param percMV reward Percentage reward for members
* @param tokens total tokens to be rewarded
*/
function setClaimRewardDetail(
uint claimid,
uint percCA,
uint percMV,
uint tokens
)
external
onlyInternal
{
claimRewardDetail[claimid].percCA = percCA;
claimRewardDetail[claimid].percMV = percMV;
claimRewardDetail[claimid].tokenToBeDist = tokens;
}
/**
* @dev Sets the reward claim status against a vote id.
* @param _voteid vote Id.
* @param claimed true if reward for vote is claimed, else false.
*/
function setRewardClaimed(uint _voteid, bool claimed) external onlyInternal {
allvotes[_voteid].rewardClaimed = claimed;
}
/**
* @dev Sets the final vote's result(either accepted or declined)of a claim.
* @param _claimId Claim Id.
* @param _verdict 1 if claim is accepted,-1 if declined.
*/
function changeFinalVerdict(uint _claimId, int8 _verdict) external onlyInternal {
claimVote[_claimId] = _verdict;
}
/**
* @dev Creates a new claim.
*/
function addClaim(
uint _claimId,
uint _coverId,
address _from,
uint _nowtime
)
external
onlyInternal
{
allClaims.push(Claim(_coverId, _nowtime));
allClaimsByAddress[_from].push(_claimId);
}
/**
* @dev Add Vote's details of a given claim.
*/
function addVote(
address _voter,
uint _tokens,
uint claimId,
int8 _verdict
)
external
onlyInternal
{
allvotes.push(Vote(_voter, _tokens, claimId, _verdict, false));
}
/**
* @dev Stores the id of the claim assessor vote given to a claim.
* Maintains record of all votes given by all the CA to a claim.
* @param _claimId Claim Id to which vote has given by the CA.
* @param _voteid Vote Id.
*/
function addClaimVoteCA(uint _claimId, uint _voteid) external onlyInternal {
claimVoteCA[_claimId].push(_voteid);
}
/**
* @dev Sets the id of the vote.
* @param _from Claim assessor's address who has given the vote.
* @param _claimId Claim Id for which vote has been given by the CA.
* @param _voteid Vote Id which will be stored against the given _from and claimid.
*/
function setUserClaimVoteCA(
address _from,
uint _claimId,
uint _voteid
)
external
onlyInternal
{
userClaimVoteCA[_from][_claimId] = _voteid;
voteAddressCA[_from].push(_voteid);
}
/**
* @dev Stores the tokens locked by the Claim Assessors during voting of a given claim.
* @param _claimId Claim Id.
* @param _vote 1 for accept and increases the tokens of claim as accept,
* -1 for deny and increases the tokens of claim as deny.
* @param _tokens Number of tokens.
*/
function setClaimTokensCA(uint _claimId, int8 _vote, uint _tokens) external onlyInternal {
if (_vote == 1)
claimTokensCA[_claimId].accept = claimTokensCA[_claimId].accept.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW
if (_vote == -1)
claimTokensCA[_claimId].deny = claimTokensCA[_claimId].deny.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/**
* @dev Stores the tokens locked by the Members during voting of a given claim.
* @param _claimId Claim Id.
* @param _vote 1 for accept and increases the tokens of claim as accept,
* -1 for deny and increases the tokens of claim as deny.
* @param _tokens Number of tokens.
*/
function setClaimTokensMV(uint _claimId, int8 _vote, uint _tokens) external onlyInternal {
if (_vote == 1)
claimTokensMV[_claimId].accept = claimTokensMV[_claimId].accept.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW
if (_vote == -1)
claimTokensMV[_claimId].deny = claimTokensMV[_claimId].deny.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/**
* @dev Stores the id of the member vote given to a claim.
* Maintains record of all votes given by all the Members to a claim.
* @param _claimId Claim Id to which vote has been given by the Member.
* @param _voteid Vote Id.
*/
function addClaimVotemember(uint _claimId, uint _voteid) external onlyInternal {
claimVoteMember[_claimId].push(_voteid);
}
/**
* @dev Sets the id of the vote.
* @param _from Member's address who has given the vote.
* @param _claimId Claim Id for which vote has been given by the Member.
* @param _voteid Vote Id which will be stored against the given _from and claimid.
*/
function setUserClaimVoteMember(
address _from,
uint _claimId,
uint _voteid
)
external
onlyInternal
{
userClaimVoteMember[_from][_claimId] = _voteid;
voteAddressMember[_from].push(_voteid);
}
/**
* @dev Increases the count of failure until payout of a claim is successful.
*/
function updateState12Count(uint _claimId, uint _cnt) external onlyInternal {
claimState12Count[_claimId] = claimState12Count[_claimId].add(_cnt); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/**
* @dev Sets status of a claim.
* @param _claimId Claim Id.
* @param _stat Status number.
*/
function setClaimStatus(uint _claimId, uint _stat) external onlyInternal {
claimsStatus[_claimId] = _stat;
}
/**
* @dev Sets the timestamp of a given claim at which the Claim's details has been updated.
* @param _claimId Claim Id of claim which has been changed.
* @param _dateUpd timestamp at which claim is updated.
*/
function setClaimdateUpd(uint _claimId, uint _dateUpd) external onlyInternal {
allClaims[_claimId].dateUpd = _dateUpd;
}
/**
@dev Queues Claims during Emergency Pause.
*/
function setClaimAtEmergencyPause(
uint _coverId,
uint _dateUpd,
bool _submit
)
external
onlyInternal
{
claimPause.push(ClaimsPause(_coverId, _dateUpd, _submit));
}
/**
* @dev Set submission flag for Claims queued during emergency pause.
* Set to true after EP is turned off and the claim is submitted .
*/
function setClaimSubmittedAtEPTrue(uint _index, bool _submit) external onlyInternal {
claimPause[_index].submit = _submit;
}
/**
* @dev Sets the index from which claim needs to be
* submitted when emergency pause is swithched off.
*/
function setFirstClaimIndexToSubmitAfterEP(
uint _firstClaimIndexToSubmit
)
external
onlyInternal
{
claimPauseLastsubmit = _firstClaimIndexToSubmit;
}
/**
* @dev Sets the pending vote duration for a claim in case of emergency pause.
*/
function setPendingClaimDetails(
uint _claimId,
uint _pendingTime,
bool _voting
)
external
onlyInternal
{
claimPauseVotingEP.push(ClaimPauseVoting(_claimId, _pendingTime, _voting));
}
/**
* @dev Sets voting flag true after claim is reopened for voting after emergency pause.
*/
function setPendingClaimVoteStatus(uint _claimId, bool _vote) external onlyInternal {
claimPauseVotingEP[_claimId].voting = _vote;
}
/**
* @dev Sets the index from which claim needs to be
* reopened when emergency pause is swithched off.
*/
function setFirstClaimIndexToStartVotingAfterEP(
uint _claimStartVotingFirstIndex
)
external
onlyInternal
{
claimStartVotingFirstIndex = _claimStartVotingFirstIndex;
}
/**
* @dev Calls Vote Event.
*/
function callVoteEvent(
address _userAddress,
uint _claimId,
bytes4 _typeOf,
uint _tokens,
uint _submitDate,
int8 _verdict
)
external
onlyInternal
{
emit VoteCast(
_userAddress,
_claimId,
_typeOf,
_tokens,
_submitDate,
_verdict
);
}
/**
* @dev Calls Claim Event.
*/
function callClaimEvent(
uint _coverId,
address _userAddress,
uint _claimId,
uint _datesubmit
)
external
onlyInternal
{
emit ClaimRaise(_coverId, _userAddress, _claimId, _datesubmit);
}
/**
* @dev Gets Uint Parameters by parameter code
* @param code whose details we want
* @return string value of the parameter
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "CAMAXVT") {
val = maxVotingTime / (1 hours);
} else if (code == "CAMINVT") {
val = minVotingTime / (1 hours);
} else if (code == "CAPRETRY") {
val = payoutRetryTime / (1 hours);
} else if (code == "CADEPT") {
val = claimDepositTime / (1 days);
} else if (code == "CAREWPER") {
val = claimRewardPerc;
} else if (code == "CAMINTH") {
val = minVoteThreshold;
} else if (code == "CAMAXTH") {
val = maxVoteThreshold;
} else if (code == "CACONPER") {
val = majorityConsensus;
} else if (code == "CAPAUSET") {
val = pauseDaysCA / (1 days);
}
}
/**
* @dev Get claim queued during emergency pause by index.
*/
function getClaimOfEmergencyPauseByIndex(
uint _index
)
external
view
returns(
uint coverId,
uint dateUpd,
bool submit
)
{
coverId = claimPause[_index].coverid;
dateUpd = claimPause[_index].dateUpd;
submit = claimPause[_index].submit;
}
/**
* @dev Gets the Claim's details of given claimid.
*/
function getAllClaimsByIndex(
uint _claimId
)
external
view
returns(
uint coverId,
int8 vote,
uint status,
uint dateUpd,
uint state12Count
)
{
return(
allClaims[_claimId].coverId,
claimVote[_claimId],
claimsStatus[_claimId],
allClaims[_claimId].dateUpd,
claimState12Count[_claimId]
);
}
/**
* @dev Gets the vote id of a given claim of a given Claim Assessor.
*/
function getUserClaimVoteCA(
address _add,
uint _claimId
)
external
view
returns(uint idVote)
{
return userClaimVoteCA[_add][_claimId];
}
/**
* @dev Gets the vote id of a given claim of a given member.
*/
function getUserClaimVoteMember(
address _add,
uint _claimId
)
external
view
returns(uint idVote)
{
return userClaimVoteMember[_add][_claimId];
}
/**
* @dev Gets the count of all votes.
*/
function getAllVoteLength() external view returns(uint voteCount) {
return allvotes.length.sub(1); //Start Index always from 1.
}
/**
* @dev Gets the status number of a given claim.
* @param _claimId Claim id.
* @return statno Status Number.
*/
function getClaimStatusNumber(uint _claimId) external view returns(uint claimId, uint statno) {
return (_claimId, claimsStatus[_claimId]);
}
/**
* @dev Gets the reward percentage to be distributed for a given status id
* @param statusNumber the number of type of status
* @return percCA reward Percentage for claim assessor
* @return percMV reward Percentage for members
*/
function getRewardStatus(uint statusNumber) external view returns(uint percCA, uint percMV) {
return (rewardStatus[statusNumber].percCA, rewardStatus[statusNumber].percMV);
}
/**
* @dev Gets the number of tries that have been made for a successful payout of a Claim.
*/
function getClaimState12Count(uint _claimId) external view returns(uint num) {
num = claimState12Count[_claimId];
}
/**
* @dev Gets the last update date of a claim.
*/
function getClaimDateUpd(uint _claimId) external view returns(uint dateupd) {
dateupd = allClaims[_claimId].dateUpd;
}
/**
* @dev Gets all Claims created by a user till date.
* @param _member user's address.
* @return claimarr List of Claims id.
*/
function getAllClaimsByAddress(address _member) external view returns(uint[] memory claimarr) {
return allClaimsByAddress[_member];
}
/**
* @dev Gets the number of tokens that has been locked
* while giving vote to a claim by Claim Assessors.
* @param _claimId Claim Id.
* @return accept Total number of tokens when CA accepts the claim.
* @return deny Total number of tokens when CA declines the claim.
*/
function getClaimsTokenCA(
uint _claimId
)
external
view
returns(
uint claimId,
uint accept,
uint deny
)
{
return (
_claimId,
claimTokensCA[_claimId].accept,
claimTokensCA[_claimId].deny
);
}
/**
* @dev Gets the number of tokens that have been
* locked while assessing a claim as a member.
* @param _claimId Claim Id.
* @return accept Total number of tokens in acceptance of the claim.
* @return deny Total number of tokens against the claim.
*/
function getClaimsTokenMV(
uint _claimId
)
external
view
returns(
uint claimId,
uint accept,
uint deny
)
{
return (
_claimId,
claimTokensMV[_claimId].accept,
claimTokensMV[_claimId].deny
);
}
/**
* @dev Gets the total number of votes cast as Claims assessor for/against a given claim
*/
function getCaClaimVotesToken(uint _claimId) external view returns(uint claimId, uint cnt) {
claimId = _claimId;
cnt = 0;
for (uint i = 0; i < claimVoteCA[_claimId].length; i++) {
cnt = cnt.add(allvotes[claimVoteCA[_claimId][i]].tokens);
}
}
/**
* @dev Gets the total number of tokens cast as a member for/against a given claim
*/
function getMemberClaimVotesToken(
uint _claimId
)
external
view
returns(uint claimId, uint cnt)
{
claimId = _claimId;
cnt = 0;
for (uint i = 0; i < claimVoteMember[_claimId].length; i++) {
cnt = cnt.add(allvotes[claimVoteMember[_claimId][i]].tokens);
}
}
/**
* @dev Provides information of a vote when given its vote id.
* @param _voteid Vote Id.
*/
function getVoteDetails(uint _voteid)
external view
returns(
uint tokens,
uint claimId,
int8 verdict,
bool rewardClaimed
)
{
return (
allvotes[_voteid].tokens,
allvotes[_voteid].claimId,
allvotes[_voteid].verdict,
allvotes[_voteid].rewardClaimed
);
}
/**
* @dev Gets the voter's address of a given vote id.
*/
function getVoterVote(uint _voteid) external view returns(address voter) {
return allvotes[_voteid].voter;
}
/**
* @dev Provides information of a Claim when given its claim id.
* @param _claimId Claim Id.
*/
function getClaim(
uint _claimId
)
external
view
returns(
uint claimId,
uint coverId,
int8 vote,
uint status,
uint dateUpd,
uint state12Count
)
{
return (
_claimId,
allClaims[_claimId].coverId,
claimVote[_claimId],
claimsStatus[_claimId],
allClaims[_claimId].dateUpd,
claimState12Count[_claimId]
);
}
/**
* @dev Gets the total number of votes of a given claim.
* @param _claimId Claim Id.
* @param _ca if 1: votes given by Claim Assessors to a claim,
* else returns the number of votes of given by Members to a claim.
* @return len total number of votes for/against a given claim.
*/
function getClaimVoteLength(
uint _claimId,
uint8 _ca
)
external
view
returns(uint claimId, uint len)
{
claimId = _claimId;
if (_ca == 1)
len = claimVoteCA[_claimId].length;
else
len = claimVoteMember[_claimId].length;
}
/**
* @dev Gets the verdict of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return ver 1 if vote was given in favour,-1 if given in against.
*/
function getVoteVerdict(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns(int8 ver)
{
if (_ca == 1)
ver = allvotes[claimVoteCA[_claimId][_index]].verdict;
else
ver = allvotes[claimVoteMember[_claimId][_index]].verdict;
}
/**
* @dev Gets the Number of tokens of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return tok Number of tokens.
*/
function getVoteToken(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns(uint tok)
{
if (_ca == 1)
tok = allvotes[claimVoteCA[_claimId][_index]].tokens;
else
tok = allvotes[claimVoteMember[_claimId][_index]].tokens;
}
/**
* @dev Gets the Voter's address of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return voter Voter's address.
*/
function getVoteVoter(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns(address voter)
{
if (_ca == 1)
voter = allvotes[claimVoteCA[_claimId][_index]].voter;
else
voter = allvotes[claimVoteMember[_claimId][_index]].voter;
}
/**
* @dev Gets total number of Claims created by a user till date.
* @param _add User's address.
*/
function getUserClaimCount(address _add) external view returns(uint len) {
len = allClaimsByAddress[_add].length;
}
/**
* @dev Calculates number of Claims that are in pending state.
*/
function getClaimLength() external view returns(uint len) {
len = allClaims.length.sub(pendingClaimStart);
}
/**
* @dev Gets the Number of all the Claims created till date.
*/
function actualClaimLength() external view returns(uint len) {
len = allClaims.length;
}
/**
* @dev Gets details of a claim.
* @param _index claim id = pending claim start + given index
* @param _add User's address.
* @return coverid cover against which claim has been submitted.
* @return claimId Claim Id.
* @return voteCA verdict of vote given as a Claim Assessor.
* @return voteMV verdict of vote given as a Member.
* @return statusnumber Status of claim.
*/
function getClaimFromNewStart(
uint _index,
address _add
)
external
view
returns(
uint coverid,
uint claimId,
int8 voteCA,
int8 voteMV,
uint statusnumber
)
{
uint i = pendingClaimStart.add(_index);
coverid = allClaims[i].coverId;
claimId = i;
if (userClaimVoteCA[_add][i] > 0)
voteCA = allvotes[userClaimVoteCA[_add][i]].verdict;
else
voteCA = 0;
if (userClaimVoteMember[_add][i] > 0)
voteMV = allvotes[userClaimVoteMember[_add][i]].verdict;
else
voteMV = 0;
statusnumber = claimsStatus[i];
}
/**
* @dev Gets details of a claim of a user at a given index.
*/
function getUserClaimByIndex(
uint _index,
address _add
)
external
view
returns(
uint status,
uint coverid,
uint claimId
)
{
claimId = allClaimsByAddress[_add][_index];
status = claimsStatus[claimId];
coverid = allClaims[claimId].coverId;
}
/**
* @dev Gets Id of all the votes given to a claim.
* @param _claimId Claim Id.
* @return ca id of all the votes given by Claim assessors to a claim.
* @return mv id of all the votes given by members to a claim.
*/
function getAllVotesForClaim(
uint _claimId
)
external
view
returns(
uint claimId,
uint[] memory ca,
uint[] memory mv
)
{
return (_claimId, claimVoteCA[_claimId], claimVoteMember[_claimId]);
}
/**
* @dev Gets Number of tokens deposit in a vote using
* Claim assessor's address and claim id.
* @return tokens Number of deposited tokens.
*/
function getTokensClaim(
address _of,
uint _claimId
)
external
view
returns(
uint claimId,
uint tokens
)
{
return (_claimId, allvotes[userClaimVoteCA[_of][_claimId]].tokens);
}
/**
* @param _voter address of the voter.
* @return lastCAvoteIndex last index till which reward was distributed for CA
* @return lastMVvoteIndex last index till which reward was distributed for member
*/
function getRewardDistributedIndex(
address _voter
)
external
view
returns(
uint lastCAvoteIndex,
uint lastMVvoteIndex
)
{
return (
voterVoteRewardReceived[_voter].lastCAvoteIndex,
voterVoteRewardReceived[_voter].lastMVvoteIndex
);
}
/**
* @param claimid claim id.
* @return perc_CA reward Percentage for claim assessor
* @return perc_MV reward Percentage for members
* @return tokens total tokens to be rewarded
*/
function getClaimRewardDetail(
uint claimid
)
external
view
returns(
uint percCA,
uint percMV,
uint tokens
)
{
return (
claimRewardDetail[claimid].percCA,
claimRewardDetail[claimid].percMV,
claimRewardDetail[claimid].tokenToBeDist
);
}
/**
* @dev Gets cover id of a claim.
*/
function getClaimCoverId(uint _claimId) external view returns(uint claimId, uint coverid) {
return (_claimId, allClaims[_claimId].coverId);
}
/**
* @dev Gets total number of tokens staked during voting by Claim Assessors.
* @param _claimId Claim Id.
* @param _verdict 1 to get total number of accept tokens, -1 to get total number of deny tokens.
* @return token token Number of tokens(either accept or deny on the basis of verdict given as parameter).
*/
function getClaimVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) {
claimId = _claimId;
token = 0;
for (uint i = 0; i < claimVoteCA[_claimId].length; i++) {
if (allvotes[claimVoteCA[_claimId][i]].verdict == _verdict)
token = token.add(allvotes[claimVoteCA[_claimId][i]].tokens);
}
}
/**
* @dev Gets total number of tokens staked during voting by Members.
* @param _claimId Claim Id.
* @param _verdict 1 to get total number of accept tokens,
* -1 to get total number of deny tokens.
* @return token token Number of tokens(either accept or
* deny on the basis of verdict given as parameter).
*/
function getClaimMVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) {
claimId = _claimId;
token = 0;
for (uint i = 0; i < claimVoteMember[_claimId].length; i++) {
if (allvotes[claimVoteMember[_claimId][i]].verdict == _verdict)
token = token.add(allvotes[claimVoteMember[_claimId][i]].tokens);
}
}
/**
* @param _voter address of voteid
* @param index index to get voteid in CA
*/
function getVoteAddressCA(address _voter, uint index) external view returns(uint) {
return voteAddressCA[_voter][index];
}
/**
* @param _voter address of voter
* @param index index to get voteid in member vote
*/
function getVoteAddressMember(address _voter, uint index) external view returns(uint) {
return voteAddressMember[_voter][index];
}
/**
* @param _voter address of voter
*/
function getVoteAddressCALength(address _voter) external view returns(uint) {
return voteAddressCA[_voter].length;
}
/**
* @param _voter address of voter
*/
function getVoteAddressMemberLength(address _voter) external view returns(uint) {
return voteAddressMember[_voter].length;
}
/**
* @dev Gets the Final result of voting of a claim.
* @param _claimId Claim id.
* @return verdict 1 if claim is accepted, -1 if declined.
*/
function getFinalVerdict(uint _claimId) external view returns(int8 verdict) {
return claimVote[_claimId];
}
/**
* @dev Get number of Claims queued for submission during emergency pause.
*/
function getLengthOfClaimSubmittedAtEP() external view returns(uint len) {
len = claimPause.length;
}
/**
* @dev Gets the index from which claim needs to be
* submitted when emergency pause is swithched off.
*/
function getFirstClaimIndexToSubmitAfterEP() external view returns(uint indexToSubmit) {
indexToSubmit = claimPauseLastsubmit;
}
/**
* @dev Gets number of Claims to be reopened for voting post emergency pause period.
*/
function getLengthOfClaimVotingPause() external view returns(uint len) {
len = claimPauseVotingEP.length;
}
/**
* @dev Gets claim details to be reopened for voting after emergency pause.
*/
function getPendingClaimDetailsByIndex(
uint _index
)
external
view
returns(
uint claimId,
uint pendingTime,
bool voting
)
{
claimId = claimPauseVotingEP[_index].claimid;
pendingTime = claimPauseVotingEP[_index].pendingTime;
voting = claimPauseVotingEP[_index].voting;
}
/**
* @dev Gets the index from which claim needs to be reopened when emergency pause is swithched off.
*/
function getFirstClaimIndexToStartVotingAfterEP() external view returns(uint firstindex) {
firstindex = claimStartVotingFirstIndex;
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "CAMAXVT") {
_setMaxVotingTime(val * 1 hours);
} else if (code == "CAMINVT") {
_setMinVotingTime(val * 1 hours);
} else if (code == "CAPRETRY") {
_setPayoutRetryTime(val * 1 hours);
} else if (code == "CADEPT") {
_setClaimDepositTime(val * 1 days);
} else if (code == "CAREWPER") {
_setClaimRewardPerc(val);
} else if (code == "CAMINTH") {
_setMinVoteThreshold(val);
} else if (code == "CAMAXTH") {
_setMaxVoteThreshold(val);
} else if (code == "CACONPER") {
_setMajorityConsensus(val);
} else if (code == "CAPAUSET") {
_setPauseDaysCA(val * 1 days);
} else {
revert("Invalid param code");
}
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {}
/**
* @dev Adds status under which a claim can lie.
* @param percCA reward percentage for claim assessor
* @param percMV reward percentage for members
*/
function _pushStatus(uint percCA, uint percMV) internal {
rewardStatus.push(ClaimRewardStatus(percCA, percMV));
}
/**
* @dev adds reward incentive for all possible claim status for Claim assessors and members
*/
function _addRewardIncentive() internal {
_pushStatus(0, 0); //0 Pending-Claim Assessor Vote
_pushStatus(0, 0); //1 Pending-Claim Assessor Vote Denied, Pending Member Vote
_pushStatus(0, 0); //2 Pending-CA Vote Threshold not Reached Accept, Pending Member Vote
_pushStatus(0, 0); //3 Pending-CA Vote Threshold not Reached Deny, Pending Member Vote
_pushStatus(0, 0); //4 Pending-CA Consensus not reached Accept, Pending Member Vote
_pushStatus(0, 0); //5 Pending-CA Consensus not reached Deny, Pending Member Vote
_pushStatus(100, 0); //6 Final-Claim Assessor Vote Denied
_pushStatus(100, 0); //7 Final-Claim Assessor Vote Accepted
_pushStatus(0, 100); //8 Final-Claim Assessor Vote Denied, MV Accepted
_pushStatus(0, 100); //9 Final-Claim Assessor Vote Denied, MV Denied
_pushStatus(0, 0); //10 Final-Claim Assessor Vote Accept, MV Nodecision
_pushStatus(0, 0); //11 Final-Claim Assessor Vote Denied, MV Nodecision
_pushStatus(0, 0); //12 Claim Accepted Payout Pending
_pushStatus(0, 0); //13 Claim Accepted No Payout
_pushStatus(0, 0); //14 Claim Accepted Payout Done
}
/**
* @dev Sets Maximum time(in seconds) for which claim assessment voting is open
*/
function _setMaxVotingTime(uint _time) internal {
maxVotingTime = _time;
}
/**
* @dev Sets Minimum time(in seconds) for which claim assessment voting is open
*/
function _setMinVotingTime(uint _time) internal {
minVotingTime = _time;
}
/**
* @dev Sets Minimum vote threshold required
*/
function _setMinVoteThreshold(uint val) internal {
minVoteThreshold = val;
}
/**
* @dev Sets Maximum vote threshold required
*/
function _setMaxVoteThreshold(uint val) internal {
maxVoteThreshold = val;
}
/**
* @dev Sets the value considered as Majority Consenus in voting
*/
function _setMajorityConsensus(uint val) internal {
majorityConsensus = val;
}
/**
* @dev Sets the payout retry time
*/
function _setPayoutRetryTime(uint _time) internal {
payoutRetryTime = _time;
}
/**
* @dev Sets percentage of reward given for claim assessment
*/
function _setClaimRewardPerc(uint _val) internal {
claimRewardPerc = _val;
}
/**
* @dev Sets the time for which claim is deposited.
*/
function _setClaimDepositTime(uint _time) internal {
claimDepositTime = _time;
}
/**
* @dev Sets number of days claim assessment will be paused
*/
function _setPauseDaysCA(uint val) internal {
pauseDaysCA = val;
}
}
// File: nexusmutual-contracts/contracts/PoolData.sol
/* Copyright (C) 2017 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity 0.5.7;
contract DSValue {
function peek() public view returns (bytes32, bool);
function read() public view returns (bytes32);
}
contract PoolData is Iupgradable {
using SafeMath for uint;
struct ApiId {
bytes4 typeOf;
bytes4 currency;
uint id;
uint64 dateAdd;
uint64 dateUpd;
}
struct CurrencyAssets {
address currAddress;
uint baseMin;
uint varMin;
}
struct InvestmentAssets {
address currAddress;
bool status;
uint64 minHoldingPercX100;
uint64 maxHoldingPercX100;
uint8 decimals;
}
struct IARankDetails {
bytes4 maxIACurr;
uint64 maxRate;
bytes4 minIACurr;
uint64 minRate;
}
struct McrData {
uint mcrPercx100;
uint mcrEther;
uint vFull; //Pool funds
uint64 date;
}
IARankDetails[] internal allIARankDetails;
McrData[] public allMCRData;
bytes4[] internal allInvestmentCurrencies;
bytes4[] internal allCurrencies;
bytes32[] public allAPIcall;
mapping(bytes32 => ApiId) public allAPIid;
mapping(uint64 => uint) internal datewiseId;
mapping(bytes16 => uint) internal currencyLastIndex;
mapping(bytes4 => CurrencyAssets) internal allCurrencyAssets;
mapping(bytes4 => InvestmentAssets) internal allInvestmentAssets;
mapping(bytes4 => uint) internal caAvgRate;
mapping(bytes4 => uint) internal iaAvgRate;
address public notariseMCR;
address public daiFeedAddress;
uint private constant DECIMAL1E18 = uint(10) ** 18;
uint public uniswapDeadline;
uint public liquidityTradeCallbackTime;
uint public lastLiquidityTradeTrigger;
uint64 internal lastDate;
uint public variationPercX100;
uint public iaRatesTime;
uint public minCap;
uint public mcrTime;
uint public a;
uint public shockParameter;
uint public c;
uint public mcrFailTime;
uint public ethVolumeLimit;
uint public capReached;
uint public capacityLimit;
constructor(address _notariseAdd, address _daiFeedAdd, address _daiAdd) public {
notariseMCR = _notariseAdd;
daiFeedAddress = _daiFeedAdd;
c = 5800000;
a = 1028;
mcrTime = 24 hours;
mcrFailTime = 6 hours;
allMCRData.push(McrData(0, 0, 0, 0));
minCap = 12000 * DECIMAL1E18;
shockParameter = 50;
variationPercX100 = 100; //1%
iaRatesTime = 24 hours; //24 hours in seconds
uniswapDeadline = 20 minutes;
liquidityTradeCallbackTime = 4 hours;
ethVolumeLimit = 4;
capacityLimit = 10;
allCurrencies.push("ETH");
allCurrencyAssets["ETH"] = CurrencyAssets(address(0), 1000 * DECIMAL1E18, 0);
allCurrencies.push("DAI");
allCurrencyAssets["DAI"] = CurrencyAssets(_daiAdd, 50000 * DECIMAL1E18, 0);
allInvestmentCurrencies.push("ETH");
allInvestmentAssets["ETH"] = InvestmentAssets(address(0), true, 2500, 10000, 18);
allInvestmentCurrencies.push("DAI");
allInvestmentAssets["DAI"] = InvestmentAssets(_daiAdd, true, 250, 1500, 18);
}
/**
* @dev to set the maximum cap allowed
* @param val is the new value
*/
function setCapReached(uint val) external onlyInternal {
capReached = val;
}
/// @dev Updates the 3 day average rate of a IA currency.
/// To be replaced by MakerDao's on chain rates
/// @param curr IA Currency Name.
/// @param rate Average exchange rate X 100 (of last 3 days).
function updateIAAvgRate(bytes4 curr, uint rate) external onlyInternal {
iaAvgRate[curr] = rate;
}
/// @dev Updates the 3 day average rate of a CA currency.
/// To be replaced by MakerDao's on chain rates
/// @param curr Currency Name.
/// @param rate Average exchange rate X 100 (of last 3 days).
function updateCAAvgRate(bytes4 curr, uint rate) external onlyInternal {
caAvgRate[curr] = rate;
}
/// @dev Adds details of (Minimum Capital Requirement)MCR.
/// @param mcrp Minimum Capital Requirement percentage (MCR% * 100 ,Ex:for 54.56% ,given 5456)
/// @param vf Pool fund value in Ether used in the last full daily calculation from the Capital model.
function pushMCRData(uint mcrp, uint mcre, uint vf, uint64 time) external onlyInternal {
allMCRData.push(McrData(mcrp, mcre, vf, time));
}
/**
* @dev Updates the Timestamp at which result of oracalize call is received.
*/
function updateDateUpdOfAPI(bytes32 myid) external onlyInternal {
allAPIid[myid].dateUpd = uint64(now);
}
/**
* @dev Saves the details of the Oraclize API.
* @param myid Id return by the oraclize query.
* @param _typeof type of the query for which oraclize call is made.
* @param id ID of the proposal,quote,cover etc. for which oraclize call is made
*/
function saveApiDetails(bytes32 myid, bytes4 _typeof, uint id) external onlyInternal {
allAPIid[myid] = ApiId(_typeof, "", id, uint64(now), uint64(now));
}
/**
* @dev Stores the id return by the oraclize query.
* Maintains record of all the Ids return by oraclize query.
* @param myid Id return by the oraclize query.
*/
function addInAllApiCall(bytes32 myid) external onlyInternal {
allAPIcall.push(myid);
}
/**
* @dev Saves investment asset rank details.
* @param maxIACurr Maximum ranked investment asset currency.
* @param maxRate Maximum ranked investment asset rate.
* @param minIACurr Minimum ranked investment asset currency.
* @param minRate Minimum ranked investment asset rate.
* @param date in yyyymmdd.
*/
function saveIARankDetails(
bytes4 maxIACurr,
uint64 maxRate,
bytes4 minIACurr,
uint64 minRate,
uint64 date
)
external
onlyInternal
{
allIARankDetails.push(IARankDetails(maxIACurr, maxRate, minIACurr, minRate));
datewiseId[date] = allIARankDetails.length.sub(1);
}
/**
* @dev to get the time for the laste liquidity trade trigger
*/
function setLastLiquidityTradeTrigger() external onlyInternal {
lastLiquidityTradeTrigger = now;
}
/**
* @dev Updates Last Date.
*/
function updatelastDate(uint64 newDate) external onlyInternal {
lastDate = newDate;
}
/**
* @dev Adds currency asset currency.
* @param curr currency of the asset
* @param currAddress address of the currency
* @param baseMin base minimum in 10^18.
*/
function addCurrencyAssetCurrency(
bytes4 curr,
address currAddress,
uint baseMin
)
external
{
require(ms.checkIsAuthToGoverned(msg.sender));
allCurrencies.push(curr);
allCurrencyAssets[curr] = CurrencyAssets(currAddress, baseMin, 0);
}
/**
* @dev Adds investment asset.
*/
function addInvestmentAssetCurrency(
bytes4 curr,
address currAddress,
bool status,
uint64 minHoldingPercX100,
uint64 maxHoldingPercX100,
uint8 decimals
)
external
{
require(ms.checkIsAuthToGoverned(msg.sender));
allInvestmentCurrencies.push(curr);
allInvestmentAssets[curr] = InvestmentAssets(currAddress, status,
minHoldingPercX100, maxHoldingPercX100, decimals);
}
/**
* @dev Changes base minimum of a given currency asset.
*/
function changeCurrencyAssetBaseMin(bytes4 curr, uint baseMin) external {
require(ms.checkIsAuthToGoverned(msg.sender));
allCurrencyAssets[curr].baseMin = baseMin;
}
/**
* @dev changes variable minimum of a given currency asset.
*/
function changeCurrencyAssetVarMin(bytes4 curr, uint varMin) external onlyInternal {
allCurrencyAssets[curr].varMin = varMin;
}
/**
* @dev Changes the investment asset status.
*/
function changeInvestmentAssetStatus(bytes4 curr, bool status) external {
require(ms.checkIsAuthToGoverned(msg.sender));
allInvestmentAssets[curr].status = status;
}
/**
* @dev Changes the investment asset Holding percentage of a given currency.
*/
function changeInvestmentAssetHoldingPerc(
bytes4 curr,
uint64 minPercX100,
uint64 maxPercX100
)
external
{
require(ms.checkIsAuthToGoverned(msg.sender));
allInvestmentAssets[curr].minHoldingPercX100 = minPercX100;
allInvestmentAssets[curr].maxHoldingPercX100 = maxPercX100;
}
/**
* @dev Gets Currency asset token address.
*/
function changeCurrencyAssetAddress(bytes4 curr, address currAdd) external {
require(ms.checkIsAuthToGoverned(msg.sender));
allCurrencyAssets[curr].currAddress = currAdd;
}
/**
* @dev Changes Investment asset token address.
*/
function changeInvestmentAssetAddressAndDecimal(
bytes4 curr,
address currAdd,
uint8 newDecimal
)
external
{
require(ms.checkIsAuthToGoverned(msg.sender));
allInvestmentAssets[curr].currAddress = currAdd;
allInvestmentAssets[curr].decimals = newDecimal;
}
/// @dev Changes address allowed to post MCR.
function changeNotariseAddress(address _add) external onlyInternal {
notariseMCR = _add;
}
/// @dev updates daiFeedAddress address.
/// @param _add address of DAI feed.
function changeDAIfeedAddress(address _add) external onlyInternal {
daiFeedAddress = _add;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) {
codeVal = code;
if (code == "MCRTIM") {
val = mcrTime / (1 hours);
} else if (code == "MCRFTIM") {
val = mcrFailTime / (1 hours);
} else if (code == "MCRMIN") {
val = minCap;
} else if (code == "MCRSHOCK") {
val = shockParameter;
} else if (code == "MCRCAPL") {
val = capacityLimit;
} else if (code == "IMZ") {
val = variationPercX100;
} else if (code == "IMRATET") {
val = iaRatesTime / (1 hours);
} else if (code == "IMUNIDL") {
val = uniswapDeadline / (1 minutes);
} else if (code == "IMLIQT") {
val = liquidityTradeCallbackTime / (1 hours);
} else if (code == "IMETHVL") {
val = ethVolumeLimit;
} else if (code == "C") {
val = c;
} else if (code == "A") {
val = a;
}
}
/// @dev Checks whether a given address can notaise MCR data or not.
/// @param _add Address.
/// @return res Returns 0 if address is not authorized, else 1.
function isnotarise(address _add) external view returns(bool res) {
res = false;
if (_add == notariseMCR)
res = true;
}
/// @dev Gets the details of last added MCR.
/// @return mcrPercx100 Total Minimum Capital Requirement percentage of that month of year(multiplied by 100).
/// @return vFull Total Pool fund value in Ether used in the last full daily calculation.
function getLastMCR() external view returns(uint mcrPercx100, uint mcrEtherx1E18, uint vFull, uint64 date) {
uint index = allMCRData.length.sub(1);
return (
allMCRData[index].mcrPercx100,
allMCRData[index].mcrEther,
allMCRData[index].vFull,
allMCRData[index].date
);
}
/// @dev Gets last Minimum Capital Requirement percentage of Capital Model
/// @return val MCR% value,multiplied by 100.
function getLastMCRPerc() external view returns(uint) {
return allMCRData[allMCRData.length.sub(1)].mcrPercx100;
}
/// @dev Gets last Ether price of Capital Model
/// @return val ether value,multiplied by 100.
function getLastMCREther() external view returns(uint) {
return allMCRData[allMCRData.length.sub(1)].mcrEther;
}
/// @dev Gets Pool fund value in Ether used in the last full daily calculation from the Capital model.
function getLastVfull() external view returns(uint) {
return allMCRData[allMCRData.length.sub(1)].vFull;
}
/// @dev Gets last Minimum Capital Requirement in Ether.
/// @return date of MCR.
function getLastMCRDate() external view returns(uint64 date) {
date = allMCRData[allMCRData.length.sub(1)].date;
}
/// @dev Gets details for token price calculation.
function getTokenPriceDetails(bytes4 curr) external view returns(uint _a, uint _c, uint rate) {
_a = a;
_c = c;
rate = _getAvgRate(curr, false);
}
/// @dev Gets the total number of times MCR calculation has been made.
function getMCRDataLength() external view returns(uint len) {
len = allMCRData.length;
}
/**
* @dev Gets investment asset rank details by given date.
*/
function getIARankDetailsByDate(
uint64 date
)
external
view
returns(
bytes4 maxIACurr,
uint64 maxRate,
bytes4 minIACurr,
uint64 minRate
)
{
uint index = datewiseId[date];
return (
allIARankDetails[index].maxIACurr,
allIARankDetails[index].maxRate,
allIARankDetails[index].minIACurr,
allIARankDetails[index].minRate
);
}
/**
* @dev Gets Last Date.
*/
function getLastDate() external view returns(uint64 date) {
return lastDate;
}
/**
* @dev Gets investment currency for a given index.
*/
function getInvestmentCurrencyByIndex(uint index) external view returns(bytes4 currName) {
return allInvestmentCurrencies[index];
}
/**
* @dev Gets count of investment currency.
*/
function getInvestmentCurrencyLen() external view returns(uint len) {
return allInvestmentCurrencies.length;
}
/**
* @dev Gets all the investment currencies.
*/
function getAllInvestmentCurrencies() external view returns(bytes4[] memory currencies) {
return allInvestmentCurrencies;
}
/**
* @dev Gets All currency for a given index.
*/
function getCurrenciesByIndex(uint index) external view returns(bytes4 currName) {
return allCurrencies[index];
}
/**
* @dev Gets count of All currency.
*/
function getAllCurrenciesLen() external view returns(uint len) {
return allCurrencies.length;
}
/**
* @dev Gets all currencies
*/
function getAllCurrencies() external view returns(bytes4[] memory currencies) {
return allCurrencies;
}
/**
* @dev Gets currency asset details for a given currency.
*/
function getCurrencyAssetVarBase(
bytes4 curr
)
external
view
returns(
bytes4 currency,
uint baseMin,
uint varMin
)
{
return (
curr,
allCurrencyAssets[curr].baseMin,
allCurrencyAssets[curr].varMin
);
}
/**
* @dev Gets minimum variable value for currency asset.
*/
function getCurrencyAssetVarMin(bytes4 curr) external view returns(uint varMin) {
return allCurrencyAssets[curr].varMin;
}
/**
* @dev Gets base minimum of a given currency asset.
*/
function getCurrencyAssetBaseMin(bytes4 curr) external view returns(uint baseMin) {
return allCurrencyAssets[curr].baseMin;
}
/**
* @dev Gets investment asset maximum and minimum holding percentage of a given currency.
*/
function getInvestmentAssetHoldingPerc(
bytes4 curr
)
external
view
returns(
uint64 minHoldingPercX100,
uint64 maxHoldingPercX100
)
{
return (
allInvestmentAssets[curr].minHoldingPercX100,
allInvestmentAssets[curr].maxHoldingPercX100
);
}
/**
* @dev Gets investment asset decimals.
*/
function getInvestmentAssetDecimals(bytes4 curr) external view returns(uint8 decimal) {
return allInvestmentAssets[curr].decimals;
}
/**
* @dev Gets investment asset maximum holding percentage of a given currency.
*/
function getInvestmentAssetMaxHoldingPerc(bytes4 curr) external view returns(uint64 maxHoldingPercX100) {
return allInvestmentAssets[curr].maxHoldingPercX100;
}
/**
* @dev Gets investment asset minimum holding percentage of a given currency.
*/
function getInvestmentAssetMinHoldingPerc(bytes4 curr) external view returns(uint64 minHoldingPercX100) {
return allInvestmentAssets[curr].minHoldingPercX100;
}
/**
* @dev Gets investment asset details of a given currency
*/
function getInvestmentAssetDetails(
bytes4 curr
)
external
view
returns(
bytes4 currency,
address currAddress,
bool status,
uint64 minHoldingPerc,
uint64 maxHoldingPerc,
uint8 decimals
)
{
return (
curr,
allInvestmentAssets[curr].currAddress,
allInvestmentAssets[curr].status,
allInvestmentAssets[curr].minHoldingPercX100,
allInvestmentAssets[curr].maxHoldingPercX100,
allInvestmentAssets[curr].decimals
);
}
/**
* @dev Gets Currency asset token address.
*/
function getCurrencyAssetAddress(bytes4 curr) external view returns(address) {
return allCurrencyAssets[curr].currAddress;
}
/**
* @dev Gets investment asset token address.
*/
function getInvestmentAssetAddress(bytes4 curr) external view returns(address) {
return allInvestmentAssets[curr].currAddress;
}
/**
* @dev Gets investment asset active Status of a given currency.
*/
function getInvestmentAssetStatus(bytes4 curr) external view returns(bool status) {
return allInvestmentAssets[curr].status;
}
/**
* @dev Gets type of oraclize query for a given Oraclize Query ID.
* @param myid Oraclize Query ID identifying the query for which the result is being received.
* @return _typeof It could be of type "quote","quotation","cover","claim" etc.
*/
function getApiIdTypeOf(bytes32 myid) external view returns(bytes4) {
return allAPIid[myid].typeOf;
}
/**
* @dev Gets ID associated to oraclize query for a given Oraclize Query ID.
* @param myid Oraclize Query ID identifying the query for which the result is being received.
* @return id1 It could be the ID of "proposal","quotation","cover","claim" etc.
*/
function getIdOfApiId(bytes32 myid) external view returns(uint) {
return allAPIid[myid].id;
}
/**
* @dev Gets the Timestamp of a oracalize call.
*/
function getDateAddOfAPI(bytes32 myid) external view returns(uint64) {
return allAPIid[myid].dateAdd;
}
/**
* @dev Gets the Timestamp at which result of oracalize call is received.
*/
function getDateUpdOfAPI(bytes32 myid) external view returns(uint64) {
return allAPIid[myid].dateUpd;
}
/**
* @dev Gets currency by oracalize id.
*/
function getCurrOfApiId(bytes32 myid) external view returns(bytes4) {
return allAPIid[myid].currency;
}
/**
* @dev Gets ID return by the oraclize query of a given index.
* @param index Index.
* @return myid ID return by the oraclize query.
*/
function getApiCallIndex(uint index) external view returns(bytes32 myid) {
myid = allAPIcall[index];
}
/**
* @dev Gets Length of API call.
*/
function getApilCallLength() external view returns(uint) {
return allAPIcall.length;
}
/**
* @dev Get Details of Oraclize API when given Oraclize Id.
* @param myid ID return by the oraclize query.
* @return _typeof ype of the query for which oraclize
* call is made.("proposal","quote","quotation" etc.)
*/
function getApiCallDetails(
bytes32 myid
)
external
view
returns(
bytes4 _typeof,
bytes4 curr,
uint id,
uint64 dateAdd,
uint64 dateUpd
)
{
return (
allAPIid[myid].typeOf,
allAPIid[myid].currency,
allAPIid[myid].id,
allAPIid[myid].dateAdd,
allAPIid[myid].dateUpd
);
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "MCRTIM") {
_changeMCRTime(val * 1 hours);
} else if (code == "MCRFTIM") {
_changeMCRFailTime(val * 1 hours);
} else if (code == "MCRMIN") {
_changeMinCap(val);
} else if (code == "MCRSHOCK") {
_changeShockParameter(val);
} else if (code == "MCRCAPL") {
_changeCapacityLimit(val);
} else if (code == "IMZ") {
_changeVariationPercX100(val);
} else if (code == "IMRATET") {
_changeIARatesTime(val * 1 hours);
} else if (code == "IMUNIDL") {
_changeUniswapDeadlineTime(val * 1 minutes);
} else if (code == "IMLIQT") {
_changeliquidityTradeCallbackTime(val * 1 hours);
} else if (code == "IMETHVL") {
_setEthVolumeLimit(val);
} else if (code == "C") {
_changeC(val);
} else if (code == "A") {
_changeA(val);
} else {
revert("Invalid param code");
}
}
/**
* @dev to get the average rate of currency rate
* @param curr is the currency in concern
* @return required rate
*/
function getCAAvgRate(bytes4 curr) public view returns(uint rate) {
return _getAvgRate(curr, false);
}
/**
* @dev to get the average rate of investment rate
* @param curr is the investment in concern
* @return required rate
*/
function getIAAvgRate(bytes4 curr) public view returns(uint rate) {
return _getAvgRate(curr, true);
}
function changeDependentContractAddress() public onlyInternal {}
/// @dev Gets the average rate of a CA currency.
/// @param curr Currency Name.
/// @return rate Average rate X 100(of last 3 days).
function _getAvgRate(bytes4 curr, bool isIA) internal view returns(uint rate) {
if (curr == "DAI") {
DSValue ds = DSValue(daiFeedAddress);
rate = uint(ds.read()).div(uint(10) ** 16);
} else if (isIA) {
rate = iaAvgRate[curr];
} else {
rate = caAvgRate[curr];
}
}
/**
* @dev to set the ethereum volume limit
* @param val is the new limit value
*/
function _setEthVolumeLimit(uint val) internal {
ethVolumeLimit = val;
}
/// @dev Sets minimum Cap.
function _changeMinCap(uint newCap) internal {
minCap = newCap;
}
/// @dev Sets Shock Parameter.
function _changeShockParameter(uint newParam) internal {
shockParameter = newParam;
}
/// @dev Changes time period for obtaining new MCR data from external oracle query.
function _changeMCRTime(uint _time) internal {
mcrTime = _time;
}
/// @dev Sets MCR Fail time.
function _changeMCRFailTime(uint _time) internal {
mcrFailTime = _time;
}
/**
* @dev to change the uniswap deadline time
* @param newDeadline is the value
*/
function _changeUniswapDeadlineTime(uint newDeadline) internal {
uniswapDeadline = newDeadline;
}
/**
* @dev to change the liquidity trade call back time
* @param newTime is the new value to be set
*/
function _changeliquidityTradeCallbackTime(uint newTime) internal {
liquidityTradeCallbackTime = newTime;
}
/**
* @dev Changes time after which investment asset rates need to be fed.
*/
function _changeIARatesTime(uint _newTime) internal {
iaRatesTime = _newTime;
}
/**
* @dev Changes the variation range percentage.
*/
function _changeVariationPercX100(uint newPercX100) internal {
variationPercX100 = newPercX100;
}
/// @dev Changes Growth Step
function _changeC(uint newC) internal {
c = newC;
}
/// @dev Changes scaling factor.
function _changeA(uint val) internal {
a = val;
}
/**
* @dev to change the capacity limit
* @param val is the new value
*/
function _changeCapacityLimit(uint val) internal {
capacityLimit = val;
}
}
// File: nexusmutual-contracts/contracts/QuotationData.sol
/* Copyright (C) 2017 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity 0.5.7;
contract QuotationData is Iupgradable {
using SafeMath for uint;
enum HCIDStatus { NA, kycPending, kycPass, kycFailedOrRefunded, kycPassNoCover }
enum CoverStatus { Active, ClaimAccepted, ClaimDenied, CoverExpired, ClaimSubmitted, Requested }
struct Cover {
address payable memberAddress;
bytes4 currencyCode;
uint sumAssured;
uint16 coverPeriod;
uint validUntil;
address scAddress;
uint premiumNXM;
}
struct HoldCover {
uint holdCoverId;
address payable userAddress;
address scAddress;
bytes4 coverCurr;
uint[] coverDetails;
uint16 coverPeriod;
}
address public authQuoteEngine;
mapping(bytes4 => uint) internal currencyCSA;
mapping(address => uint[]) internal userCover;
mapping(address => uint[]) public userHoldedCover;
mapping(address => bool) public refundEligible;
mapping(address => mapping(bytes4 => uint)) internal currencyCSAOfSCAdd;
mapping(uint => uint8) public coverStatus;
mapping(uint => uint) public holdedCoverIDStatus;
mapping(uint => bool) public timestampRepeated;
Cover[] internal allCovers;
HoldCover[] internal allCoverHolded;
uint public stlp;
uint public stl;
uint public pm;
uint public minDays;
uint public tokensRetained;
address public kycAuthAddress;
event CoverDetailsEvent(
uint indexed cid,
address scAdd,
uint sumAssured,
uint expiry,
uint premium,
uint premiumNXM,
bytes4 curr
);
event CoverStatusEvent(uint indexed cid, uint8 statusNum);
constructor(address _authQuoteAdd, address _kycAuthAdd) public {
authQuoteEngine = _authQuoteAdd;
kycAuthAddress = _kycAuthAdd;
stlp = 90;
stl = 100;
pm = 30;
minDays = 30;
tokensRetained = 10;
allCovers.push(Cover(address(0), "0x00", 0, 0, 0, address(0), 0));
uint[] memory arr = new uint[](1);
allCoverHolded.push(HoldCover(0, address(0), address(0), 0x00, arr, 0));
}
/// @dev Adds the amount in Total Sum Assured of a given currency of a given smart contract address.
/// @param _add Smart Contract Address.
/// @param _amount Amount to be added.
function addInTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal {
currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/// @dev Subtracts the amount from Total Sum Assured of a given currency and smart contract address.
/// @param _add Smart Contract Address.
/// @param _amount Amount to be subtracted.
function subFromTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal {
currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].sub(_amount);
}
/// @dev Subtracts the amount from Total Sum Assured of a given currency.
/// @param _curr Currency Name.
/// @param _amount Amount to be subtracted.
function subFromTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal {
currencyCSA[_curr] = currencyCSA[_curr].sub(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/// @dev Adds the amount in Total Sum Assured of a given currency.
/// @param _curr Currency Name.
/// @param _amount Amount to be added.
function addInTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal {
currencyCSA[_curr] = currencyCSA[_curr].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/// @dev sets bit for timestamp to avoid replay attacks.
function setTimestampRepeated(uint _timestamp) external onlyInternal {
timestampRepeated[_timestamp] = true;
}
/// @dev Creates a blank new cover.
function addCover(
uint16 _coverPeriod,
uint _sumAssured,
address payable _userAddress,
bytes4 _currencyCode,
address _scAddress,
uint premium,
uint premiumNXM
)
external
onlyInternal
{
uint expiryDate = now.add(uint(_coverPeriod).mul(1 days));
allCovers.push(Cover(_userAddress, _currencyCode,
_sumAssured, _coverPeriod, expiryDate, _scAddress, premiumNXM));
uint cid = allCovers.length.sub(1);
userCover[_userAddress].push(cid);
emit CoverDetailsEvent(cid, _scAddress, _sumAssured, expiryDate, premium, premiumNXM, _currencyCode);
}
/// @dev create holded cover which will process after verdict of KYC.
function addHoldCover(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] calldata coverDetails,
uint16 coverPeriod
)
external
onlyInternal
{
uint holdedCoverLen = allCoverHolded.length;
holdedCoverIDStatus[holdedCoverLen] = uint(HCIDStatus.kycPending);
allCoverHolded.push(HoldCover(holdedCoverLen, from, scAddress,
coverCurr, coverDetails, coverPeriod));
userHoldedCover[from].push(allCoverHolded.length.sub(1));
}
///@dev sets refund eligible bit.
///@param _add user address.
///@param status indicates if user have pending kyc.
function setRefundEligible(address _add, bool status) external onlyInternal {
refundEligible[_add] = status;
}
/// @dev to set current status of particular holded coverID (1 for not completed KYC,
/// 2 for KYC passed, 3 for failed KYC or full refunded,
/// 4 for KYC completed but cover not processed)
function setHoldedCoverIDStatus(uint holdedCoverID, uint status) external onlyInternal {
holdedCoverIDStatus[holdedCoverID] = status;
}
/**
* @dev to set address of kyc authentication
* @param _add is the new address
*/
function setKycAuthAddress(address _add) external onlyInternal {
kycAuthAddress = _add;
}
/// @dev Changes authorised address for generating quote off chain.
function changeAuthQuoteEngine(address _add) external onlyInternal {
authQuoteEngine = _add;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) {
codeVal = code;
if (code == "STLP") {
val = stlp;
} else if (code == "STL") {
val = stl;
} else if (code == "PM") {
val = pm;
} else if (code == "QUOMIND") {
val = minDays;
} else if (code == "QUOTOK") {
val = tokensRetained;
}
}
/// @dev Gets Product details.
/// @return _minDays minimum cover period.
/// @return _PM Profit margin.
/// @return _STL short term Load.
/// @return _STLP short term load period.
function getProductDetails()
external
view
returns (
uint _minDays,
uint _pm,
uint _stl,
uint _stlp
)
{
_minDays = minDays;
_pm = pm;
_stl = stl;
_stlp = stlp;
}
/// @dev Gets total number covers created till date.
function getCoverLength() external view returns(uint len) {
return (allCovers.length);
}
/// @dev Gets Authorised Engine address.
function getAuthQuoteEngine() external view returns(address _add) {
_add = authQuoteEngine;
}
/// @dev Gets the Total Sum Assured amount of a given currency.
function getTotalSumAssured(bytes4 _curr) external view returns(uint amount) {
amount = currencyCSA[_curr];
}
/// @dev Gets all the Cover ids generated by a given address.
/// @param _add User's address.
/// @return allCover array of covers.
function getAllCoversOfUser(address _add) external view returns(uint[] memory allCover) {
return (userCover[_add]);
}
/// @dev Gets total number of covers generated by a given address
function getUserCoverLength(address _add) external view returns(uint len) {
len = userCover[_add].length;
}
/// @dev Gets the status of a given cover.
function getCoverStatusNo(uint _cid) external view returns(uint8) {
return coverStatus[_cid];
}
/// @dev Gets the Cover Period (in days) of a given cover.
function getCoverPeriod(uint _cid) external view returns(uint32 cp) {
cp = allCovers[_cid].coverPeriod;
}
/// @dev Gets the Sum Assured Amount of a given cover.
function getCoverSumAssured(uint _cid) external view returns(uint sa) {
sa = allCovers[_cid].sumAssured;
}
/// @dev Gets the Currency Name in which a given cover is assured.
function getCurrencyOfCover(uint _cid) external view returns(bytes4 curr) {
curr = allCovers[_cid].currencyCode;
}
/// @dev Gets the validity date (timestamp) of a given cover.
function getValidityOfCover(uint _cid) external view returns(uint date) {
date = allCovers[_cid].validUntil;
}
/// @dev Gets Smart contract address of cover.
function getscAddressOfCover(uint _cid) external view returns(uint, address) {
return (_cid, allCovers[_cid].scAddress);
}
/// @dev Gets the owner address of a given cover.
function getCoverMemberAddress(uint _cid) external view returns(address payable _add) {
_add = allCovers[_cid].memberAddress;
}
/// @dev Gets the premium amount of a given cover in NXM.
function getCoverPremiumNXM(uint _cid) external view returns(uint _premiumNXM) {
_premiumNXM = allCovers[_cid].premiumNXM;
}
/// @dev Provides the details of a cover Id
/// @param _cid cover Id
/// @return memberAddress cover user address.
/// @return scAddress smart contract Address
/// @return currencyCode currency of cover
/// @return sumAssured sum assured of cover
/// @return premiumNXM premium in NXM
function getCoverDetailsByCoverID1(
uint _cid
)
external
view
returns (
uint cid,
address _memberAddress,
address _scAddress,
bytes4 _currencyCode,
uint _sumAssured,
uint premiumNXM
)
{
return (
_cid,
allCovers[_cid].memberAddress,
allCovers[_cid].scAddress,
allCovers[_cid].currencyCode,
allCovers[_cid].sumAssured,
allCovers[_cid].premiumNXM
);
}
/// @dev Provides details of a cover Id
/// @param _cid cover Id
/// @return status status of cover.
/// @return sumAssured Sum assurance of cover.
/// @return coverPeriod Cover Period of cover (in days).
/// @return validUntil is validity of cover.
function getCoverDetailsByCoverID2(
uint _cid
)
external
view
returns (
uint cid,
uint8 status,
uint sumAssured,
uint16 coverPeriod,
uint validUntil
)
{
return (
_cid,
coverStatus[_cid],
allCovers[_cid].sumAssured,
allCovers[_cid].coverPeriod,
allCovers[_cid].validUntil
);
}
/// @dev Provides details of a holded cover Id
/// @param _hcid holded cover Id
/// @return scAddress SmartCover address of cover.
/// @return coverCurr currency of cover.
/// @return coverPeriod Cover Period of cover (in days).
function getHoldedCoverDetailsByID1(
uint _hcid
)
external
view
returns (
uint hcid,
address scAddress,
bytes4 coverCurr,
uint16 coverPeriod
)
{
return (
_hcid,
allCoverHolded[_hcid].scAddress,
allCoverHolded[_hcid].coverCurr,
allCoverHolded[_hcid].coverPeriod
);
}
/// @dev Gets total number holded covers created till date.
function getUserHoldedCoverLength(address _add) external view returns (uint) {
return userHoldedCover[_add].length;
}
/// @dev Gets holded cover index by index of user holded covers.
function getUserHoldedCoverByIndex(address _add, uint index) external view returns (uint) {
return userHoldedCover[_add][index];
}
/// @dev Provides the details of a holded cover Id
/// @param _hcid holded cover Id
/// @return memberAddress holded cover user address.
/// @return coverDetails array contains SA, Cover Currency Price,Price in NXM, Expiration time of Qoute.
function getHoldedCoverDetailsByID2(
uint _hcid
)
external
view
returns (
uint hcid,
address payable memberAddress,
uint[] memory coverDetails
)
{
return (
_hcid,
allCoverHolded[_hcid].userAddress,
allCoverHolded[_hcid].coverDetails
);
}
/// @dev Gets the Total Sum Assured amount of a given currency and smart contract address.
function getTotalSumAssuredSC(address _add, bytes4 _curr) external view returns(uint amount) {
amount = currencyCSAOfSCAdd[_add][_curr];
}
//solhint-disable-next-line
function changeDependentContractAddress() public {}
/// @dev Changes the status of a given cover.
/// @param _cid cover Id.
/// @param _stat New status.
function changeCoverStatusNo(uint _cid, uint8 _stat) public onlyInternal {
coverStatus[_cid] = _stat;
emit CoverStatusEvent(_cid, _stat);
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "STLP") {
_changeSTLP(val);
} else if (code == "STL") {
_changeSTL(val);
} else if (code == "PM") {
_changePM(val);
} else if (code == "QUOMIND") {
_changeMinDays(val);
} else if (code == "QUOTOK") {
_setTokensRetained(val);
} else {
revert("Invalid param code");
}
}
/// @dev Changes the existing Profit Margin value
function _changePM(uint _pm) internal {
pm = _pm;
}
/// @dev Changes the existing Short Term Load Period (STLP) value.
function _changeSTLP(uint _stlp) internal {
stlp = _stlp;
}
/// @dev Changes the existing Short Term Load (STL) value.
function _changeSTL(uint _stl) internal {
stl = _stl;
}
/// @dev Changes the existing Minimum cover period (in days)
function _changeMinDays(uint _days) internal {
minDays = _days;
}
/**
* @dev to set the the amount of tokens retained
* @param val is the amount retained
*/
function _setTokensRetained(uint val) internal {
tokensRetained = val;
}
}
// File: nexusmutual-contracts/contracts/TokenData.sol
/* Copyright (C) 2017 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity 0.5.7;
contract TokenData is Iupgradable {
using SafeMath for uint;
address payable public walletAddress;
uint public lockTokenTimeAfterCoverExp;
uint public bookTime;
uint public lockCADays;
uint public lockMVDays;
uint public scValidDays;
uint public joiningFee;
uint public stakerCommissionPer;
uint public stakerMaxCommissionPer;
uint public tokenExponent;
uint public priceStep;
struct StakeCommission {
uint commissionEarned;
uint commissionRedeemed;
}
struct Stake {
address stakedContractAddress;
uint stakedContractIndex;
uint dateAdd;
uint stakeAmount;
uint unlockedAmount;
uint burnedAmount;
uint unLockableBeforeLastBurn;
}
struct Staker {
address stakerAddress;
uint stakerIndex;
}
struct CoverNote {
uint amount;
bool isDeposited;
}
/**
* @dev mapping of uw address to array of sc address to fetch
* all staked contract address of underwriter, pushing
* data into this array of Stake returns stakerIndex
*/
mapping(address => Stake[]) public stakerStakedContracts;
/**
* @dev mapping of sc address to array of UW address to fetch
* all underwritters of the staked smart contract
* pushing data into this mapped array returns scIndex
*/
mapping(address => Staker[]) public stakedContractStakers;
/**
* @dev mapping of staked contract Address to the array of StakeCommission
* here index of this array is stakedContractIndex
*/
mapping(address => mapping(uint => StakeCommission)) public stakedContractStakeCommission;
mapping(address => uint) public lastCompletedStakeCommission;
/**
* @dev mapping of the staked contract address to the current
* staker index who will receive commission.
*/
mapping(address => uint) public stakedContractCurrentCommissionIndex;
/**
* @dev mapping of the staked contract address to the
* current staker index to burn token from.
*/
mapping(address => uint) public stakedContractCurrentBurnIndex;
/**
* @dev mapping to return true if Cover Note deposited against coverId
*/
mapping(uint => CoverNote) public depositedCN;
mapping(address => uint) internal isBookedTokens;
event Commission(
address indexed stakedContractAddress,
address indexed stakerAddress,
uint indexed scIndex,
uint commissionAmount
);
constructor(address payable _walletAdd) public {
walletAddress = _walletAdd;
bookTime = 12 hours;
joiningFee = 2000000000000000; // 0.002 Ether
lockTokenTimeAfterCoverExp = 35 days;
scValidDays = 250;
lockCADays = 7 days;
lockMVDays = 2 days;
stakerCommissionPer = 20;
stakerMaxCommissionPer = 50;
tokenExponent = 4;
priceStep = 1000;
}
/**
* @dev Change the wallet address which receive Joining Fee
*/
function changeWalletAddress(address payable _address) external onlyInternal {
walletAddress = _address;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) {
codeVal = code;
if (code == "TOKEXP") {
val = tokenExponent;
} else if (code == "TOKSTEP") {
val = priceStep;
} else if (code == "RALOCKT") {
val = scValidDays;
} else if (code == "RACOMM") {
val = stakerCommissionPer;
} else if (code == "RAMAXC") {
val = stakerMaxCommissionPer;
} else if (code == "CABOOKT") {
val = bookTime / (1 hours);
} else if (code == "CALOCKT") {
val = lockCADays / (1 days);
} else if (code == "MVLOCKT") {
val = lockMVDays / (1 days);
} else if (code == "QUOLOCKT") {
val = lockTokenTimeAfterCoverExp / (1 days);
} else if (code == "JOINFEE") {
val = joiningFee;
}
}
/**
* @dev Just for interface
*/
function changeDependentContractAddress() public { //solhint-disable-line
}
/**
* @dev to get the contract staked by a staker
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return the address of staked contract
*/
function getStakerStakedContractByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (address stakedContractAddress)
{
stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
}
/**
* @dev to get the staker's staked burned
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return amount burned
*/
function getStakerStakedBurnedByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint burnedAmount)
{
burnedAmount = stakerStakedContracts[
_stakerAddress][_stakerIndex].burnedAmount;
}
/**
* @dev to get the staker's staked unlockable before the last burn
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return unlockable staked tokens
*/
function getStakerStakedUnlockableBeforeLastBurnByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint unlockable)
{
unlockable = stakerStakedContracts[
_stakerAddress][_stakerIndex].unLockableBeforeLastBurn;
}
/**
* @dev to get the staker's staked contract index
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return is the index of the smart contract address
*/
function getStakerStakedContractIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint scIndex)
{
scIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
}
/**
* @dev to get the staker index of the staked contract
* @param _stakedContractAddress is the address of the staked contract
* @param _stakedContractIndex is the index of staked contract
* @return is the index of the staker
*/
function getStakedContractStakerIndex(
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns (uint sIndex)
{
sIndex = stakedContractStakers[
_stakedContractAddress][_stakedContractIndex].stakerIndex;
}
/**
* @dev to get the staker's initial staked amount on the contract
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return staked amount
*/
function getStakerInitialStakedAmountOnContract(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint amount)
{
amount = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakeAmount;
}
/**
* @dev to get the staker's staked contract length
* @param _stakerAddress is the address of the staker
* @return length of staked contract
*/
function getStakerStakedContractLength(
address _stakerAddress
)
public
view
returns (uint length)
{
length = stakerStakedContracts[_stakerAddress].length;
}
/**
* @dev to get the staker's unlocked tokens which were staked
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return amount
*/
function getStakerUnlockedStakedTokens(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint amount)
{
amount = stakerStakedContracts[
_stakerAddress][_stakerIndex].unlockedAmount;
}
/**
* @dev pushes the unlocked staked tokens by a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker to distribute commission.
* @param _amount amount to be given as commission.
*/
function pushUnlockedStakedTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unlockedAmount = stakerStakedContracts[_stakerAddress][
_stakerIndex].unlockedAmount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/**
* @dev pushes the Burned tokens for a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be burned.
*/
function pushBurnedTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].burnedAmount = stakerStakedContracts[_stakerAddress][
_stakerIndex].burnedAmount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/**
* @dev pushes the unLockable tokens for a staker before last burn.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be added to unlockable.
*/
function pushUnlockableBeforeLastBurnTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn = stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/**
* @dev sets the unLockable tokens for a staker before last burn.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be added to unlockable.
*/
function setUnlockableBeforeLastBurnTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn = _amount;
}
/**
* @dev pushes the earned commission earned by a staker.
* @param _stakerAddress address of staker.
* @param _stakedContractAddress address of smart contract.
* @param _stakedContractIndex index of the staker to distribute commission.
* @param _commissionAmount amount to be given as commission.
*/
function pushEarnedStakeCommissions(
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex,
uint _commissionAmount
)
public
onlyInternal
{
stakedContractStakeCommission[_stakedContractAddress][_stakedContractIndex].
commissionEarned = stakedContractStakeCommission[_stakedContractAddress][
_stakedContractIndex].commissionEarned.add(_commissionAmount); //injected INTEGER OVERFLOW OR UNDERFLOW
emit Commission(
_stakerAddress,
_stakedContractAddress,
_stakedContractIndex,
_commissionAmount
);
}
/**
* @dev pushes the redeemed commission redeemed by a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker to distribute commission.
* @param _amount amount to be given as commission.
*/
function pushRedeemedStakeCommissions(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
uint stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
address stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
stakedContractStakeCommission[stakedContractAddress][stakedContractIndex].
commissionRedeemed = stakedContractStakeCommission[
stakedContractAddress][stakedContractIndex].commissionRedeemed.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/**
* @dev Gets stake commission given to an underwriter
* for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function getStakerEarnedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint)
{
return _getStakerEarnedStakeCommission(_stakerAddress, _stakerIndex);
}
/**
* @dev Gets stake commission redeemed by an underwriter
* for particular staked contract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
* @return commissionEarned total amount given to staker.
*/
function getStakerRedeemedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint)
{
return _getStakerRedeemedStakeCommission(_stakerAddress, _stakerIndex);
}
/**
* @dev Gets total stake commission given to an underwriter
* @param _stakerAddress address of staker.
* @return totalCommissionEarned total commission earned by staker.
*/
function getStakerTotalEarnedStakeCommission(
address _stakerAddress
)
public
view
returns (uint totalCommissionEarned)
{
totalCommissionEarned = 0;
for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) {
totalCommissionEarned = totalCommissionEarned.
add(_getStakerEarnedStakeCommission(_stakerAddress, i));
}
}
/**
* @dev Gets total stake commission given to an underwriter
* @param _stakerAddress address of staker.
* @return totalCommissionEarned total commission earned by staker.
*/
function getStakerTotalReedmedStakeCommission(
address _stakerAddress
)
public
view
returns(uint totalCommissionRedeemed)
{
totalCommissionRedeemed = 0;
for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) {
totalCommissionRedeemed = totalCommissionRedeemed.add(
_getStakerRedeemedStakeCommission(_stakerAddress, i));
}
}
/**
* @dev set flag to deposit/ undeposit cover note
* against a cover Id
* @param coverId coverId of Cover
* @param flag true/false for deposit/undeposit
*/
function setDepositCN(uint coverId, bool flag) public onlyInternal {
if (flag == true) {
require(!depositedCN[coverId].isDeposited, "Cover note already deposited");
}
depositedCN[coverId].isDeposited = flag;
}
/**
* @dev set locked cover note amount
* against a cover Id
* @param coverId coverId of Cover
* @param amount amount of nxm to be locked
*/
function setDepositCNAmount(uint coverId, uint amount) public onlyInternal {
depositedCN[coverId].amount = amount;
}
/**
* @dev to get the staker address on a staked contract
* @param _stakedContractAddress is the address of the staked contract in concern
* @param _stakedContractIndex is the index of staked contract's index
* @return address of staker
*/
function getStakedContractStakerByIndex(
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns (address stakerAddress)
{
stakerAddress = stakedContractStakers[
_stakedContractAddress][_stakedContractIndex].stakerAddress;
}
/**
* @dev to get the length of stakers on a staked contract
* @param _stakedContractAddress is the address of the staked contract in concern
* @return length in concern
*/
function getStakedContractStakersLength(
address _stakedContractAddress
)
public
view
returns (uint length)
{
length = stakedContractStakers[_stakedContractAddress].length;
}
/**
* @dev Adds a new stake record.
* @param _stakerAddress staker address.
* @param _stakedContractAddress smart contract address.
* @param _amount amountof NXM to be staked.
*/
function addStake(
address _stakerAddress,
address _stakedContractAddress,
uint _amount
)
public
onlyInternal
returns(uint scIndex)
{
scIndex = (stakedContractStakers[_stakedContractAddress].push(
Staker(_stakerAddress, stakerStakedContracts[_stakerAddress].length))).sub(1);
stakerStakedContracts[_stakerAddress].push(
Stake(_stakedContractAddress, scIndex, now, _amount, 0, 0, 0));
}
/**
* @dev books the user's tokens for maintaining Assessor Velocity,
* i.e. once a token is used to cast a vote as a Claims assessor,
* @param _of user's address.
*/
function bookCATokens(address _of) public onlyInternal {
require(!isCATokensBooked(_of), "Tokens already booked");
isBookedTokens[_of] = now.add(bookTime);
}
/**
* @dev to know if claim assessor's tokens are booked or not
* @param _of is the claim assessor's address in concern
* @return boolean representing the status of tokens booked
*/
function isCATokensBooked(address _of) public view returns(bool res) {
if (now < isBookedTokens[_of])
res = true;
}
/**
* @dev Sets the index which will receive commission.
* @param _stakedContractAddress smart contract address.
* @param _index current index.
*/
function setStakedContractCurrentCommissionIndex(
address _stakedContractAddress,
uint _index
)
public
onlyInternal
{
stakedContractCurrentCommissionIndex[_stakedContractAddress] = _index;
}
/**
* @dev Sets the last complete commission index
* @param _stakerAddress smart contract address.
* @param _index current index.
*/
function setLastCompletedStakeCommissionIndex(
address _stakerAddress,
uint _index
)
public
onlyInternal
{
lastCompletedStakeCommission[_stakerAddress] = _index;
}
/**
* @dev Sets the index till which commission is distrubuted.
* @param _stakedContractAddress smart contract address.
* @param _index current index.
*/
function setStakedContractCurrentBurnIndex(
address _stakedContractAddress,
uint _index
)
public
onlyInternal
{
stakedContractCurrentBurnIndex[_stakedContractAddress] = _index;
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "TOKEXP") {
_setTokenExponent(val);
} else if (code == "TOKSTEP") {
_setPriceStep(val);
} else if (code == "RALOCKT") {
_changeSCValidDays(val);
} else if (code == "RACOMM") {
_setStakerCommissionPer(val);
} else if (code == "RAMAXC") {
_setStakerMaxCommissionPer(val);
} else if (code == "CABOOKT") {
_changeBookTime(val * 1 hours);
} else if (code == "CALOCKT") {
_changelockCADays(val * 1 days);
} else if (code == "MVLOCKT") {
_changelockMVDays(val * 1 days);
} else if (code == "QUOLOCKT") {
_setLockTokenTimeAfterCoverExp(val * 1 days);
} else if (code == "JOINFEE") {
_setJoiningFee(val);
} else {
revert("Invalid param code");
}
}
/**
* @dev Internal function to get stake commission given to an
* underwriter for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function _getStakerEarnedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
internal
view
returns (uint amount)
{
uint _stakedContractIndex;
address _stakedContractAddress;
_stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
_stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
amount = stakedContractStakeCommission[
_stakedContractAddress][_stakedContractIndex].commissionEarned;
}
/**
* @dev Internal function to get stake commission redeemed by an
* underwriter for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function _getStakerRedeemedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
internal
view
returns (uint amount)
{
uint _stakedContractIndex;
address _stakedContractAddress;
_stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
_stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
amount = stakedContractStakeCommission[
_stakedContractAddress][_stakedContractIndex].commissionRedeemed;
}
/**
* @dev to set the percentage of staker commission
* @param _val is new percentage value
*/
function _setStakerCommissionPer(uint _val) internal {
stakerCommissionPer = _val;
}
/**
* @dev to set the max percentage of staker commission
* @param _val is new percentage value
*/
function _setStakerMaxCommissionPer(uint _val) internal {
stakerMaxCommissionPer = _val;
}
/**
* @dev to set the token exponent value
* @param _val is new value
*/
function _setTokenExponent(uint _val) internal {
tokenExponent = _val;
}
/**
* @dev to set the price step
* @param _val is new value
*/
function _setPriceStep(uint _val) internal {
priceStep = _val;
}
/**
* @dev Changes number of days for which NXM needs to staked in case of underwriting
*/
function _changeSCValidDays(uint _days) internal {
scValidDays = _days;
}
/**
* @dev Changes the time period up to which tokens will be locked.
* Used to generate the validity period of tokens booked by
* a user for participating in claim's assessment/claim's voting.
*/
function _changeBookTime(uint _time) internal {
bookTime = _time;
}
/**
* @dev Changes lock CA days - number of days for which tokens
* are locked while submitting a vote.
*/
function _changelockCADays(uint _val) internal {
lockCADays = _val;
}
/**
* @dev Changes lock MV days - number of days for which tokens are locked
* while submitting a vote.
*/
function _changelockMVDays(uint _val) internal {
lockMVDays = _val;
}
/**
* @dev Changes extra lock period for a cover, post its expiry.
*/
function _setLockTokenTimeAfterCoverExp(uint time) internal {
lockTokenTimeAfterCoverExp = time;
}
/**
* @dev Set the joining fee for membership
*/
function _setJoiningFee(uint _amount) internal {
joiningFee = _amount;
}
}
// File: nexusmutual-contracts/contracts/external/oraclize/ethereum-api/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.
*/
pragma solidity >= 0.5.0 < 0.6.0; // Incompatible compiler version - please select a compiler within the stated pragma range, or use a different version of the oraclizeAPI!
// Dummy contract only used to emit to end-user they are using wrong solc
contract solcChecker {
/* INCOMPATIBLE SOLC: import the following instead: "github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol" */ function f(bytes calldata x) external;
}
contract OraclizeI {
address public cbAddress;
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function getPrice(string memory _datasource) public returns (uint _dsprice);
function randomDS_getSessionPubKeyHash() external view returns (bytes32 _sessionKeyHash);
function getPrice(string memory _datasource, uint _gasLimit) public returns (uint _dsprice);
function queryN(uint _timestamp, string memory _datasource, bytes memory _argN) public payable returns (bytes32 _id);
function query(uint _timestamp, string calldata _datasource, string calldata _arg) external payable returns (bytes32 _id);
function query2(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) public payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg, uint _gasLimit) external payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string calldata _datasource, bytes calldata _argN, uint _gasLimit) external payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg1, string calldata _arg2, uint _gasLimit) external payable returns (bytes32 _id);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _address);
}
/*
Begin solidity-cborutils
https://github.com/smartcontractkit/solidity-cborutils
MIT License
Copyright (c) 2018 SmartContract ChainLink, 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.
*/
library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory _buf, uint _capacity) internal pure {
uint capacity = _capacity;
if (capacity % 32 != 0) {
capacity += 32 - (capacity % 32);
}
_buf.capacity = capacity; // Allocate space for the buffer data
assembly {
let ptr := mload(0x40)
mstore(_buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory _buf, uint _capacity) private pure {
bytes memory oldbuf = _buf.buf;
init(_buf, _capacity);
append(_buf, oldbuf);
}
function max(uint _a, uint _b) private pure returns (uint _max) {
if (_a > _b) {
return _a;
}
return _b;
}
/**
* @dev Appends a byte array to the end of the buffer. Resizes if doing so
* would exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
* @return The original buffer.
*
*/
function append(buffer memory _buf, bytes memory _data) internal pure returns (buffer memory _buffer) {
if (_data.length + _buf.buf.length > _buf.capacity) {
resize(_buf, max(_buf.capacity, _data.length) * 2);
}
uint dest;
uint src;
uint len = _data.length;
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
dest := add(add(bufptr, buflen), 32) // Start address = buffer address + buffer length + sizeof(buffer length)
mstore(bufptr, add(buflen, mload(_data))) // Update buffer length
src := add(_data, 32)
}
for(; len >= 32; len -= 32) { // Copy word-length chunks while possible
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint mask = 256 ** (32 - len) - 1; // Copy remaining bytes
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return _buf;
}
/**
*
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
* @return The original buffer.
*
*/
function append(buffer memory _buf, uint8 _data) internal pure {
if (_buf.buf.length + 1 > _buf.capacity) {
resize(_buf, _buf.capacity * 2);
}
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
let dest := add(add(bufptr, buflen), 32) // Address = buffer address + buffer length + sizeof(buffer length)
mstore8(dest, _data)
mstore(bufptr, add(buflen, 1)) // Update buffer length
}
}
/**
*
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
* @return The original buffer.
*
*/
function appendInt(buffer memory _buf, uint _data, uint _len) internal pure returns (buffer memory _buffer) {
if (_len + _buf.buf.length > _buf.capacity) {
resize(_buf, max(_buf.capacity, _len) * 2);
}
uint mask = 256 ** _len - 1;
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
let dest := add(add(bufptr, buflen), _len) // Address = buffer address + buffer length + sizeof(buffer length) + len
mstore(dest, or(and(mload(dest), not(mask)), _data))
mstore(bufptr, add(buflen, _len)) // Update buffer length
}
return _buf;
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function encodeType(Buffer.buffer memory _buf, uint8 _major, uint _value) private pure {
if (_value <= 23) {
_buf.append(uint8((_major << 5) | _value));
} else if (_value <= 0xFF) {
_buf.append(uint8((_major << 5) | 24));
_buf.appendInt(_value, 1);
} else if (_value <= 0xFFFF) {
_buf.append(uint8((_major << 5) | 25));
_buf.appendInt(_value, 2);
} else if (_value <= 0xFFFFFFFF) {
_buf.append(uint8((_major << 5) | 26));
_buf.appendInt(_value, 4);
} else if (_value <= 0xFFFFFFFFFFFFFFFF) {
_buf.append(uint8((_major << 5) | 27));
_buf.appendInt(_value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory _buf, uint8 _major) private pure {
_buf.append(uint8((_major << 5) | 31));
}
function encodeUInt(Buffer.buffer memory _buf, uint _value) internal pure {
encodeType(_buf, MAJOR_TYPE_INT, _value);
}
function encodeInt(Buffer.buffer memory _buf, int _value) internal pure {
if (_value >= 0) {
encodeType(_buf, MAJOR_TYPE_INT, uint(_value));
} else {
encodeType(_buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - _value));
}
}
function encodeBytes(Buffer.buffer memory _buf, bytes memory _value) internal pure {
encodeType(_buf, MAJOR_TYPE_BYTES, _value.length);
_buf.append(_value);
}
function encodeString(Buffer.buffer memory _buf, string memory _value) internal pure {
encodeType(_buf, MAJOR_TYPE_STRING, bytes(_value).length);
_buf.append(bytes(_value));
}
function startArray(Buffer.buffer memory _buf) internal pure {
encodeIndefiniteLengthType(_buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory _buf) internal pure {
encodeIndefiniteLengthType(_buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory _buf) internal pure {
encodeIndefiniteLengthType(_buf, MAJOR_TYPE_CONTENT_FREE);
}
}
/*
End solidity-cborutils
*/
contract usingOraclize {
using CBOR for Buffer.buffer;
OraclizeI oraclize;
OraclizeAddrResolverI OAR;
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_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
byte constant proofType_Android = 0x40;
byte constant proofType_TLSNotary = 0x10;
string oraclize_network_name;
uint8 constant networkID_auto = 0;
uint8 constant networkID_morden = 2;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_consensys = 161;
mapping(bytes32 => bytes32) oraclize_randomDS_args;
mapping(bytes32 => bool) oraclize_randomDS_sessionKeysHashVerified;
modifier oraclizeAPI {
if ((address(OAR) == address(0)) || (getCodeSize(address(OAR)) == 0)) {
oraclize_setNetwork(networkID_auto);
}
if (address(oraclize) != OAR.getAddress()) {
oraclize = OraclizeI(OAR.getAddress());
}
_;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string memory _result, bytes memory _proof) {
// RandomDS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1)
require((_proof[0] == "L") && (_proof[1] == "P") && (uint8(_proof[2]) == uint8(1)));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_setNetwork(uint8 _networkID) internal returns (bool _networkSet) {
return oraclize_setNetwork();
_networkID; // silence the warning and remain backwards compatible
}
function oraclize_setNetworkName(string memory _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string memory _networkName) {
return oraclize_network_name;
}
function oraclize_setNetwork() internal returns (bool _networkSet) {
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(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41) > 0) { //goerli testnet
OAR = OraclizeAddrResolverI(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41);
oraclize_setNetworkName("eth_goerli");
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 memory _result) public {
__callback(_myid, _result, new bytes(0));
}
function __callback(bytes32 _myid, string memory _result, bytes memory _proof) public {
return;
_myid; _result; _proof; // Silence compiler warnings
}
function oraclize_getPrice(string memory _datasource) oraclizeAPI internal returns (uint _queryPrice) {
return oraclize.getPrice(_datasource);
}
function oraclize_getPrice(string memory _datasource, uint _gasLimit) oraclizeAPI internal returns (uint _queryPrice) {
return oraclize.getPrice(_datasource, _gasLimit);
}
function oraclize_query(string memory _datasource, string memory _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 memory _datasource, string memory _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 memory _datasource, string memory _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 memory _datasource, string memory _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 memory _datasource, string memory _arg1, string memory _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 memory _datasource, string memory _arg1, string memory _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 memory _datasource, string memory _arg1, string memory _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 memory _datasource, string memory _arg1, string memory _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 memory _datasource, string[] memory _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 memory _datasource, string[] memory _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 memory _datasource, string[] memory _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 memory _datasource, string[] memory _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 memory _datasource, string[1] memory _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 memory _datasource, string[1] memory _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 memory _datasource, string[1] memory _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 memory _datasource, string[1] memory _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 memory _datasource, string[2] memory _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 memory _datasource, string[2] memory _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 memory _datasource, string[2] memory _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 memory _datasource, string[2] memory _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 memory _datasource, string[3] memory _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 memory _datasource, string[3] memory _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 memory _datasource, string[3] memory _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 memory _datasource, string[3] memory _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 memory _datasource, string[4] memory _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 memory _datasource, string[4] memory _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 memory _datasource, string[4] memory _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 memory _datasource, string[4] memory _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 memory _datasource, string[5] memory _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 memory _datasource, string[5] memory _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 memory _datasource, string[5] memory _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 memory _datasource, string[5] memory _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 memory _datasource, bytes[] memory _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 memory _datasource, bytes[] memory _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 memory _datasource, bytes[] memory _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 memory _datasource, bytes[] memory _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 memory _datasource, bytes[1] memory _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 memory _datasource, bytes[1] memory _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 memory _datasource, bytes[1] memory _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 memory _datasource, bytes[1] memory _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 memory _datasource, bytes[2] memory _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 memory _datasource, bytes[2] memory _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 memory _datasource, bytes[2] memory _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 memory _datasource, bytes[2] memory _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 memory _datasource, bytes[3] memory _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 memory _datasource, bytes[3] memory _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 memory _datasource, bytes[3] memory _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 memory _datasource, bytes[3] memory _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 memory _datasource, bytes[4] memory _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 memory _datasource, bytes[4] memory _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 memory _datasource, bytes[4] memory _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 memory _datasource, bytes[4] memory _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 memory _datasource, bytes[5] memory _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 memory _datasource, bytes[5] memory _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 memory _datasource, bytes[5] memory _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 memory _datasource, bytes[5] memory _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_setProof(byte _proofP) oraclizeAPI internal {
return oraclize.setProofType(_proofP);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address _callbackAddress) {
return oraclize.cbAddress();
}
function getCodeSize(address _addr) view internal returns (uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function oraclize_setCustomGasPrice(uint _gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(_gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32 _sessionKeyHash) {
return oraclize.randomDS_getSessionPubKeyHash();
}
function parseAddr(string memory _a) internal pure returns (address _parsedAddress) {
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(uint8(tmp[i]));
b2 = uint160(uint8(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 memory _a, string memory _b) internal pure returns (int _returnCode) {
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 memory _haystack, string memory _needle) internal pure returns (int _returnCode) {
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 memory _a, string memory _b) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, "", "", "");
}
function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory _concatenatedString) {
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;
uint i = 0;
for (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 safeParseInt(string memory _a) internal pure returns (uint _parsedInt) {
return safeParseInt(_a, 0);
}
function safeParseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i = 0; i < bresult.length; i++) {
if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) {
if (decimals) {
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(uint8(bresult[i])) - 48;
} else if (uint(uint8(bresult[i])) == 46) {
require(!decimals, 'More than one decimal encountered in string!');
decimals = true;
} else {
revert("Non-numeral character encountered in string!");
}
}
if (_b > 0) {
mint *= 10 ** _b;
}
return mint;
}
function parseInt(string memory _a) internal pure returns (uint _parsedInt) {
return parseInt(_a, 0);
}
function parseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i = 0; i < bresult.length; i++) {
if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) {
if (decimals) {
if (_b == 0) {
break;
} else {
_b--;
}
}
mint *= 10;
mint += uint(uint8(bresult[i])) - 48;
} else if (uint(uint8(bresult[i])) == 46) {
decimals = true;
}
}
if (_b > 0) {
mint *= 10 ** _b;
}
return mint;
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] memory _arr) internal pure returns (bytes memory _cborEncoding) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < _arr.length; i++) {
buf.encodeString(_arr[i]);
}
buf.endSequence();
return buf.buf;
}
function ba2cbor(bytes[] memory _arr) internal pure returns (bytes memory _cborEncoding) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < _arr.length; i++) {
buf.encodeBytes(_arr[i]);
}
buf.endSequence();
return buf.buf;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32 _queryId) {
require((_nbytes > 0) && (_nbytes <= 32));
_delay *= 10; // Convert from seconds to ledger timer ticks
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(uint8(_nbytes));
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
/*
The following variables can be relaxed.
Check the relaxed random contract at https://github.com/oraclize/ethereum-examples
for an idea on how to override and replace commit hash variables.
*/
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(abi.encodePacked(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;
}
function verifySig(bytes32 _tosignh, bytes memory _dersig, bytes memory _pubkey) internal returns (bool _sigVerified) {
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4 + (uint(uint8(_dersig[3])) - 0x20);
sigr_ = copyBytes(_dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(_dersig, offset + (uint(uint8(_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(uint160(uint256(keccak256(_pubkey)))) == signer) {
return true;
} else {
(sigok, signer) = safer_ecrecover(_tosignh, 28, sigr, sigs);
return (address(uint160(uint256(keccak256(_pubkey)))) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes memory _proof, uint _sig2offset) internal returns (bool _proofVerified) {
bool sigok;
// Random DS Proof Step 6: Verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(uint8(_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(uint8(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) {
return false;
}
// Random DS Proof 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(uint8(_proof[3 + 65 + 1])) + 2);
copyBytes(_proof, 3 + 65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string memory _result, bytes memory _proof) internal returns (uint8 _returnCode) {
// Random DS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L") || (_proof[1] != "P") || (uint8(_proof[2]) != uint8(1))) {
return 1;
}
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (!proofVerified) {
return 2;
}
return 0;
}
function matchBytes32Prefix(bytes32 _content, bytes memory _prefix, uint _nRandomBytes) internal pure returns (bool _matchesPrefix) {
bool match_ = true;
require(_prefix.length == _nRandomBytes);
for (uint256 i = 0; i< _nRandomBytes; i++) {
if (_content[i] != _prefix[i]) {
match_ = false;
}
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes memory _proof, bytes32 _queryId, bytes memory _result, string memory _contextName) internal returns (bool _proofVerified) {
// Random DS Proof Step 2: The unique keyhash has to match with the sha256 of (context name + _queryId)
uint ledgerProofLength = 3 + 65 + (uint(uint8(_proof[3 + 65 + 1])) + 2) + 32;
bytes memory keyhash = new bytes(32);
copyBytes(_proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(_contextName, _queryId)))))) {
return false;
}
bytes memory sig1 = new bytes(uint(uint8(_proof[ledgerProofLength + (32 + 8 + 1 + 32) + 1])) + 2);
copyBytes(_proof, ledgerProofLength + (32 + 8 + 1 + 32), sig1.length, sig1, 0);
// Random DS Proof 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(uint8(_proof[ledgerProofLength + 32 + 8])))) {
return false;
}
// Random DS Proof 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(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))) { //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[_queryId];
} else return false;
// Random DS Proof 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]) {
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 memory _from, uint _fromOffset, uint _length, bytes memory _to, uint _toOffset) internal pure returns (bytes memory _copiedBytes) {
uint minLength = _length + _toOffset;
require(_to.length >= minLength); // Buffer too small. Should be a better way?
uint i = 32 + _fromOffset; // NOTE: the offset 32 is added to skip the `size` field of both bytes variables
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 _success, address _recoveredAddress) {
/*
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)
ret := call(3000, 1, 0, size, 128, size, 32) // NOTE: we can reuse the request memory because we deal with the return code.
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 memory _sig) internal returns (bool _success, address _recoveredAddress) {
bytes32 r;
bytes32 s;
uint8 v;
if (_sig.length != 65) {
return (false, address(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, address(0));
}
return safer_ecrecover(_hash, v, r, s);
}
function safeMemoryCleaner() internal pure {
assembly {
let fmem := mload(0x40)
codecopy(fmem, codesize, sub(msize, fmem))
}
}
}
/*
END ORACLIZE_API
*/
// File: nexusmutual-contracts/contracts/Quotation.sol
/* Copyright (C) 2017 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity 0.5.7;
contract Quotation is Iupgradable {
using SafeMath for uint;
TokenFunctions internal tf;
TokenController internal tc;
TokenData internal td;
Pool1 internal p1;
PoolData internal pd;
QuotationData internal qd;
MCR internal m1;
MemberRoles internal mr;
bool internal locked;
event RefundEvent(address indexed user, bool indexed status, uint holdedCoverID, bytes32 reason);
modifier noReentrancy() {
require(!locked, "Reentrant call.");
locked = true;
_;
locked = false;
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
m1 = MCR(ms.getLatestAddress("MC"));
tf = TokenFunctions(ms.getLatestAddress("TF"));
tc = TokenController(ms.getLatestAddress("TC"));
td = TokenData(ms.getLatestAddress("TD"));
qd = QuotationData(ms.getLatestAddress("QD"));
p1 = Pool1(ms.getLatestAddress("P1"));
pd = PoolData(ms.getLatestAddress("PD"));
mr = MemberRoles(ms.getLatestAddress("MR"));
}
function sendEther() public payable {
}
/**
* @dev Expires a cover after a set period of time.
* Changes the status of the Cover and reduces the current
* sum assured of all areas in which the quotation lies
* Unlocks the CN tokens of the cover. Updates the Total Sum Assured value.
* @param _cid Cover Id.
*/
function expireCover(uint _cid) public {
require(checkCoverExpired(_cid) && qd.getCoverStatusNo(_cid) != uint(QuotationData.CoverStatus.CoverExpired));
tf.unlockCN(_cid);
bytes4 curr;
address scAddress;
uint sumAssured;
(, , scAddress, curr, sumAssured, ) = qd.getCoverDetailsByCoverID1(_cid);
if (qd.getCoverStatusNo(_cid) != uint(QuotationData.CoverStatus.ClaimAccepted))
_removeSAFromCSA(_cid, sumAssured);
qd.changeCoverStatusNo(_cid, uint8(QuotationData.CoverStatus.CoverExpired));
}
/**
* @dev Checks if a cover should get expired/closed or not.
* @param _cid Cover Index.
* @return expire true if the Cover's time has expired, false otherwise.
*/
function checkCoverExpired(uint _cid) public view returns(bool expire) {
expire = qd.getValidityOfCover(_cid) < uint64(now);
}
/**
* @dev Updates the Sum Assured Amount of all the quotation.
* @param _cid Cover id
* @param _amount that will get subtracted Current Sum Assured
* amount that comes under a quotation.
*/
function removeSAFromCSA(uint _cid, uint _amount) public onlyInternal {
_removeSAFromCSA(_cid, _amount);
}
/**
* @dev Makes Cover funded via NXM tokens.
* @param smartCAdd Smart Contract Address
*/
function makeCoverUsingNXMTokens(
uint[] memory coverDetails,
uint16 coverPeriod,
bytes4 coverCurr,
address smartCAdd,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
isMemberAndcheckPause
{
tc.burnFrom(msg.sender, coverDetails[2]); //need burn allowance
_verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s);
}
/**
* @dev Verifies cover details signed off chain.
* @param from address of funder.
* @param scAddress Smart Contract Address
*/
function verifyCoverDetails(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
onlyInternal
{
_verifyCoverDetails(
from,
scAddress,
coverCurr,
coverDetails,
coverPeriod,
_v,
_r,
_s
);
}
/**
* @dev Verifies signature.
* @param coverDetails details related to cover.
* @param coverPeriod validity of cover.
* @param smaratCA smarat contract address.
* @param _v argument from vrs hash.
* @param _r argument from vrs hash.
* @param _s argument from vrs hash.
*/
function verifySign(
uint[] memory coverDetails,
uint16 coverPeriod,
bytes4 curr,
address smaratCA,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
view
returns(bool)
{
require(smaratCA != address(0));
require(pd.capReached() == 1, "Can not buy cover until cap reached for 1st time");
bytes32 hash = getOrderHash(coverDetails, coverPeriod, curr, smaratCA);
return isValidSignature(hash, _v, _r, _s);
}
/**
* @dev Gets order hash for given cover details.
* @param coverDetails details realted to cover.
* @param coverPeriod validity of cover.
* @param smaratCA smarat contract address.
*/
function getOrderHash(
uint[] memory coverDetails,
uint16 coverPeriod,
bytes4 curr,
address smaratCA
)
public
view
returns(bytes32)
{
return keccak256(
abi.encodePacked(
coverDetails[0],
curr, coverPeriod,
smaratCA,
coverDetails[1],
coverDetails[2],
coverDetails[3],
coverDetails[4],
address(this)
)
);
}
/**
* @dev Verifies signature.
* @param hash order hash
* @param v argument from vrs hash.
* @param r argument from vrs hash.
* @param s argument from vrs hash.
*/
function isValidSignature(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public view returns(bool) {
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash));
address a = ecrecover(prefixedHash, v, r, s);
return (a == qd.getAuthQuoteEngine());
}
/**
* @dev to get the status of recently holded coverID
* @param userAdd is the user address in concern
* @return the status of the concerned coverId
*/
function getRecentHoldedCoverIdStatus(address userAdd) public view returns(int) {
uint holdedCoverLen = qd.getUserHoldedCoverLength(userAdd);
if (holdedCoverLen == 0) {
return -1;
} else {
uint holdedCoverID = qd.getUserHoldedCoverByIndex(userAdd, holdedCoverLen.sub(1));
return int(qd.holdedCoverIDStatus(holdedCoverID));
}
}
/**
* @dev to initiate the membership and the cover
* @param smartCAdd is the smart contract address to make cover on
* @param coverCurr is the currency used to make cover
* @param coverDetails list of details related to cover like cover amount, expire time, coverCurrPrice and priceNXM
* @param coverPeriod is cover period for which cover is being bought
* @param _v argument from vrs hash
* @param _r argument from vrs hash
* @param _s argument from vrs hash
*/
function initiateMembershipAndCover(
address smartCAdd,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
payable
checkPause
{
require(coverDetails[3] > now);
require(!qd.timestampRepeated(coverDetails[4]));
qd.setTimestampRepeated(coverDetails[4]);
require(!ms.isMember(msg.sender));
require(qd.refundEligible(msg.sender) == false);
uint joinFee = td.joiningFee();
uint totalFee = joinFee;
if (coverCurr == "ETH") {
totalFee = joinFee.add(coverDetails[1]);
} else {
IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr));
require(erc20.transferFrom(msg.sender, address(this), coverDetails[1]));
}
require(msg.value == totalFee);
require(verifySign(coverDetails, coverPeriod, coverCurr, smartCAdd, _v, _r, _s));
qd.addHoldCover(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod);
qd.setRefundEligible(msg.sender, true);
}
/**
* @dev to get the verdict of kyc process
* @param status is the kyc status
* @param _add is the address of member
*/
function kycVerdict(address _add, bool status) public checkPause noReentrancy {
require(msg.sender == qd.kycAuthAddress());
_kycTrigger(status, _add);
}
/**
* @dev transfering Ethers to newly created quotation contract.
*/
function transferAssetsToNewContract(address newAdd) public onlyInternal noReentrancy {
uint amount = address(this).balance;
IERC20 erc20;
if (amount > 0) {
// newAdd.transfer(amount);
Quotation newQT = Quotation(newAdd);
newQT.sendEther.value(amount)();
}
uint currAssetLen = pd.getAllCurrenciesLen();
for (uint64 i = 1; i < currAssetLen; i++) {
bytes4 currName = pd.getCurrenciesByIndex(i);
address currAddr = pd.getCurrencyAssetAddress(currName);
erc20 = IERC20(currAddr); //solhint-disable-line
if (erc20.balanceOf(address(this)) > 0) {
require(erc20.transfer(newAdd, erc20.balanceOf(address(this))));
}
}
}
/**
* @dev Creates cover of the quotation, changes the status of the quotation ,
* updates the total sum assured and locks the tokens of the cover against a quote.
* @param from Quote member Ethereum address.
*/
function _makeCover ( //solhint-disable-line
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod
)
internal
{
uint cid = qd.getCoverLength();
qd.addCover(coverPeriod, coverDetails[0],
from, coverCurr, scAddress, coverDetails[1], coverDetails[2]);
// if cover period of quote is less than 60 days.
if (coverPeriod <= 60) {
p1.closeCoverOraclise(cid, uint64(uint(coverPeriod).mul(1 days)));
}
uint coverNoteAmount = (coverDetails[2].mul(qd.tokensRetained())).div(100);
tc.mint(from, coverNoteAmount);
tf.lockCN(coverNoteAmount, coverPeriod, cid, from);
qd.addInTotalSumAssured(coverCurr, coverDetails[0]);
qd.addInTotalSumAssuredSC(scAddress, coverCurr, coverDetails[0]);
tf.pushStakerRewards(scAddress, coverDetails[2]);
}
/**
* @dev Makes a vover.
* @param from address of funder.
* @param scAddress Smart Contract Address
*/
function _verifyCoverDetails(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
)
internal
{
require(coverDetails[3] > now);
require(!qd.timestampRepeated(coverDetails[4]));
qd.setTimestampRepeated(coverDetails[4]);
require(verifySign(coverDetails, coverPeriod, coverCurr, scAddress, _v, _r, _s));
_makeCover(from, scAddress, coverCurr, coverDetails, coverPeriod);
}
/**
* @dev Updates the Sum Assured Amount of all the quotation.
* @param _cid Cover id
* @param _amount that will get subtracted Current Sum Assured
* amount that comes under a quotation.
*/
function _removeSAFromCSA(uint _cid, uint _amount) internal checkPause {
address _add;
bytes4 coverCurr;
(, , _add, coverCurr, , ) = qd.getCoverDetailsByCoverID1(_cid);
qd.subFromTotalSumAssured(coverCurr, _amount);
qd.subFromTotalSumAssuredSC(_add, coverCurr, _amount);
}
/**
* @dev to trigger the kyc process
* @param status is the kyc status
* @param _add is the address of member
*/
function _kycTrigger(bool status, address _add) internal {
uint holdedCoverLen = qd.getUserHoldedCoverLength(_add).sub(1);
uint holdedCoverID = qd.getUserHoldedCoverByIndex(_add, holdedCoverLen);
address payable userAdd;
address scAddress;
bytes4 coverCurr;
uint16 coverPeriod;
uint[] memory coverDetails = new uint[](4);
IERC20 erc20;
(, userAdd, coverDetails) = qd.getHoldedCoverDetailsByID2(holdedCoverID);
(, scAddress, coverCurr, coverPeriod) = qd.getHoldedCoverDetailsByID1(holdedCoverID);
require(qd.refundEligible(userAdd));
qd.setRefundEligible(userAdd, false);
require(qd.holdedCoverIDStatus(holdedCoverID) == uint(QuotationData.HCIDStatus.kycPending));
uint joinFee = td.joiningFee();
if (status) {
mr.payJoiningFee.value(joinFee)(userAdd);
if (coverDetails[3] > now) {
qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycPass));
address poolAdd = ms.getLatestAddress("P1");
if (coverCurr == "ETH") {
p1.sendEther.value(coverDetails[1])();
} else {
erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line
require(erc20.transfer(poolAdd, coverDetails[1]));
}
emit RefundEvent(userAdd, status, holdedCoverID, "KYC Passed");
_makeCover(userAdd, scAddress, coverCurr, coverDetails, coverPeriod);
} else {
qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycPassNoCover));
if (coverCurr == "ETH") {
userAdd.transfer(coverDetails[1]);
} else {
erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line
require(erc20.transfer(userAdd, coverDetails[1]));
}
emit RefundEvent(userAdd, status, holdedCoverID, "Cover Failed");
}
} else {
qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycFailedOrRefunded));
uint totalRefund = joinFee;
if (coverCurr == "ETH") {
totalRefund = coverDetails[1].add(joinFee);
} else {
erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line
require(erc20.transfer(userAdd, coverDetails[1]));
}
userAdd.transfer(totalRefund);
emit RefundEvent(userAdd, status, holdedCoverID, "KYC Failed");
}
}
}
// File: nexusmutual-contracts/contracts/external/uniswap/solidity-interface.sol
pragma solidity 0.5.7;
contract Factory {
function getExchange(address token) public view returns (address);
function getToken(address exchange) public view returns (address);
}
contract Exchange {
function getEthToTokenInputPrice(uint256 ethSold) public view returns(uint256);
function getTokenToEthInputPrice(uint256 tokensSold) public view returns(uint256);
function ethToTokenSwapInput(uint256 minTokens, uint256 deadline) public payable returns (uint256);
function ethToTokenTransferInput(uint256 minTokens, uint256 deadline, address recipient)
public payable returns (uint256);
function tokenToEthSwapInput(uint256 tokensSold, uint256 minEth, uint256 deadline)
public payable returns (uint256);
function tokenToEthTransferInput(uint256 tokensSold, uint256 minEth, uint256 deadline, address recipient)
public payable returns (uint256);
function tokenToTokenSwapInput(
uint256 tokensSold,
uint256 minTokensBought,
uint256 minEthBought,
uint256 deadline,
address tokenAddress
)
public returns (uint256);
function tokenToTokenTransferInput(
uint256 tokensSold,
uint256 minTokensBought,
uint256 minEthBought,
uint256 deadline,
address recipient,
address tokenAddress
)
public returns (uint256);
}
// File: nexusmutual-contracts/contracts/Pool2.sol
/* Copyright (C) 2017 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity 0.5.7;
contract Pool2 is Iupgradable {
using SafeMath for uint;
MCR internal m1;
Pool1 internal p1;
PoolData internal pd;
Factory internal factory;
address public uniswapFactoryAddress;
uint internal constant DECIMAL1E18 = uint(10) ** 18;
bool internal locked;
constructor(address _uniswapFactoryAdd) public {
uniswapFactoryAddress = _uniswapFactoryAdd;
factory = Factory(_uniswapFactoryAdd);
}
function() external payable {}
event Liquidity(bytes16 typeOf, bytes16 functionName);
event Rebalancing(bytes4 iaCurr, uint tokenAmount);
modifier noReentrancy() {
require(!locked, "Reentrant call.");
locked = true;
_;
locked = false;
}
/**
* @dev to change the uniswap factory address
* @param newFactoryAddress is the new factory address in concern
* @return the status of the concerned coverId
*/
function changeUniswapFactoryAddress(address newFactoryAddress) external onlyInternal {
// require(ms.isOwner(msg.sender) || ms.checkIsAuthToGoverned(msg.sender));
uniswapFactoryAddress = newFactoryAddress;
factory = Factory(uniswapFactoryAddress);
}
/**
* @dev On upgrade transfer all investment assets and ether to new Investment Pool
* @param newPoolAddress New Investment Assest Pool address
*/
function upgradeInvestmentPool(address payable newPoolAddress) external onlyInternal noReentrancy {
uint len = pd.getInvestmentCurrencyLen();
for (uint64 i = 1; i < len; i++) {
bytes4 iaName = pd.getInvestmentCurrencyByIndex(i);
_upgradeInvestmentPool(iaName, newPoolAddress);
}
if (address(this).balance > 0) {
Pool2 newP2 = Pool2(newPoolAddress);
newP2.sendEther.value(address(this).balance)();
}
}
/**
* @dev Internal Swap of assets between Capital
* and Investment Sub pool for excess or insufficient
* liquidity conditions of a given currency.
*/
function internalLiquiditySwap(bytes4 curr) external onlyInternal noReentrancy {
uint caBalance;
uint baseMin;
uint varMin;
(, baseMin, varMin) = pd.getCurrencyAssetVarBase(curr);
caBalance = _getCurrencyAssetsBalance(curr);
if (caBalance > uint(baseMin).add(varMin).mul(2)) {
_internalExcessLiquiditySwap(curr, baseMin, varMin, caBalance);
} else if (caBalance < uint(baseMin).add(varMin)) {
_internalInsufficientLiquiditySwap(curr, baseMin, varMin, caBalance);
}
}
/**
* @dev Saves a given investment asset details. To be called daily.
* @param curr array of Investment asset name.
* @param rate array of investment asset exchange rate.
* @param date current date in yyyymmdd.
*/
function saveIADetails(bytes4[] calldata curr, uint64[] calldata rate, uint64 date, bool bit)
external checkPause noReentrancy {
bytes4 maxCurr;
bytes4 minCurr;
uint64 maxRate;
uint64 minRate;
//ONLY NOTARZIE ADDRESS CAN POST
require(pd.isnotarise(msg.sender));
(maxCurr, maxRate, minCurr, minRate) = _calculateIARank(curr, rate);
pd.saveIARankDetails(maxCurr, maxRate, minCurr, minRate, date);
pd.updatelastDate(date);
uint len = curr.length;
for (uint i = 0; i < len; i++) {
pd.updateIAAvgRate(curr[i], rate[i]);
}
if (bit) //for testing purpose
_rebalancingLiquidityTrading(maxCurr, maxRate);
p1.saveIADetailsOracalise(pd.iaRatesTime());
}
/**
* @dev External Trade for excess or insufficient
* liquidity conditions of a given currency.
*/
function externalLiquidityTrade() external onlyInternal {
bool triggerTrade;
bytes4 curr;
bytes4 minIACurr;
bytes4 maxIACurr;
uint amount;
uint minIARate;
uint maxIARate;
uint baseMin;
uint varMin;
uint caBalance;
(maxIACurr, maxIARate, minIACurr, minIARate) = pd.getIARankDetailsByDate(pd.getLastDate());
uint len = pd.getAllCurrenciesLen();
for (uint64 i = 0; i < len; i++) {
curr = pd.getCurrenciesByIndex(i);
(, baseMin, varMin) = pd.getCurrencyAssetVarBase(curr);
caBalance = _getCurrencyAssetsBalance(curr);
if (caBalance > uint(baseMin).add(varMin).mul(2)) { //excess
amount = caBalance.sub(((uint(baseMin).add(varMin)).mul(3)).div(2)); //*10**18;
triggerTrade = _externalExcessLiquiditySwap(curr, minIACurr, amount);
} else if (caBalance < uint(baseMin).add(varMin)) { // insufficient
amount = (((uint(baseMin).add(varMin)).mul(3)).div(2)).sub(caBalance);
triggerTrade = _externalInsufficientLiquiditySwap(curr, maxIACurr, amount);
}
if (triggerTrade) {
p1.triggerExternalLiquidityTrade();
}
}
}
/**
* Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
m1 = MCR(ms.getLatestAddress("MC"));
pd = PoolData(ms.getLatestAddress("PD"));
p1 = Pool1(ms.getLatestAddress("P1"));
}
function sendEther() public payable {
}
/**
* @dev Gets currency asset balance for a given currency name.
*/
function _getCurrencyAssetsBalance(bytes4 _curr) public view returns(uint caBalance) {
if (_curr == "ETH") {
caBalance = address(p1).balance;
} else {
IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr));
caBalance = erc20.balanceOf(address(p1));
}
}
/**
* @dev Transfers ERC20 investment asset from this Pool to another Pool.
*/
function _transferInvestmentAsset(
bytes4 _curr,
address _transferTo,
uint _amount
)
internal
{
if (_curr == "ETH") {
if (_amount > address(this).balance)
_amount = address(this).balance;
p1.sendEther.value(_amount)();
} else {
IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr));
if (_amount > erc20.balanceOf(address(this)))
_amount = erc20.balanceOf(address(this));
require(erc20.transfer(_transferTo, _amount));
}
}
/**
* @dev to perform rebalancing
* @param iaCurr is the investment asset currency
* @param iaRate is the investment asset rate
*/
function _rebalancingLiquidityTrading(
bytes4 iaCurr,
uint64 iaRate
)
internal
checkPause
{
uint amountToSell;
uint totalRiskBal = pd.getLastVfull();
uint intermediaryEth;
uint ethVol = pd.ethVolumeLimit();
totalRiskBal = (totalRiskBal.mul(100000)).div(DECIMAL1E18);
Exchange exchange;
if (totalRiskBal > 0) {
amountToSell = ((totalRiskBal.mul(2).mul(
iaRate)).mul(pd.variationPercX100())).div(100 * 100 * 100000);
amountToSell = (amountToSell.mul(
10**uint(pd.getInvestmentAssetDecimals(iaCurr)))).div(100); // amount of asset to sell
if (iaCurr != "ETH" && _checkTradeConditions(iaCurr, iaRate, totalRiskBal)) {
exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(iaCurr)));
intermediaryEth = exchange.getTokenToEthInputPrice(amountToSell);
if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) {
intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100);
amountToSell = (exchange.getEthToTokenInputPrice(intermediaryEth).mul(995)).div(1000);
}
IERC20 erc20;
erc20 = IERC20(pd.getCurrencyAssetAddress(iaCurr));
erc20.approve(address(exchange), amountToSell);
exchange.tokenToEthSwapInput(amountToSell, (exchange.getTokenToEthInputPrice(
amountToSell).mul(995)).div(1000), pd.uniswapDeadline().add(now));
} else if (iaCurr == "ETH" && _checkTradeConditions(iaCurr, iaRate, totalRiskBal)) {
_transferInvestmentAsset(iaCurr, ms.getLatestAddress("P1"), amountToSell);
}
emit Rebalancing(iaCurr, amountToSell);
}
}
/**
* @dev Checks whether trading is required for a
* given investment asset at a given exchange rate.
*/
function _checkTradeConditions(
bytes4 curr,
uint64 iaRate,
uint totalRiskBal
)
internal
view
returns(bool check)
{
if (iaRate > 0) {
uint iaBalance = _getInvestmentAssetBalance(curr).div(DECIMAL1E18);
if (iaBalance > 0 && totalRiskBal > 0) {
uint iaMax;
uint iaMin;
uint checkNumber;
uint z;
(iaMin, iaMax) = pd.getInvestmentAssetHoldingPerc(curr);
z = pd.variationPercX100();
checkNumber = (iaBalance.mul(100 * 100000)).div(totalRiskBal.mul(iaRate));
if ((checkNumber > ((totalRiskBal.mul(iaMax.add(z))).mul(100000)).div(100)) ||
(checkNumber < ((totalRiskBal.mul(iaMin.sub(z))).mul(100000)).div(100)))
check = true; //eligibleIA
}
}
}
/**
* @dev Gets the investment asset rank.
*/
function _getIARank(
bytes4 curr,
uint64 rateX100,
uint totalRiskPoolBalance
)
internal
view
returns (int rhsh, int rhsl) //internal function
{
uint currentIAmaxHolding;
uint currentIAminHolding;
uint iaBalance = _getInvestmentAssetBalance(curr);
(currentIAminHolding, currentIAmaxHolding) = pd.getInvestmentAssetHoldingPerc(curr);
if (rateX100 > 0) {
uint rhsf;
rhsf = (iaBalance.mul(1000000)).div(totalRiskPoolBalance.mul(rateX100));
rhsh = int(rhsf - currentIAmaxHolding);
rhsl = int(rhsf - currentIAminHolding);
}
}
/**
* @dev Calculates the investment asset rank.
*/
function _calculateIARank(
bytes4[] memory curr,
uint64[] memory rate
)
internal
view
returns(
bytes4 maxCurr,
uint64 maxRate,
bytes4 minCurr,
uint64 minRate
)
{
int max = 0;
int min = -1;
int rhsh;
int rhsl;
uint totalRiskPoolBalance;
(totalRiskPoolBalance, ) = m1.calVtpAndMCRtp();
uint len = curr.length;
for (uint i = 0; i < len; i++) {
rhsl = 0;
rhsh = 0;
if (pd.getInvestmentAssetStatus(curr[i])) {
(rhsh, rhsl) = _getIARank(curr[i], rate[i], totalRiskPoolBalance);
if (rhsh > max || i == 0) {
max = rhsh;
maxCurr = curr[i];
maxRate = rate[i];
}
if (rhsl < min || rhsl == 0 || i == 0) {
min = rhsl;
minCurr = curr[i];
minRate = rate[i];
}
}
}
}
/**
* @dev to get balance of an investment asset
* @param _curr is the investment asset in concern
* @return the balance
*/
function _getInvestmentAssetBalance(bytes4 _curr) internal view returns (uint balance) {
if (_curr == "ETH") {
balance = address(this).balance;
} else {
IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr));
balance = erc20.balanceOf(address(this));
}
}
/**
* @dev Creates Excess liquidity trading order for a given currency and a given balance.
*/
function _internalExcessLiquiditySwap(bytes4 _curr, uint _baseMin, uint _varMin, uint _caBalance) internal {
// require(ms.isInternal(msg.sender) || md.isnotarise(msg.sender));
bytes4 minIACurr;
// uint amount;
(, , minIACurr, ) = pd.getIARankDetailsByDate(pd.getLastDate());
if (_curr == minIACurr) {
// amount = _caBalance.sub(((_baseMin.add(_varMin)).mul(3)).div(2)); //*10**18;
p1.transferCurrencyAsset(_curr, _caBalance.sub(((_baseMin.add(_varMin)).mul(3)).div(2)));
} else {
p1.triggerExternalLiquidityTrade();
}
}
/**
* @dev insufficient liquidity swap
* for a given currency and a given balance.
*/
function _internalInsufficientLiquiditySwap(bytes4 _curr, uint _baseMin, uint _varMin, uint _caBalance) internal {
bytes4 maxIACurr;
uint amount;
(maxIACurr, , , ) = pd.getIARankDetailsByDate(pd.getLastDate());
if (_curr == maxIACurr) {
amount = (((_baseMin.add(_varMin)).mul(3)).div(2)).sub(_caBalance);
_transferInvestmentAsset(_curr, ms.getLatestAddress("P1"), amount);
} else {
IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(maxIACurr));
if ((maxIACurr == "ETH" && address(this).balance > 0) ||
(maxIACurr != "ETH" && erc20.balanceOf(address(this)) > 0))
p1.triggerExternalLiquidityTrade();
}
}
/**
* @dev Creates External excess liquidity trading
* order for a given currency and a given balance.
* @param curr Currency Asset to Sell
* @param minIACurr Investment Asset to Buy
* @param amount Amount of Currency Asset to Sell
*/
function _externalExcessLiquiditySwap(
bytes4 curr,
bytes4 minIACurr,
uint256 amount
)
internal
returns (bool trigger)
{
uint intermediaryEth;
Exchange exchange;
IERC20 erc20;
uint ethVol = pd.ethVolumeLimit();
if (curr == minIACurr) {
p1.transferCurrencyAsset(curr, amount);
} else if (curr == "ETH" && minIACurr != "ETH") {
exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(minIACurr)));
if (amount > (address(exchange).balance.mul(ethVol)).div(100)) { // 4% ETH volume limit
amount = (address(exchange).balance.mul(ethVol)).div(100);
trigger = true;
}
p1.transferCurrencyAsset(curr, amount);
exchange.ethToTokenSwapInput.value(amount)
(exchange.getEthToTokenInputPrice(amount).mul(995).div(1000), pd.uniswapDeadline().add(now));
} else if (curr != "ETH" && minIACurr == "ETH") {
exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr)));
erc20 = IERC20(pd.getCurrencyAssetAddress(curr));
intermediaryEth = exchange.getTokenToEthInputPrice(amount);
if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) {
intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100);
amount = exchange.getEthToTokenInputPrice(intermediaryEth);
intermediaryEth = exchange.getTokenToEthInputPrice(amount);
trigger = true;
}
p1.transferCurrencyAsset(curr, amount);
// erc20.decreaseAllowance(address(exchange), erc20.allowance(address(this), address(exchange)));
erc20.approve(address(exchange), amount);
exchange.tokenToEthSwapInput(amount, (
intermediaryEth.mul(995)).div(1000), pd.uniswapDeadline().add(now));
} else {
exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr)));
intermediaryEth = exchange.getTokenToEthInputPrice(amount);
if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) {
intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100);
amount = exchange.getEthToTokenInputPrice(intermediaryEth);
trigger = true;
}
Exchange tmp = Exchange(factory.getExchange(
pd.getInvestmentAssetAddress(minIACurr))); // minIACurr exchange
if (intermediaryEth > address(tmp).balance.mul(ethVol).div(100)) {
intermediaryEth = address(tmp).balance.mul(ethVol).div(100);
amount = exchange.getEthToTokenInputPrice(intermediaryEth);
trigger = true;
}
p1.transferCurrencyAsset(curr, amount);
erc20 = IERC20(pd.getCurrencyAssetAddress(curr));
erc20.approve(address(exchange), amount);
exchange.tokenToTokenSwapInput(amount, (tmp.getEthToTokenInputPrice(
intermediaryEth).mul(995)).div(1000), (intermediaryEth.mul(995)).div(1000),
pd.uniswapDeadline().add(now), pd.getInvestmentAssetAddress(minIACurr));
}
}
/**
* @dev insufficient liquidity swap
* for a given currency and a given balance.
* @param curr Currency Asset to buy
* @param maxIACurr Investment Asset to sell
* @param amount Amount of Investment Asset to sell
*/
function _externalInsufficientLiquiditySwap(
bytes4 curr,
bytes4 maxIACurr,
uint256 amount
)
internal
returns (bool trigger)
{
Exchange exchange;
IERC20 erc20;
uint intermediaryEth;
// uint ethVol = pd.ethVolumeLimit();
if (curr == maxIACurr) {
_transferInvestmentAsset(curr, ms.getLatestAddress("P1"), amount);
} else if (curr == "ETH" && maxIACurr != "ETH") {
exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(maxIACurr)));
intermediaryEth = exchange.getEthToTokenInputPrice(amount);
if (amount > (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100)) {
amount = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100);
// amount = exchange.getEthToTokenInputPrice(intermediaryEth);
intermediaryEth = exchange.getEthToTokenInputPrice(amount);
trigger = true;
}
erc20 = IERC20(pd.getCurrencyAssetAddress(maxIACurr));
if (intermediaryEth > erc20.balanceOf(address(this))) {
intermediaryEth = erc20.balanceOf(address(this));
}
// erc20.decreaseAllowance(address(exchange), erc20.allowance(address(this), address(exchange)));
erc20.approve(address(exchange), intermediaryEth);
exchange.tokenToEthTransferInput(intermediaryEth, (
exchange.getTokenToEthInputPrice(intermediaryEth).mul(995)).div(1000),
pd.uniswapDeadline().add(now), address(p1));
} else if (curr != "ETH" && maxIACurr == "ETH") {
exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr)));
intermediaryEth = exchange.getTokenToEthInputPrice(amount);
if (intermediaryEth > address(this).balance)
intermediaryEth = address(this).balance;
if (intermediaryEth > (address(exchange).balance.mul
(pd.ethVolumeLimit())).div(100)) { // 4% ETH volume limit
intermediaryEth = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100);
trigger = true;
}
exchange.ethToTokenTransferInput.value(intermediaryEth)((exchange.getEthToTokenInputPrice(
intermediaryEth).mul(995)).div(1000), pd.uniswapDeadline().add(now), address(p1));
} else {
address currAdd = pd.getCurrencyAssetAddress(curr);
exchange = Exchange(factory.getExchange(currAdd));
intermediaryEth = exchange.getTokenToEthInputPrice(amount);
if (intermediaryEth > (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100)) {
intermediaryEth = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100);
trigger = true;
}
Exchange tmp = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(maxIACurr)));
if (intermediaryEth > address(tmp).balance.mul(pd.ethVolumeLimit()).div(100)) {
intermediaryEth = address(tmp).balance.mul(pd.ethVolumeLimit()).div(100);
// amount = exchange.getEthToTokenInputPrice(intermediaryEth);
trigger = true;
}
uint maxIAToSell = tmp.getEthToTokenInputPrice(intermediaryEth);
erc20 = IERC20(pd.getInvestmentAssetAddress(maxIACurr));
uint maxIABal = erc20.balanceOf(address(this));
if (maxIAToSell > maxIABal) {
maxIAToSell = maxIABal;
intermediaryEth = tmp.getTokenToEthInputPrice(maxIAToSell);
// amount = exchange.getEthToTokenInputPrice(intermediaryEth);
}
amount = exchange.getEthToTokenInputPrice(intermediaryEth);
erc20.approve(address(tmp), maxIAToSell);
tmp.tokenToTokenTransferInput(maxIAToSell, (
amount.mul(995)).div(1000), (
intermediaryEth), pd.uniswapDeadline().add(now), address(p1), currAdd);
}
}
/**
* @dev Transfers ERC20 investment asset from this Pool to another Pool.
*/
function _upgradeInvestmentPool(
bytes4 _curr,
address _newPoolAddress
)
internal
{
IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr));
if (erc20.balanceOf(address(this)) > 0)
require(erc20.transfer(_newPoolAddress, erc20.balanceOf(address(this))));
}
}
// File: nexusmutual-contracts/contracts/Pool1.sol
/* Copyright (C) 2017 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity 0.5.7;
contract Pool1 is usingOraclize, Iupgradable {
using SafeMath for uint;
Quotation internal q2;
NXMToken internal tk;
TokenController internal tc;
TokenFunctions internal tf;
Pool2 internal p2;
PoolData internal pd;
MCR internal m1;
Claims public c1;
TokenData internal td;
bool internal locked;
uint internal constant DECIMAL1E18 = uint(10) ** 18;
// uint internal constant PRICE_STEP = uint(1000) * DECIMAL1E18;
event Apiresult(address indexed sender, string msg, bytes32 myid);
event Payout(address indexed to, uint coverId, uint tokens);
modifier noReentrancy() {
require(!locked, "Reentrant call.");
locked = true;
_;
locked = false;
}
function () external payable {} //solhint-disable-line
/**
* @dev Pays out the sum assured in case a claim is accepted
* @param coverid Cover Id.
* @param claimid Claim Id.
* @return succ true if payout is successful, false otherwise.
*/
function sendClaimPayout(
uint coverid,
uint claimid,
uint sumAssured,
address payable coverHolder,
bytes4 coverCurr
)
external
onlyInternal
noReentrancy
returns(bool succ)
{
uint sa = sumAssured.div(DECIMAL1E18);
bool check;
IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr));
//Payout
if (coverCurr == "ETH" && address(this).balance >= sumAssured) {
// check = _transferCurrencyAsset(coverCurr, coverHolder, sumAssured);
coverHolder.transfer(sumAssured);
check = true;
} else if (coverCurr == "DAI" && erc20.balanceOf(address(this)) >= sumAssured) {
erc20.transfer(coverHolder, sumAssured);
check = true;
}
if (check == true) {
q2.removeSAFromCSA(coverid, sa);
pd.changeCurrencyAssetVarMin(coverCurr,
pd.getCurrencyAssetVarMin(coverCurr).sub(sumAssured));
emit Payout(coverHolder, coverid, sumAssured);
succ = true;
} else {
c1.setClaimStatus(claimid, 12);
}
_triggerExternalLiquidityTrade();
// p2.internalLiquiditySwap(coverCurr);
tf.burnStakerLockedToken(coverid, coverCurr, sumAssured);
}
/**
* @dev to trigger external liquidity trade
*/
function triggerExternalLiquidityTrade() external onlyInternal {
_triggerExternalLiquidityTrade();
}
///@dev Oraclize call to close emergency pause.
function closeEmergencyPause(uint time) external onlyInternal {
bytes32 myid = _oraclizeQuery(4, time, "URL", "", 300000);
_saveApiDetails(myid, "EP", 0);
}
/// @dev Calls the Oraclize Query to close a given Claim after a given period of time.
/// @param id Claim Id to be closed
/// @param time Time (in seconds) after which Claims assessment voting needs to be closed
function closeClaimsOraclise(uint id, uint time) external onlyInternal {
bytes32 myid = _oraclizeQuery(4, time, "URL", "", 3000000);
_saveApiDetails(myid, "CLA", id);
}
/// @dev Calls Oraclize Query to expire a given Cover after a given period of time.
/// @param id Quote Id to be expired
/// @param time Time (in seconds) after which the cover should be expired
function closeCoverOraclise(uint id, uint64 time) external onlyInternal {
bytes32 myid = _oraclizeQuery(4, time, "URL", strConcat(
"http://a1.nexusmutual.io/api/Claims/closeClaim_hash/", uint2str(id)), 1000000);
_saveApiDetails(myid, "COV", id);
}
/// @dev Calls the Oraclize Query to initiate MCR calculation.
/// @param time Time (in milliseconds) after which the next MCR calculation should be initiated
function mcrOraclise(uint time) external onlyInternal {
bytes32 myid = _oraclizeQuery(3, time, "URL", "https://api.nexusmutual.io/postMCR/M1", 0);
_saveApiDetails(myid, "MCR", 0);
}
/// @dev Calls the Oraclize Query in case MCR calculation fails.
/// @param time Time (in seconds) after which the next MCR calculation should be initiated
function mcrOracliseFail(uint id, uint time) external onlyInternal {
bytes32 myid = _oraclizeQuery(4, time, "URL", "", 1000000);
_saveApiDetails(myid, "MCRF", id);
}
/// @dev Oraclize call to update investment asset rates.
function saveIADetailsOracalise(uint time) external onlyInternal {
bytes32 myid = _oraclizeQuery(3, time, "URL", "https://api.nexusmutual.io/saveIADetails/M1", 0);
_saveApiDetails(myid, "IARB", 0);
}
/**
* @dev Transfers all assest (i.e ETH balance, Currency Assest) from old Pool to new Pool
* @param newPoolAddress Address of the new Pool
*/
function upgradeCapitalPool(address payable newPoolAddress) external noReentrancy onlyInternal {
for (uint64 i = 1; i < pd.getAllCurrenciesLen(); i++) {
bytes4 caName = pd.getCurrenciesByIndex(i);
_upgradeCapitalPool(caName, newPoolAddress);
}
if (address(this).balance > 0) {
Pool1 newP1 = Pool1(newPoolAddress);
newP1.sendEther.value(address(this).balance)();
}
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public {
m1 = MCR(ms.getLatestAddress("MC"));
tk = NXMToken(ms.tokenAddress());
tf = TokenFunctions(ms.getLatestAddress("TF"));
tc = TokenController(ms.getLatestAddress("TC"));
pd = PoolData(ms.getLatestAddress("PD"));
q2 = Quotation(ms.getLatestAddress("QT"));
p2 = Pool2(ms.getLatestAddress("P2"));
c1 = Claims(ms.getLatestAddress("CL"));
td = TokenData(ms.getLatestAddress("TD"));
}
function sendEther() public payable {
}
/**
* @dev transfers currency asset to an address
* @param curr is the currency of currency asset to transfer
* @param amount is amount of currency asset to transfer
* @return boolean to represent success or failure
*/
function transferCurrencyAsset(
bytes4 curr,
uint amount
)
public
onlyInternal
noReentrancy
returns(bool)
{
return _transferCurrencyAsset(curr, amount);
}
/// @dev Handles callback of external oracle query.
function __callback(bytes32 myid, string memory result) public {
result; //silence compiler warning
// owner will be removed from production build
ms.delegateCallBack(myid);
}
/// @dev Enables user to purchase cover with funding in ETH.
/// @param smartCAdd Smart Contract Address
function makeCoverBegin(
address smartCAdd,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
isMember
checkPause
payable
{
require(msg.value == coverDetails[1]);
q2.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s);
}
/**
* @dev Enables user to purchase cover via currency asset eg DAI
*/
function makeCoverUsingCA(
address smartCAdd,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
isMember
checkPause
{
IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr));
require(erc20.transferFrom(msg.sender, address(this), coverDetails[1]), "Transfer failed");
q2.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s);
}
/// @dev Enables user to purchase NXM at the current token price.
function buyToken() public payable isMember checkPause returns(bool success) {
require(msg.value > 0);
uint tokenPurchased = _getToken(address(this).balance, msg.value);
tc.mint(msg.sender, tokenPurchased);
success = true;
}
/// @dev Sends a given amount of Ether to a given address.
/// @param amount amount (in wei) to send.
/// @param _add Receiver's address.
/// @return succ True if transfer is a success, otherwise False.
function transferEther(uint amount, address payable _add) public noReentrancy checkPause returns(bool succ) {
require(ms.checkIsAuthToGoverned(msg.sender), "Not authorized to Govern");
succ = _add.send(amount);
}
/**
* @dev Allows selling of NXM for ether.
* Seller first needs to give this contract allowance to
* transfer/burn tokens in the NXMToken contract
* @param _amount Amount of NXM to sell
* @return success returns true on successfull sale
*/
function sellNXMTokens(uint _amount) public isMember noReentrancy checkPause returns(bool success) {
require(tk.balanceOf(msg.sender) >= _amount, "Not enough balance");
require(!tf.isLockedForMemberVote(msg.sender), "Member voted");
require(_amount <= m1.getMaxSellTokens(), "exceeds maximum token sell limit");
uint sellingPrice = _getWei(_amount);
tc.burnFrom(msg.sender, _amount);
msg.sender.transfer(sellingPrice);
success = true;
}
/**
* @dev gives the investment asset balance
* @return investment asset balance
*/
function getInvestmentAssetBalance() public view returns (uint balance) {
IERC20 erc20;
uint currTokens;
for (uint i = 1; i < pd.getInvestmentCurrencyLen(); i++) {
bytes4 currency = pd.getInvestmentCurrencyByIndex(i);
erc20 = IERC20(pd.getInvestmentAssetAddress(currency));
currTokens = erc20.balanceOf(address(p2));
if (pd.getIAAvgRate(currency) > 0)
balance = balance.add((currTokens.mul(100)).div(pd.getIAAvgRate(currency)));
}
balance = balance.add(address(p2).balance);
}
/**
* @dev Returns the amount of wei a seller will get for selling NXM
* @param amount Amount of NXM to sell
* @return weiToPay Amount of wei the seller will get
*/
function getWei(uint amount) public view returns(uint weiToPay) {
return _getWei(amount);
}
/**
* @dev Returns the amount of token a buyer will get for corresponding wei
* @param weiPaid Amount of wei
* @return tokenToGet Amount of tokens the buyer will get
*/
function getToken(uint weiPaid) public view returns(uint tokenToGet) {
return _getToken((address(this).balance).add(weiPaid), weiPaid);
}
/**
* @dev to trigger external liquidity trade
*/
function _triggerExternalLiquidityTrade() internal {
if (now > pd.lastLiquidityTradeTrigger().add(pd.liquidityTradeCallbackTime())) {
pd.setLastLiquidityTradeTrigger();
bytes32 myid = _oraclizeQuery(4, pd.liquidityTradeCallbackTime(), "URL", "", 300000);
_saveApiDetails(myid, "ULT", 0);
}
}
/**
* @dev Returns the amount of wei a seller will get for selling NXM
* @param _amount Amount of NXM to sell
* @return weiToPay Amount of wei the seller will get
*/
function _getWei(uint _amount) internal view returns(uint weiToPay) {
uint tokenPrice;
uint weiPaid;
uint tokenSupply = tk.totalSupply();
uint vtp;
uint mcrFullperc;
uint vFull;
uint mcrtp;
(mcrFullperc, , vFull, ) = pd.getLastMCR();
(vtp, ) = m1.calVtpAndMCRtp();
while (_amount > 0) {
mcrtp = (mcrFullperc.mul(vtp)).div(vFull);
tokenPrice = m1.calculateStepTokenPrice("ETH", mcrtp);
tokenPrice = (tokenPrice.mul(975)).div(1000); //97.5%
if (_amount <= td.priceStep().mul(DECIMAL1E18)) {
weiToPay = weiToPay.add((tokenPrice.mul(_amount)).div(DECIMAL1E18));
break;
} else {
_amount = _amount.sub(td.priceStep().mul(DECIMAL1E18));
tokenSupply = tokenSupply.sub(td.priceStep().mul(DECIMAL1E18));
weiPaid = (tokenPrice.mul(td.priceStep().mul(DECIMAL1E18))).div(DECIMAL1E18);
vtp = vtp.sub(weiPaid);
weiToPay = weiToPay.add(weiPaid);
}
}
}
/**
* @dev gives the token
* @param _poolBalance is the pool balance
* @param _weiPaid is the amount paid in wei
* @return the token to get
*/
function _getToken(uint _poolBalance, uint _weiPaid) internal view returns(uint tokenToGet) {
uint tokenPrice;
uint superWeiLeft = (_weiPaid).mul(DECIMAL1E18);
uint tempTokens;
uint superWeiSpent;
uint tokenSupply = tk.totalSupply();
uint vtp;
uint mcrFullperc;
uint vFull;
uint mcrtp;
(mcrFullperc, , vFull, ) = pd.getLastMCR();
(vtp, ) = m1.calculateVtpAndMCRtp((_poolBalance).sub(_weiPaid));
require(m1.calculateTokenPrice("ETH") > 0, "Token price can not be zero");
while (superWeiLeft > 0) {
mcrtp = (mcrFullperc.mul(vtp)).div(vFull);
tokenPrice = m1.calculateStepTokenPrice("ETH", mcrtp);
tempTokens = superWeiLeft.div(tokenPrice);
if (tempTokens <= td.priceStep().mul(DECIMAL1E18)) {
tokenToGet = tokenToGet.add(tempTokens);
break;
} else {
tokenToGet = tokenToGet.add(td.priceStep().mul(DECIMAL1E18));
tokenSupply = tokenSupply.add(td.priceStep().mul(DECIMAL1E18));
superWeiSpent = td.priceStep().mul(DECIMAL1E18).mul(tokenPrice);
superWeiLeft = superWeiLeft.sub(superWeiSpent);
vtp = vtp.add((td.priceStep().mul(DECIMAL1E18).mul(tokenPrice)).div(DECIMAL1E18));
}
}
}
/**
* @dev Save the details of the Oraclize API.
* @param myid Id return by the oraclize query.
* @param _typeof type of the query for which oraclize call is made.
* @param id ID of the proposal, quote, cover etc. for which oraclize call is made.
*/
function _saveApiDetails(bytes32 myid, bytes4 _typeof, uint id) internal {
pd.saveApiDetails(myid, _typeof, id);
pd.addInAllApiCall(myid);
}
/**
* @dev transfers currency asset
* @param _curr is currency of asset to transfer
* @param _amount is the amount to be transferred
* @return boolean representing the success of transfer
*/
function _transferCurrencyAsset(bytes4 _curr, uint _amount) internal returns(bool succ) {
if (_curr == "ETH") {
if (address(this).balance < _amount)
_amount = address(this).balance;
p2.sendEther.value(_amount)();
succ = true;
} else {
IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); //solhint-disable-line
if (erc20.balanceOf(address(this)) < _amount)
_amount = erc20.balanceOf(address(this));
require(erc20.transfer(address(p2), _amount));
succ = true;
}
}
/**
* @dev Transfers ERC20 Currency asset from this Pool to another Pool on upgrade.
*/
function _upgradeCapitalPool(
bytes4 _curr,
address _newPoolAddress
)
internal
{
IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr));
if (erc20.balanceOf(address(this)) > 0)
require(erc20.transfer(_newPoolAddress, erc20.balanceOf(address(this))));
}
/**
* @dev oraclize query
* @param paramCount is number of paramters passed
* @param timestamp is the current timestamp
* @param datasource in concern
* @param arg in concern
* @param gasLimit required for query
* @return id of oraclize query
*/
function _oraclizeQuery(
uint paramCount,
uint timestamp,
string memory datasource,
string memory arg,
uint gasLimit
)
internal
returns (bytes32 id)
{
if (paramCount == 4) {
id = oraclize_query(timestamp, datasource, arg, gasLimit);
} else if (paramCount == 3) {
id = oraclize_query(timestamp, datasource, arg);
} else {
id = oraclize_query(datasource, arg);
}
}
}
// File: nexusmutual-contracts/contracts/MCR.sol
/* Copyright (C) 2017 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity 0.5.7;
contract MCR is Iupgradable {
using SafeMath for uint;
Pool1 internal p1;
PoolData internal pd;
NXMToken internal tk;
QuotationData internal qd;
MemberRoles internal mr;
TokenData internal td;
ProposalCategory internal proposalCategory;
uint private constant DECIMAL1E18 = uint(10) ** 18;
uint private constant DECIMAL1E05 = uint(10) ** 5;
uint private constant DECIMAL1E19 = uint(10) ** 19;
uint private constant minCapFactor = uint(10) ** 21;
uint public variableMincap;
uint public dynamicMincapThresholdx100 = 13000;
uint public dynamicMincapIncrementx100 = 100;
event MCREvent(
uint indexed date,
uint blockNumber,
bytes4[] allCurr,
uint[] allCurrRates,
uint mcrEtherx100,
uint mcrPercx100,
uint vFull
);
/**
* @dev Adds new MCR data.
* @param mcrP Minimum Capital Requirement in percentage.
* @param vF Pool1 fund value in Ether used in the last full daily calculation of the Capital model.
* @param onlyDate Date(yyyymmdd) at which MCR details are getting added.
*/
function addMCRData(
uint mcrP,
uint mcrE,
uint vF,
bytes4[] calldata curr,
uint[] calldata _threeDayAvg,
uint64 onlyDate
)
external
checkPause
{
require(proposalCategory.constructorCheck());
require(pd.isnotarise(msg.sender));
if (mr.launched() && pd.capReached() != 1) {
if (mcrP >= 10000)
pd.setCapReached(1);
}
uint len = pd.getMCRDataLength();
_addMCRData(len, onlyDate, curr, mcrE, mcrP, vF, _threeDayAvg);
}
/**
* @dev Adds MCR Data for last failed attempt.
*/
function addLastMCRData(uint64 date) external checkPause onlyInternal {
uint64 lastdate = uint64(pd.getLastMCRDate());
uint64 failedDate = uint64(date);
if (failedDate >= lastdate) {
uint mcrP;
uint mcrE;
uint vF;
(mcrP, mcrE, vF, ) = pd.getLastMCR();
uint len = pd.getAllCurrenciesLen();
pd.pushMCRData(mcrP, mcrE, vF, date);
for (uint j = 0; j < len; j++) {
bytes4 currName = pd.getCurrenciesByIndex(j);
pd.updateCAAvgRate(currName, pd.getCAAvgRate(currName));
}
emit MCREvent(date, block.number, new bytes4[](0), new uint[](0), mcrE, mcrP, vF);
// Oraclize call for next MCR calculation
_callOracliseForMCR();
}
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
qd = QuotationData(ms.getLatestAddress("QD"));
p1 = Pool1(ms.getLatestAddress("P1"));
pd = PoolData(ms.getLatestAddress("PD"));
tk = NXMToken(ms.tokenAddress());
mr = MemberRoles(ms.getLatestAddress("MR"));
td = TokenData(ms.getLatestAddress("TD"));
proposalCategory = ProposalCategory(ms.getLatestAddress("PC"));
}
/**
* @dev Gets total sum assured(in ETH).
* @return amount of sum assured
*/
function getAllSumAssurance() public view returns(uint amount) {
uint len = pd.getAllCurrenciesLen();
for (uint i = 0; i < len; i++) {
bytes4 currName = pd.getCurrenciesByIndex(i);
if (currName == "ETH") {
amount = amount.add(qd.getTotalSumAssured(currName));
} else {
if (pd.getCAAvgRate(currName) > 0)
amount = amount.add((qd.getTotalSumAssured(currName).mul(100)).div(pd.getCAAvgRate(currName)));
}
}
}
/**
* @dev Calculates V(Tp) and MCR%(Tp), i.e, Pool Fund Value in Ether
* and MCR% used in the Token Price Calculation.
* @return vtp Pool Fund Value in Ether used for the Token Price Model
* @return mcrtp MCR% used in the Token Price Model.
*/
function _calVtpAndMCRtp(uint poolBalance) public view returns(uint vtp, uint mcrtp) {
vtp = 0;
IERC20 erc20;
uint currTokens = 0;
uint i;
for (i = 1; i < pd.getAllCurrenciesLen(); i++) {
bytes4 currency = pd.getCurrenciesByIndex(i);
erc20 = IERC20(pd.getCurrencyAssetAddress(currency));
currTokens = erc20.balanceOf(address(p1));
if (pd.getCAAvgRate(currency) > 0)
vtp = vtp.add((currTokens.mul(100)).div(pd.getCAAvgRate(currency)));
}
vtp = vtp.add(poolBalance).add(p1.getInvestmentAssetBalance());
uint mcrFullperc;
uint vFull;
(mcrFullperc, , vFull, ) = pd.getLastMCR();
if (vFull > 0) {
mcrtp = (mcrFullperc.mul(vtp)).div(vFull);
}
}
/**
* @dev Calculates the Token Price of NXM in a given currency.
* @param curr Currency name.
*/
function calculateStepTokenPrice(
bytes4 curr,
uint mcrtp
)
public
view
onlyInternal
returns(uint tokenPrice)
{
return _calculateTokenPrice(curr, mcrtp);
}
/**
* @dev Calculates the Token Price of NXM in a given currency
* with provided token supply for dynamic token price calculation
* @param curr Currency name.
*/
function calculateTokenPrice (bytes4 curr) public view returns(uint tokenPrice) {
uint mcrtp;
(, mcrtp) = _calVtpAndMCRtp(address(p1).balance);
return _calculateTokenPrice(curr, mcrtp);
}
function calVtpAndMCRtp() public view returns(uint vtp, uint mcrtp) {
return _calVtpAndMCRtp(address(p1).balance);
}
function calculateVtpAndMCRtp(uint poolBalance) public view returns(uint vtp, uint mcrtp) {
return _calVtpAndMCRtp(poolBalance);
}
function getThresholdValues(uint vtp, uint vF, uint totalSA, uint minCap) public view returns(uint lowerThreshold, uint upperThreshold)
{
minCap = (minCap.mul(minCapFactor)).add(variableMincap);
uint lower = 0;
if (vtp >= vF) {
upperThreshold = vtp.mul(120).mul(100).div((minCap)); //Max Threshold = [MAX(Vtp, Vfull) x 120] / mcrMinCap
} else {
upperThreshold = vF.mul(120).mul(100).div((minCap));
}
if (vtp > 0) {
lower = totalSA.mul(DECIMAL1E18).mul(pd.shockParameter()).div(100);
if(lower < minCap.mul(11).div(10))
lower = minCap.mul(11).div(10);
}
if (lower > 0) { //Min Threshold = [Vtp / MAX(TotalActiveSA x ShockParameter, mcrMinCap x 1.1)] x 100
lowerThreshold = vtp.mul(100).mul(100).div(lower);
}
}
/**
* @dev Gets max numbers of tokens that can be sold at the moment.
*/
function getMaxSellTokens() public view returns(uint maxTokens) {
uint baseMin = pd.getCurrencyAssetBaseMin("ETH");
uint maxTokensAccPoolBal;
if (address(p1).balance > baseMin.mul(50).div(100)) {
maxTokensAccPoolBal = address(p1).balance.sub(
(baseMin.mul(50)).div(100));
}
maxTokensAccPoolBal = (maxTokensAccPoolBal.mul(DECIMAL1E18)).div(
(calculateTokenPrice("ETH").mul(975)).div(1000));
uint lastMCRPerc = pd.getLastMCRPerc();
if (lastMCRPerc > 10000)
maxTokens = (((uint(lastMCRPerc).sub(10000)).mul(2000)).mul(DECIMAL1E18)).div(10000);
if (maxTokens > maxTokensAccPoolBal)
maxTokens = maxTokensAccPoolBal;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) {
codeVal = code;
if (code == "DMCT") {
val = dynamicMincapThresholdx100;
} else if (code == "DMCI") {
val = dynamicMincapIncrementx100;
}
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "DMCT") {
dynamicMincapThresholdx100 = val;
} else if (code == "DMCI") {
dynamicMincapIncrementx100 = val;
}
else {
revert("Invalid param code");
}
}
/**
* @dev Calls oraclize query to calculate MCR details after 24 hours.
*/
function _callOracliseForMCR() internal {
p1.mcrOraclise(pd.mcrTime());
}
/**
* @dev Calculates the Token Price of NXM in a given currency
* with provided token supply for dynamic token price calculation
* @param _curr Currency name.
* @return tokenPrice Token price.
*/
function _calculateTokenPrice(
bytes4 _curr,
uint mcrtp
)
internal
view
returns(uint tokenPrice)
{
uint getA;
uint getC;
uint getCAAvgRate;
uint tokenExponentValue = td.tokenExponent();
// uint max = (mcrtp.mul(mcrtp).mul(mcrtp).mul(mcrtp));
uint max = mcrtp ** tokenExponentValue;
uint dividingFactor = tokenExponentValue.mul(4);
(getA, getC, getCAAvgRate) = pd.getTokenPriceDetails(_curr);
uint mcrEth = pd.getLastMCREther();
getC = getC.mul(DECIMAL1E18);
tokenPrice = (mcrEth.mul(DECIMAL1E18).mul(max).div(getC)).div(10 ** dividingFactor);
tokenPrice = tokenPrice.add(getA.mul(DECIMAL1E18).div(DECIMAL1E05));
tokenPrice = tokenPrice.mul(getCAAvgRate * 10);
tokenPrice = (tokenPrice).div(10**3);
}
/**
* @dev Adds MCR Data. Checks if MCR is within valid
* thresholds in order to rule out any incorrect calculations
*/
function _addMCRData(
uint len,
uint64 newMCRDate,
bytes4[] memory curr,
uint mcrE,
uint mcrP,
uint vF,
uint[] memory _threeDayAvg
)
internal
{
uint vtp = 0;
uint lowerThreshold = 0;
uint upperThreshold = 0;
if (len > 1) {
(vtp, ) = _calVtpAndMCRtp(address(p1).balance);
(lowerThreshold, upperThreshold) = getThresholdValues(vtp, vF, getAllSumAssurance(), pd.minCap());
}
if(mcrP > dynamicMincapThresholdx100)
variableMincap = (variableMincap.mul(dynamicMincapIncrementx100.add(10000)).add(minCapFactor.mul(pd.minCap().mul(dynamicMincapIncrementx100)))).div(10000);
// Explanation for above formula :-
// actual formula -> variableMinCap = variableMinCap + (variableMinCap+minCap)*dynamicMincapIncrement/100
// Implemented formula is simplified form of actual formula.
// Let consider above formula as b = b + (a+b)*c/100
// here, dynamicMincapIncrement is in x100 format.
// so b+(a+b)*cx100/10000 can be written as => (10000.b + b.cx100 + a.cx100)/10000.
// It can further simplify to (b.(10000+cx100) + a.cx100)/10000.
if (len == 1 || (mcrP) >= lowerThreshold
&& (mcrP) <= upperThreshold) {
vtp = pd.getLastMCRDate(); // due to stack to deep error,we are reusing already declared variable
pd.pushMCRData(mcrP, mcrE, vF, newMCRDate);
for (uint i = 0; i < curr.length; i++) {
pd.updateCAAvgRate(curr[i], _threeDayAvg[i]);
}
emit MCREvent(newMCRDate, block.number, curr, _threeDayAvg, mcrE, mcrP, vF);
// Oraclize call for next MCR calculation
if (vtp < newMCRDate) {
_callOracliseForMCR();
}
} else {
p1.mcrOracliseFail(newMCRDate, pd.mcrFailTime());
}
}
}
// File: nexusmutual-contracts/contracts/Claims.sol
/* Copyright (C) 2017 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity 0.5.7;
contract Claims is Iupgradable {
using SafeMath for uint;
TokenFunctions internal tf;
NXMToken internal tk;
TokenController internal tc;
ClaimsReward internal cr;
Pool1 internal p1;
ClaimsData internal cd;
TokenData internal td;
PoolData internal pd;
Pool2 internal p2;
QuotationData internal qd;
MCR internal m1;
uint private constant DECIMAL1E18 = uint(10) ** 18;
/**
* @dev Sets the status of claim using claim id.
* @param claimId claim id.
* @param stat status to be set.
*/
function setClaimStatus(uint claimId, uint stat) external onlyInternal {
_setClaimStatus(claimId, stat);
}
/**
* @dev Gets claim details of claim id = pending claim start + given index
*/
function getClaimFromNewStart(
uint index
)
external
view
returns (
uint coverId,
uint claimId,
int8 voteCA,
int8 voteMV,
uint statusnumber
)
{
(coverId, claimId, voteCA, voteMV, statusnumber) = cd.getClaimFromNewStart(index, msg.sender);
// status = rewardStatus[statusnumber].claimStatusDesc;
}
/**
* @dev Gets details of a claim submitted by the calling user, at a given index
*/
function getUserClaimByIndex(
uint index
)
external
view
returns(
uint status,
uint coverId,
uint claimId
)
{
uint statusno;
(statusno, coverId, claimId) = cd.getUserClaimByIndex(index, msg.sender);
status = statusno;
}
/**
* @dev Gets details of a given claim id.
* @param _claimId Claim Id.
* @return status Current status of claim id
* @return finalVerdict Decision made on the claim, 1 -> acceptance, -1 -> denial
* @return claimOwner Address through which claim is submitted
* @return coverId Coverid associated with the claim id
*/
function getClaimbyIndex(uint _claimId) external view returns (
uint claimId,
uint status,
int8 finalVerdict,
address claimOwner,
uint coverId
)
{
uint stat;
claimId = _claimId;
(, coverId, finalVerdict, stat, , ) = cd.getClaim(_claimId);
claimOwner = qd.getCoverMemberAddress(coverId);
status = stat;
}
/**
* @dev Calculates total amount that has been used to assess a claim.
* Computaion:Adds acceptCA(tokens used for voting in favor of a claim)
* denyCA(tokens used for voting against a claim) * current token price.
* @param claimId Claim Id.
* @param member Member type 0 -> Claim Assessors, else members.
* @return tokens Total Amount used in Claims assessment.
*/
function getCATokens(uint claimId, uint member) external view returns(uint tokens) {
uint coverId;
(, coverId) = cd.getClaimCoverId(claimId);
bytes4 curr = qd.getCurrencyOfCover(coverId);
uint tokenx1e18 = m1.calculateTokenPrice(curr);
uint accept;
uint deny;
if (member == 0) {
(, accept, deny) = cd.getClaimsTokenCA(claimId);
} else {
(, accept, deny) = cd.getClaimsTokenMV(claimId);
}
tokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); // amount (not in tokens)
}
/**
* Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
tk = NXMToken(ms.tokenAddress());
td = TokenData(ms.getLatestAddress("TD"));
tf = TokenFunctions(ms.getLatestAddress("TF"));
tc = TokenController(ms.getLatestAddress("TC"));
p1 = Pool1(ms.getLatestAddress("P1"));
p2 = Pool2(ms.getLatestAddress("P2"));
pd = PoolData(ms.getLatestAddress("PD"));
cr = ClaimsReward(ms.getLatestAddress("CR"));
cd = ClaimsData(ms.getLatestAddress("CD"));
qd = QuotationData(ms.getLatestAddress("QD"));
m1 = MCR(ms.getLatestAddress("MC"));
}
/**
* @dev Updates the pending claim start variable,
* the lowest claim id with a pending decision/payout.
*/
function changePendingClaimStart() public onlyInternal {
uint origstat;
uint state12Count;
uint pendingClaimStart = cd.pendingClaimStart();
uint actualClaimLength = cd.actualClaimLength();
for (uint i = pendingClaimStart; i < actualClaimLength; i++) {
(, , , origstat, , state12Count) = cd.getClaim(i);
if (origstat > 5 && ((origstat != 12) || (origstat == 12 && state12Count >= 60)))
cd.setpendingClaimStart(i);
else
break;
}
}
/**
* @dev Submits a claim for a given cover note.
* Adds claim to queue incase of emergency pause else directly submits the claim.
* @param coverId Cover Id.
*/
function submitClaim(uint coverId) public {
address qadd = qd.getCoverMemberAddress(coverId);
require(qadd == msg.sender);
uint8 cStatus;
(, cStatus, , , ) = qd.getCoverDetailsByCoverID2(coverId);
require(cStatus != uint8(QuotationData.CoverStatus.ClaimSubmitted), "Claim already submitted");
require(cStatus != uint8(QuotationData.CoverStatus.CoverExpired), "Cover already expired");
if (ms.isPause() == false) {
_addClaim(coverId, now, qadd);
} else {
cd.setClaimAtEmergencyPause(coverId, now, false);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.Requested));
}
}
/**
* @dev Submits the Claims queued once the emergency pause is switched off.
*/
function submitClaimAfterEPOff() public onlyInternal {
uint lengthOfClaimSubmittedAtEP = cd.getLengthOfClaimSubmittedAtEP();
uint firstClaimIndexToSubmitAfterEP = cd.getFirstClaimIndexToSubmitAfterEP();
uint coverId;
uint dateUpd;
bool submit;
address qadd;
for (uint i = firstClaimIndexToSubmitAfterEP; i < lengthOfClaimSubmittedAtEP; i++) {
(coverId, dateUpd, submit) = cd.getClaimOfEmergencyPauseByIndex(i);
require(submit == false);
qadd = qd.getCoverMemberAddress(coverId);
_addClaim(coverId, dateUpd, qadd);
cd.setClaimSubmittedAtEPTrue(i, true);
}
cd.setFirstClaimIndexToSubmitAfterEP(lengthOfClaimSubmittedAtEP);
}
/**
* @dev Castes vote for members who have tokens locked under Claims Assessment
* @param claimId claim id.
* @param verdict 1 for Accept,-1 for Deny.
*/
function submitCAVote(uint claimId, int8 verdict) public isMemberAndcheckPause {
require(checkVoteClosing(claimId) != 1);
require(cd.userClaimVotePausedOn(msg.sender).add(cd.pauseDaysCA()) < now);
uint tokens = tc.tokensLockedAtTime(msg.sender, "CLA", now.add(cd.claimDepositTime()));
require(tokens > 0);
uint stat;
(, stat) = cd.getClaimStatusNumber(claimId);
require(stat == 0);
require(cd.getUserClaimVoteCA(msg.sender, claimId) == 0);
td.bookCATokens(msg.sender);
cd.addVote(msg.sender, tokens, claimId, verdict);
cd.callVoteEvent(msg.sender, claimId, "CAV", tokens, now, verdict);
uint voteLength = cd.getAllVoteLength();
cd.addClaimVoteCA(claimId, voteLength);
cd.setUserClaimVoteCA(msg.sender, claimId, voteLength);
cd.setClaimTokensCA(claimId, verdict, tokens);
tc.extendLockOf(msg.sender, "CLA", td.lockCADays());
int close = checkVoteClosing(claimId);
if (close == 1) {
cr.changeClaimStatus(claimId);
}
}
/**
* @dev Submits a member vote for assessing a claim.
* Tokens other than those locked under Claims
* Assessment can be used to cast a vote for a given claim id.
* @param claimId Selected claim id.
* @param verdict 1 for Accept,-1 for Deny.
*/
function submitMemberVote(uint claimId, int8 verdict) public isMemberAndcheckPause {
require(checkVoteClosing(claimId) != 1);
uint stat;
uint tokens = tc.totalBalanceOf(msg.sender);
(, stat) = cd.getClaimStatusNumber(claimId);
require(stat >= 1 && stat <= 5);
require(cd.getUserClaimVoteMember(msg.sender, claimId) == 0);
cd.addVote(msg.sender, tokens, claimId, verdict);
cd.callVoteEvent(msg.sender, claimId, "MV", tokens, now, verdict);
tc.lockForMemberVote(msg.sender, td.lockMVDays());
uint voteLength = cd.getAllVoteLength();
cd.addClaimVotemember(claimId, voteLength);
cd.setUserClaimVoteMember(msg.sender, claimId, voteLength);
cd.setClaimTokensMV(claimId, verdict, tokens);
int close = checkVoteClosing(claimId);
if (close == 1) {
cr.changeClaimStatus(claimId);
}
}
/**
* @dev Pause Voting of All Pending Claims when Emergency Pause Start.
*/
function pauseAllPendingClaimsVoting() public onlyInternal {
uint firstIndex = cd.pendingClaimStart();
uint actualClaimLength = cd.actualClaimLength();
for (uint i = firstIndex; i < actualClaimLength; i++) {
if (checkVoteClosing(i) == 0) {
uint dateUpd = cd.getClaimDateUpd(i);
cd.setPendingClaimDetails(i, (dateUpd.add(cd.maxVotingTime())).sub(now), false);
}
}
}
/**
* @dev Resume the voting phase of all Claims paused due to an emergency pause.
*/
function startAllPendingClaimsVoting() public onlyInternal {
uint firstIndx = cd.getFirstClaimIndexToStartVotingAfterEP();
uint i;
uint lengthOfClaimVotingPause = cd.getLengthOfClaimVotingPause();
for (i = firstIndx; i < lengthOfClaimVotingPause; i++) {
uint pendingTime;
uint claimID;
(claimID, pendingTime, ) = cd.getPendingClaimDetailsByIndex(i);
uint pTime = (now.sub(cd.maxVotingTime())).add(pendingTime);
cd.setClaimdateUpd(claimID, pTime);
cd.setPendingClaimVoteStatus(i, true);
uint coverid;
(, coverid) = cd.getClaimCoverId(claimID);
address qadd = qd.getCoverMemberAddress(coverid);
tf.extendCNEPOff(qadd, coverid, pendingTime.add(cd.claimDepositTime()));
p1.closeClaimsOraclise(claimID, uint64(pTime));
}
cd.setFirstClaimIndexToStartVotingAfterEP(i);
}
/**
* @dev Checks if voting of a claim should be closed or not.
* @param claimId Claim Id.
* @return close 1 -> voting should be closed, 0 -> if voting should not be closed,
* -1 -> voting has already been closed.
*/
function checkVoteClosing(uint claimId) public view returns(int8 close) {
close = 0;
uint status;
(, status) = cd.getClaimStatusNumber(claimId);
uint dateUpd = cd.getClaimDateUpd(claimId);
if (status == 12 && dateUpd.add(cd.payoutRetryTime()) < now) {
if (cd.getClaimState12Count(claimId) < 60)
close = 1;
}
if (status > 5 && status != 12) {
close = -1;
} else if (status != 12 && dateUpd.add(cd.maxVotingTime()) <= now) {
close = 1;
} else if (status != 12 && dateUpd.add(cd.minVotingTime()) >= now) {
close = 0;
} else if (status == 0 || (status >= 1 && status <= 5)) {
close = _checkVoteClosingFinal(claimId, status);
}
}
/**
* @dev Checks if voting of a claim should be closed or not.
* Internally called by checkVoteClosing method
* for Claims whose status number is 0 or status number lie between 2 and 6.
* @param claimId Claim Id.
* @param status Current status of claim.
* @return close 1 if voting should be closed,0 in case voting should not be closed,
* -1 if voting has already been closed.
*/
function _checkVoteClosingFinal(uint claimId, uint status) internal view returns(int8 close) {
close = 0;
uint coverId;
(, coverId) = cd.getClaimCoverId(claimId);
bytes4 curr = qd.getCurrencyOfCover(coverId);
uint tokenx1e18 = m1.calculateTokenPrice(curr);
uint accept;
uint deny;
(, accept, deny) = cd.getClaimsTokenCA(claimId);
uint caTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18);
(, accept, deny) = cd.getClaimsTokenMV(claimId);
uint mvTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18);
uint sumassured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18);
if (status == 0 && caTokens >= sumassured.mul(10)) {
close = 1;
} else if (status >= 1 && status <= 5 && mvTokens >= sumassured.mul(10)) {
close = 1;
}
}
/**
* @dev Changes the status of an existing claim id, based on current
* status and current conditions of the system
* @param claimId Claim Id.
* @param stat status number.
*/
function _setClaimStatus(uint claimId, uint stat) internal {
uint origstat;
uint state12Count;
uint dateUpd;
uint coverId;
(, coverId, , origstat, dateUpd, state12Count) = cd.getClaim(claimId);
(, origstat) = cd.getClaimStatusNumber(claimId);
if (stat == 12 && origstat == 12) {
cd.updateState12Count(claimId, 1);
}
cd.setClaimStatus(claimId, stat);
if (state12Count >= 60 && stat == 12) {
cd.setClaimStatus(claimId, 13);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimDenied));
}
uint time = now;
cd.setClaimdateUpd(claimId, time);
if (stat >= 2 && stat <= 5) {
p1.closeClaimsOraclise(claimId, cd.maxVotingTime());
}
if (stat == 12 && (dateUpd.add(cd.payoutRetryTime()) <= now) && (state12Count < 60)) {
p1.closeClaimsOraclise(claimId, cd.payoutRetryTime());
} else if (stat == 12 && (dateUpd.add(cd.payoutRetryTime()) > now) && (state12Count < 60)) {
uint64 timeLeft = uint64((dateUpd.add(cd.payoutRetryTime())).sub(now));
p1.closeClaimsOraclise(claimId, timeLeft);
}
}
/**
* @dev Submits a claim for a given cover note.
* Set deposits flag against cover.
*/
function _addClaim(uint coverId, uint time, address add) internal {
tf.depositCN(coverId);
uint len = cd.actualClaimLength();
cd.addClaim(len, coverId, add, now);
cd.callClaimEvent(coverId, add, len, time);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimSubmitted));
bytes4 curr = qd.getCurrencyOfCover(coverId);
uint sumAssured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18);
pd.changeCurrencyAssetVarMin(curr, pd.getCurrencyAssetVarMin(curr).add(sumAssured));
p2.internalLiquiditySwap(curr);
p1.closeClaimsOraclise(len, cd.maxVotingTime());
}
}
// File: nexusmutual-contracts/contracts/ClaimsReward.sol
/* Copyright (C) 2020 NexusMutual.io
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/ */
//Claims Reward Contract contains the functions for calculating number of tokens
// that will get rewarded, unlocked or burned depending upon the status of claim.
pragma solidity 0.5.7;
contract ClaimsReward is Iupgradable {
using SafeMath for uint;
NXMToken internal tk;
TokenController internal tc;
TokenFunctions internal tf;
TokenData internal td;
QuotationData internal qd;
Claims internal c1;
ClaimsData internal cd;
Pool1 internal p1;
Pool2 internal p2;
PoolData internal pd;
Governance internal gv;
IPooledStaking internal pooledStaking;
uint private constant DECIMAL1E18 = uint(10) ** 18;
function changeDependentContractAddress() public onlyInternal {
c1 = Claims(ms.getLatestAddress("CL"));
cd = ClaimsData(ms.getLatestAddress("CD"));
tk = NXMToken(ms.tokenAddress());
tc = TokenController(ms.getLatestAddress("TC"));
td = TokenData(ms.getLatestAddress("TD"));
tf = TokenFunctions(ms.getLatestAddress("TF"));
p1 = Pool1(ms.getLatestAddress("P1"));
p2 = Pool2(ms.getLatestAddress("P2"));
pd = PoolData(ms.getLatestAddress("PD"));
qd = QuotationData(ms.getLatestAddress("QD"));
gv = Governance(ms.getLatestAddress("GV"));
pooledStaking = IPooledStaking(ms.getLatestAddress("PS"));
}
/// @dev Decides the next course of action for a given claim.
function changeClaimStatus(uint claimid) public checkPause onlyInternal {
uint coverid;
(, coverid) = cd.getClaimCoverId(claimid);
uint status;
(, status) = cd.getClaimStatusNumber(claimid);
// when current status is "Pending-Claim Assessor Vote"
if (status == 0) {
_changeClaimStatusCA(claimid, coverid, status);
} else if (status >= 1 && status <= 5) {
_changeClaimStatusMV(claimid, coverid, status);
} else if (status == 12) { // when current status is "Claim Accepted Payout Pending"
uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18);
address payable coverHolder = qd.getCoverMemberAddress(coverid);
bytes4 coverCurrency = qd.getCurrencyOfCover(coverid);
bool success = p1.sendClaimPayout(coverid, claimid, sumAssured, coverHolder, coverCurrency);
if (success) {
tf.burnStakedTokens(coverid, coverCurrency, sumAssured);
c1.setClaimStatus(claimid, 14);
}
}
c1.changePendingClaimStart();
}
/// @dev Amount of tokens to be rewarded to a user for a particular vote id.
/// @param check 1 -> CA vote, else member vote
/// @param voteid vote id for which reward has to be Calculated
/// @param flag if 1 calculate even if claimed,else don't calculate if already claimed
/// @return tokenCalculated reward to be given for vote id
/// @return lastClaimedCheck true if final verdict is still pending for that voteid
/// @return tokens number of tokens locked under that voteid
/// @return perc percentage of reward to be given.
function getRewardToBeGiven(
uint check,
uint voteid,
uint flag
)
public
view
returns (
uint tokenCalculated,
bool lastClaimedCheck,
uint tokens,
uint perc
)
{
uint claimId;
int8 verdict;
bool claimed;
uint tokensToBeDist;
uint totalTokens;
(tokens, claimId, verdict, claimed) = cd.getVoteDetails(voteid);
lastClaimedCheck = false;
int8 claimVerdict = cd.getFinalVerdict(claimId);
if (claimVerdict == 0) {
lastClaimedCheck = true;
}
if (claimVerdict == verdict && (claimed == false || flag == 1)) {
if (check == 1) {
(perc, , tokensToBeDist) = cd.getClaimRewardDetail(claimId);
} else {
(, perc, tokensToBeDist) = cd.getClaimRewardDetail(claimId);
}
if (perc > 0) {
if (check == 1) {
if (verdict == 1) {
(, totalTokens, ) = cd.getClaimsTokenCA(claimId);
} else {
(, , totalTokens) = cd.getClaimsTokenCA(claimId);
}
} else {
if (verdict == 1) {
(, totalTokens, ) = cd.getClaimsTokenMV(claimId);
}else {
(, , totalTokens) = cd.getClaimsTokenMV(claimId);
}
}
tokenCalculated = (perc.mul(tokens).mul(tokensToBeDist)).div(totalTokens.mul(100));
}
}
}
/// @dev Transfers all tokens held by contract to a new contract in case of upgrade.
function upgrade(address _newAdd) public onlyInternal {
uint amount = tk.balanceOf(address(this));
if (amount > 0) {
require(tk.transfer(_newAdd, amount));
}
}
/// @dev Total reward in token due for claim by a user.
/// @return total total number of tokens
function getRewardToBeDistributedByUser(address _add) public view returns(uint total) {
uint lengthVote = cd.getVoteAddressCALength(_add);
uint lastIndexCA;
uint lastIndexMV;
uint tokenForVoteId;
uint voteId;
(lastIndexCA, lastIndexMV) = cd.getRewardDistributedIndex(_add);
for (uint i = lastIndexCA; i < lengthVote; i++) {
voteId = cd.getVoteAddressCA(_add, i);
(tokenForVoteId, , , ) = getRewardToBeGiven(1, voteId, 0);
total = total.add(tokenForVoteId);
}
lengthVote = cd.getVoteAddressMemberLength(_add);
for (uint j = lastIndexMV; j < lengthVote; j++) {
voteId = cd.getVoteAddressMember(_add, j);
(tokenForVoteId, , , ) = getRewardToBeGiven(0, voteId, 0);
total = total.add(tokenForVoteId);
}
return (total);
}
/// @dev Gets reward amount and claiming status for a given claim id.
/// @return reward amount of tokens to user.
/// @return claimed true if already claimed false if yet to be claimed.
function getRewardAndClaimedStatus(uint check, uint claimId) public view returns(uint reward, bool claimed) {
uint voteId;
uint claimid;
uint lengthVote;
if (check == 1) {
lengthVote = cd.getVoteAddressCALength(msg.sender);
for (uint i = 0; i < lengthVote; i++) {
voteId = cd.getVoteAddressCA(msg.sender, i);
(, claimid, , claimed) = cd.getVoteDetails(voteId);
if (claimid == claimId) { break; }
}
} else {
lengthVote = cd.getVoteAddressMemberLength(msg.sender);
for (uint j = 0; j < lengthVote; j++) {
voteId = cd.getVoteAddressMember(msg.sender, j);
(, claimid, , claimed) = cd.getVoteDetails(voteId);
if (claimid == claimId) { break; }
}
}
(reward, , , ) = getRewardToBeGiven(check, voteId, 1);
}
/**
* @dev Function used to claim all pending rewards : Claims Assessment + Risk Assessment + Governance
* Claim assesment, Risk assesment, Governance rewards
*/
function claimAllPendingReward(uint records) public isMemberAndcheckPause {
_claimRewardToBeDistributed(records);
pooledStaking.withdrawReward(msg.sender);
uint governanceRewards = gv.claimReward(msg.sender, records);
if (governanceRewards > 0) {
require(tk.transfer(msg.sender, governanceRewards));
}
}
/**
* @dev Function used to get pending rewards of a particular user address.
* @param _add user address.
* @return total reward amount of the user
*/
function getAllPendingRewardOfUser(address _add) public view returns(uint) {
uint caReward = getRewardToBeDistributedByUser(_add);
uint pooledStakingReward = pooledStaking.stakerReward(_add);
uint governanceReward = gv.getPendingReward(_add);
return caReward.add(pooledStakingReward).add(governanceReward);
}
/// @dev Rewards/Punishes users who participated in Claims assessment.
// Unlocking and burning of the tokens will also depend upon the status of claim.
/// @param claimid Claim Id.
function _rewardAgainstClaim(uint claimid, uint coverid, uint sumAssured, uint status) internal {
uint premiumNXM = qd.getCoverPremiumNXM(coverid);
bytes4 curr = qd.getCurrencyOfCover(coverid);
uint distributableTokens = premiumNXM.mul(cd.claimRewardPerc()).div(100);// 20% of premium
uint percCA;
uint percMV;
(percCA, percMV) = cd.getRewardStatus(status);
cd.setClaimRewardDetail(claimid, percCA, percMV, distributableTokens);
if (percCA > 0 || percMV > 0) {
tc.mint(address(this), distributableTokens);
}
if (status == 6 || status == 9 || status == 11) {
cd.changeFinalVerdict(claimid, -1);
td.setDepositCN(coverid, false); // Unset flag
tf.burnDepositCN(coverid); // burn Deposited CN
pd.changeCurrencyAssetVarMin(curr, pd.getCurrencyAssetVarMin(curr).sub(sumAssured));
p2.internalLiquiditySwap(curr);
} else if (status == 7 || status == 8 || status == 10) {
cd.changeFinalVerdict(claimid, 1);
td.setDepositCN(coverid, false); // Unset flag
tf.unlockCN(coverid);
bool success = p1.sendClaimPayout(coverid, claimid, sumAssured, qd.getCoverMemberAddress(coverid), curr);
if (success) {
tf.burnStakedTokens(coverid, curr, sumAssured);
}
}
}
/// @dev Computes the result of Claim Assessors Voting for a given claim id.
function _changeClaimStatusCA(uint claimid, uint coverid, uint status) internal {
// Check if voting should be closed or not
if (c1.checkVoteClosing(claimid) == 1) {
uint caTokens = c1.getCATokens(claimid, 0); // converted in cover currency.
uint accept;
uint deny;
uint acceptAndDeny;
bool rewardOrPunish;
uint sumAssured;
(, accept) = cd.getClaimVote(claimid, 1);
(, deny) = cd.getClaimVote(claimid, -1);
acceptAndDeny = accept.add(deny);
accept = accept.mul(100);
deny = deny.mul(100);
if (caTokens == 0) {
status = 3;
} else {
sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18);
// Min threshold reached tokens used for voting > 5* sum assured
if (caTokens > sumAssured.mul(5)) {
if (accept.div(acceptAndDeny) > 70) {
status = 7;
qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimAccepted));
rewardOrPunish = true;
} else if (deny.div(acceptAndDeny) > 70) {
status = 6;
qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimDenied));
rewardOrPunish = true;
} else if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) {
status = 4;
} else {
status = 5;
}
} else {
if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) {
status = 2;
} else {
status = 3;
}
}
}
c1.setClaimStatus(claimid, status);
if (rewardOrPunish) {
_rewardAgainstClaim(claimid, coverid, sumAssured, status);
}
}
}
/// @dev Computes the result of Member Voting for a given claim id.
function _changeClaimStatusMV(uint claimid, uint coverid, uint status) internal {
// Check if voting should be closed or not
if (c1.checkVoteClosing(claimid) == 1) {
uint8 coverStatus;
uint statusOrig = status;
uint mvTokens = c1.getCATokens(claimid, 1); // converted in cover currency.
// If tokens used for acceptance >50%, claim is accepted
uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18);
uint thresholdUnreached = 0;
// Minimum threshold for member voting is reached only when
// value of tokens used for voting > 5* sum assured of claim id
if (mvTokens < sumAssured.mul(5)) {
thresholdUnreached = 1;
}
uint accept;
(, accept) = cd.getClaimMVote(claimid, 1);
uint deny;
(, deny) = cd.getClaimMVote(claimid, -1);
if (accept.add(deny) > 0) {
if (accept.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 &&
statusOrig <= 5 && thresholdUnreached == 0) {
status = 8;
coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted);
} else if (deny.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 &&
statusOrig <= 5 && thresholdUnreached == 0) {
status = 9;
coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied);
}
}
if (thresholdUnreached == 1 && (statusOrig == 2 || statusOrig == 4)) {
status = 10;
coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted);
} else if (thresholdUnreached == 1 && (statusOrig == 5 || statusOrig == 3 || statusOrig == 1)) {
status = 11;
coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied);
}
c1.setClaimStatus(claimid, status);
qd.changeCoverStatusNo(coverid, uint8(coverStatus));
// Reward/Punish Claim Assessors and Members who participated in Claims assessment
_rewardAgainstClaim(claimid, coverid, sumAssured, status);
}
}
/// @dev Allows a user to claim all pending Claims assessment rewards.
function _claimRewardToBeDistributed(uint _records) internal {
uint lengthVote = cd.getVoteAddressCALength(msg.sender);
uint voteid;
uint lastIndex;
(lastIndex, ) = cd.getRewardDistributedIndex(msg.sender);
uint total = 0;
uint tokenForVoteId = 0;
bool lastClaimedCheck;
uint _days = td.lockCADays();
bool claimed;
uint counter = 0;
uint claimId;
uint perc;
uint i;
uint lastClaimed = lengthVote;
for (i = lastIndex; i < lengthVote && counter < _records; i++) {
voteid = cd.getVoteAddressCA(msg.sender, i);
(tokenForVoteId, lastClaimedCheck, , perc) = getRewardToBeGiven(1, voteid, 0);
if (lastClaimed == lengthVote && lastClaimedCheck == true) {
lastClaimed = i;
}
(, claimId, , claimed) = cd.getVoteDetails(voteid);
if (perc > 0 && !claimed) {
counter++;
cd.setRewardClaimed(voteid, true);
} else if (perc == 0 && cd.getFinalVerdict(claimId) != 0 && !claimed) {
(perc, , ) = cd.getClaimRewardDetail(claimId);
if (perc == 0) {
counter++;
}
cd.setRewardClaimed(voteid, true);
}
if (tokenForVoteId > 0) {
total = tokenForVoteId.add(total);
}
}
if (lastClaimed == lengthVote) {
cd.setRewardDistributedIndexCA(msg.sender, i);
}
else {
cd.setRewardDistributedIndexCA(msg.sender, lastClaimed);
}
lengthVote = cd.getVoteAddressMemberLength(msg.sender);
lastClaimed = lengthVote;
_days = _days.mul(counter);
if (tc.tokensLockedAtTime(msg.sender, "CLA", now) > 0) {
tc.reduceLock(msg.sender, "CLA", _days);
}
(, lastIndex) = cd.getRewardDistributedIndex(msg.sender);
lastClaimed = lengthVote;
counter = 0;
for (i = lastIndex; i < lengthVote && counter < _records; i++) {
voteid = cd.getVoteAddressMember(msg.sender, i);
(tokenForVoteId, lastClaimedCheck, , ) = getRewardToBeGiven(0, voteid, 0);
if (lastClaimed == lengthVote && lastClaimedCheck == true) {
lastClaimed = i;
}
(, claimId, , claimed) = cd.getVoteDetails(voteid);
if (claimed == false && cd.getFinalVerdict(claimId) != 0) {
cd.setRewardClaimed(voteid, true);
counter++;
}
if (tokenForVoteId > 0) {
total = tokenForVoteId.add(total);
}
}
if (total > 0) {
require(tk.transfer(msg.sender, total));
}
if (lastClaimed == lengthVote) {
cd.setRewardDistributedIndexMV(msg.sender, i);
}
else {
cd.setRewardDistributedIndexMV(msg.sender, lastClaimed);
}
}
/**
* @dev Function used to claim the commission earned by the staker.
*/
function _claimStakeCommission(uint _records, address _user) external onlyInternal {
uint total=0;
uint len = td.getStakerStakedContractLength(_user);
uint lastCompletedStakeCommission = td.lastCompletedStakeCommission(_user);
uint commissionEarned;
uint commissionRedeemed;
uint maxCommission;
uint lastCommisionRedeemed = len;
uint counter;
uint i;
for (i = lastCompletedStakeCommission; i < len && counter < _records; i++) {
commissionRedeemed = td.getStakerRedeemedStakeCommission(_user, i);
commissionEarned = td.getStakerEarnedStakeCommission(_user, i);
maxCommission = td.getStakerInitialStakedAmountOnContract(
_user, i).mul(td.stakerMaxCommissionPer()).div(100);
if (lastCommisionRedeemed == len && maxCommission != commissionEarned)
lastCommisionRedeemed = i;
td.pushRedeemedStakeCommissions(_user, i, commissionEarned.sub(commissionRedeemed));
total = total.add(commissionEarned.sub(commissionRedeemed));
counter++;
}
if (lastCommisionRedeemed == len) {
td.setLastCompletedStakeCommissionIndex(_user, i);
} else {
td.setLastCompletedStakeCommissionIndex(_user, lastCommisionRedeemed);
}
if (total > 0)
require(tk.transfer(_user, total)); //solhint-disable-line
}
}
// File: nexusmutual-contracts/contracts/MemberRoles.sol
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity 0.5.7;
contract MemberRoles is IMemberRoles, Governed, Iupgradable {
TokenController public dAppToken;
TokenData internal td;
QuotationData internal qd;
ClaimsReward internal cr;
Governance internal gv;
TokenFunctions internal tf;
NXMToken public tk;
struct MemberRoleDetails {
uint memberCounter;
mapping(address => bool) memberActive;
address[] memberAddress;
address authorized;
}
enum Role {UnAssigned, AdvisoryBoard, Member, Owner}
event switchedMembership(address indexed previousMember, address indexed newMember, uint timeStamp);
MemberRoleDetails[] internal memberRoleData;
bool internal constructorCheck;
uint public maxABCount;
bool public launched;
uint public launchedOn;
modifier checkRoleAuthority(uint _memberRoleId) {
if (memberRoleData[_memberRoleId].authorized != address(0))
require(msg.sender == memberRoleData[_memberRoleId].authorized);
else
require(isAuthorizedToGovern(msg.sender), "Not Authorized");
_;
}
/**
* @dev to swap advisory board member
* @param _newABAddress is address of new AB member
* @param _removeAB is advisory board member to be removed
*/
function swapABMember (
address _newABAddress,
address _removeAB
)
external
checkRoleAuthority(uint(Role.AdvisoryBoard)) {
_updateRole(_newABAddress, uint(Role.AdvisoryBoard), true);
_updateRole(_removeAB, uint(Role.AdvisoryBoard), false);
}
/**
* @dev to swap the owner address
* @param _newOwnerAddress is the new owner address
*/
function swapOwner (
address _newOwnerAddress
)
external {
require(msg.sender == address(ms));
_updateRole(ms.owner(), uint(Role.Owner), false);
_updateRole(_newOwnerAddress, uint(Role.Owner), true);
}
/**
* @dev is used to add initital advisory board members
* @param abArray is the list of initial advisory board members
*/
function addInitialABMembers(address[] calldata abArray) external onlyOwner {
//Ensure that NXMaster has initialized.
require(ms.masterInitialized());
require(maxABCount >=
SafeMath.add(numberOfMembers(uint(Role.AdvisoryBoard)), abArray.length)
);
//AB count can't exceed maxABCount
for (uint i = 0; i < abArray.length; i++) {
require(checkRole(abArray[i], uint(MemberRoles.Role.Member)));
_updateRole(abArray[i], uint(Role.AdvisoryBoard), true);
}
}
/**
* @dev to change max number of AB members allowed
* @param _val is the new value to be set
*/
function changeMaxABCount(uint _val) external onlyInternal {
maxABCount = _val;
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public {
td = TokenData(ms.getLatestAddress("TD"));
cr = ClaimsReward(ms.getLatestAddress("CR"));
qd = QuotationData(ms.getLatestAddress("QD"));
gv = Governance(ms.getLatestAddress("GV"));
tf = TokenFunctions(ms.getLatestAddress("TF"));
tk = NXMToken(ms.tokenAddress());
dAppToken = TokenController(ms.getLatestAddress("TC"));
}
/**
* @dev to change the master address
* @param _masterAddress is the new master address
*/
function changeMasterAddress(address _masterAddress) public {
if (masterAddress != address(0))
require(masterAddress == msg.sender);
masterAddress = _masterAddress;
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
/**
* @dev to initiate the member roles
* @param _firstAB is the address of the first AB member
* @param memberAuthority is the authority (role) of the member
*/
function memberRolesInitiate (address _firstAB, address memberAuthority) public {
require(!constructorCheck);
_addInitialMemberRoles(_firstAB, memberAuthority);
constructorCheck = true;
}
/// @dev Adds new member role
/// @param _roleName New role name
/// @param _roleDescription New description hash
/// @param _authorized Authorized member against every role id
function addRole( //solhint-disable-line
bytes32 _roleName,
string memory _roleDescription,
address _authorized
)
public
onlyAuthorizedToGovern {
_addRole(_roleName, _roleDescription, _authorized);
}
/// @dev Assign or Delete a member from specific role.
/// @param _memberAddress Address of Member
/// @param _roleId RoleId to update
/// @param _active active is set to be True if we want to assign this role to member, False otherwise!
function updateRole( //solhint-disable-line
address _memberAddress,
uint _roleId,
bool _active
)
public
checkRoleAuthority(_roleId) {
_updateRole(_memberAddress, _roleId, _active);
}
/**
* @dev to add members before launch
* @param userArray is list of addresses of members
* @param tokens is list of tokens minted for each array element
*/
function addMembersBeforeLaunch(address[] memory userArray, uint[] memory tokens) public onlyOwner {
require(!launched);
for (uint i=0; i < userArray.length; i++) {
require(!ms.isMember(userArray[i]));
dAppToken.addToWhitelist(userArray[i]);
_updateRole(userArray[i], uint(Role.Member), true);
dAppToken.mint(userArray[i], tokens[i]);
}
launched = true;
launchedOn = now;
}
/**
* @dev Called by user to pay joining membership fee
*/
function payJoiningFee(address _userAddress) public payable {
require(_userAddress != address(0));
require(!ms.isPause(), "Emergency Pause Applied");
if (msg.sender == address(ms.getLatestAddress("QT"))) {
require(td.walletAddress() != address(0), "No walletAddress present");
dAppToken.addToWhitelist(_userAddress);
_updateRole(_userAddress, uint(Role.Member), true);
td.walletAddress().transfer(msg.value);
} else {
require(!qd.refundEligible(_userAddress));
require(!ms.isMember(_userAddress));
require(msg.value == td.joiningFee());
qd.setRefundEligible(_userAddress, true);
}
}
/**
* @dev to perform kyc verdict
* @param _userAddress whose kyc is being performed
* @param verdict of kyc process
*/
function kycVerdict(address payable _userAddress, bool verdict) public {
require(msg.sender == qd.kycAuthAddress());
require(!ms.isPause());
require(_userAddress != address(0));
require(!ms.isMember(_userAddress));
require(qd.refundEligible(_userAddress));
if (verdict) {
qd.setRefundEligible(_userAddress, false);
uint fee = td.joiningFee();
dAppToken.addToWhitelist(_userAddress);
_updateRole(_userAddress, uint(Role.Member), true);
td.walletAddress().transfer(fee); //solhint-disable-line
} else {
qd.setRefundEligible(_userAddress, false);
_userAddress.transfer(td.joiningFee()); //solhint-disable-line
}
}
/**
* @dev Called by existed member if wish to Withdraw membership.
*/
function withdrawMembership() public {
require(!ms.isPause() && ms.isMember(msg.sender));
require(dAppToken.totalLockedBalance(msg.sender, now) == 0); //solhint-disable-line
require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting
require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment).
require(dAppToken.tokensUnlockable(msg.sender, "CLA") == 0, "Member should have no CLA unlockable tokens");
gv.removeDelegation(msg.sender);
dAppToken.burnFrom(msg.sender, tk.balanceOf(msg.sender));
_updateRole(msg.sender, uint(Role.Member), false);
dAppToken.removeFromWhitelist(msg.sender); // need clarification on whitelist
}
/**
* @dev Called by existed member if wish to switch membership to other address.
* @param _add address of user to forward membership.
*/
function switchMembership(address _add) external {
require(!ms.isPause() && ms.isMember(msg.sender) && !ms.isMember(_add));
require(dAppToken.totalLockedBalance(msg.sender, now) == 0); //solhint-disable-line
require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting
require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment).
require(dAppToken.tokensUnlockable(msg.sender, "CLA") == 0, "Member should have no CLA unlockable tokens");
gv.removeDelegation(msg.sender);
dAppToken.addToWhitelist(_add);
_updateRole(_add, uint(Role.Member), true);
tk.transferFrom(msg.sender, _add, tk.balanceOf(msg.sender));
_updateRole(msg.sender, uint(Role.Member), false);
dAppToken.removeFromWhitelist(msg.sender);
emit switchedMembership(msg.sender, _add, now);
}
/// @dev Return number of member roles
function totalRoles() public view returns(uint256) { //solhint-disable-line
return memberRoleData.length;
}
/// @dev Change Member Address who holds the authority to Add/Delete any member from specific role.
/// @param _roleId roleId to update its Authorized Address
/// @param _newAuthorized New authorized address against role id
function changeAuthorized(uint _roleId, address _newAuthorized) public checkRoleAuthority(_roleId) { //solhint-disable-line
memberRoleData[_roleId].authorized = _newAuthorized;
}
/// @dev Gets the member addresses assigned by a specific role
/// @param _memberRoleId Member role id
/// @return roleId Role id
/// @return allMemberAddress Member addresses of specified role id
function members(uint _memberRoleId) public view returns(uint, address[] memory memberArray) { //solhint-disable-line
uint length = memberRoleData[_memberRoleId].memberAddress.length;
uint i;
uint j = 0;
memberArray = new address[](memberRoleData[_memberRoleId].memberCounter);
for (i = 0; i < length; i++) {
address member = memberRoleData[_memberRoleId].memberAddress[i];
if (memberRoleData[_memberRoleId].memberActive[member] && !_checkMemberInArray(member, memberArray)) { //solhint-disable-line
memberArray[j] = member;
j++;
}
}
return (_memberRoleId, memberArray);
}
/// @dev Gets all members' length
/// @param _memberRoleId Member role id
/// @return memberRoleData[_memberRoleId].memberCounter Member length
function numberOfMembers(uint _memberRoleId) public view returns(uint) { //solhint-disable-line
return memberRoleData[_memberRoleId].memberCounter;
}
/// @dev Return member address who holds the right to add/remove any member from specific role.
function authorized(uint _memberRoleId) public view returns(address) { //solhint-disable-line
return memberRoleData[_memberRoleId].authorized;
}
/// @dev Get All role ids array that has been assigned to a member so far.
function roles(address _memberAddress) public view returns(uint[] memory) { //solhint-disable-line
uint length = memberRoleData.length;
uint[] memory assignedRoles = new uint[](length);
uint counter = 0;
for (uint i = 1; i < length; i++) {
if (memberRoleData[i].memberActive[_memberAddress]) {
assignedRoles[counter] = i;
counter++;
}
}
return assignedRoles;
}
/// @dev Returns true if the given role id is assigned to a member.
/// @param _memberAddress Address of member
/// @param _roleId Checks member's authenticity with the roleId.
/// i.e. Returns true if this roleId is assigned to member
function checkRole(address _memberAddress, uint _roleId) public view returns(bool) { //solhint-disable-line
if (_roleId == uint(Role.UnAssigned))
return true;
else
if (memberRoleData[_roleId].memberActive[_memberAddress]) //solhint-disable-line
return true;
else
return false;
}
/// @dev Return total number of members assigned against each role id.
/// @return totalMembers Total members in particular role id
function getMemberLengthForAllRoles() public view returns(uint[] memory totalMembers) { //solhint-disable-line
totalMembers = new uint[](memberRoleData.length);
for (uint i = 0; i < memberRoleData.length; i++) {
totalMembers[i] = numberOfMembers(i);
}
}
/**
* @dev to update the member roles
* @param _memberAddress in concern
* @param _roleId the id of role
* @param _active if active is true, add the member, else remove it
*/
function _updateRole(address _memberAddress,
uint _roleId,
bool _active) internal {
// require(_roleId != uint(Role.TokenHolder), "Membership to Token holder is detected automatically");
if (_active) {
require(!memberRoleData[_roleId].memberActive[_memberAddress]);
memberRoleData[_roleId].memberCounter = SafeMath.add(memberRoleData[_roleId].memberCounter, 1);
memberRoleData[_roleId].memberActive[_memberAddress] = true;
memberRoleData[_roleId].memberAddress.push(_memberAddress);
} else {
require(memberRoleData[_roleId].memberActive[_memberAddress]);
memberRoleData[_roleId].memberCounter = SafeMath.sub(memberRoleData[_roleId].memberCounter, 1);
delete memberRoleData[_roleId].memberActive[_memberAddress];
}
}
/// @dev Adds new member role
/// @param _roleName New role name
/// @param _roleDescription New description hash
/// @param _authorized Authorized member against every role id
function _addRole(
bytes32 _roleName,
string memory _roleDescription,
address _authorized
) internal {
emit MemberRole(memberRoleData.length, _roleName, _roleDescription);
memberRoleData.push(MemberRoleDetails(0, new address[](0), _authorized));
}
/**
* @dev to check if member is in the given member array
* @param _memberAddress in concern
* @param memberArray in concern
* @return boolean to represent the presence
*/
function _checkMemberInArray(
address _memberAddress,
address[] memory memberArray
)
internal
pure
returns(bool memberExists)
{
uint i;
for (i = 0; i < memberArray.length; i++) {
if (memberArray[i] == _memberAddress) {
memberExists = true;
break;
}
}
}
/**
* @dev to add initial member roles
* @param _firstAB is the member address to be added
* @param memberAuthority is the member authority(role) to be added for
*/
function _addInitialMemberRoles(address _firstAB, address memberAuthority) internal {
maxABCount = 5;
_addRole("Unassigned", "Unassigned", address(0));
_addRole(
"Advisory Board",
"Selected few members that are deeply entrusted by the dApp. An ideal advisory board should be a mix of skills of domain, governance, research, technology, consulting etc to improve the performance of the dApp.", //solhint-disable-line
address(0)
);
_addRole(
"Member",
"Represents all users of Mutual.", //solhint-disable-line
memberAuthority
);
_addRole(
"Owner",
"Represents Owner of Mutual.", //solhint-disable-line
address(0)
);
// _updateRole(_firstAB, uint(Role.AdvisoryBoard), true);
_updateRole(_firstAB, uint(Role.Owner), true);
// _updateRole(_firstAB, uint(Role.Member), true);
launchedOn = 0;
}
function memberAtIndex(uint _memberRoleId, uint index) external view returns (address, bool) {
address memberAddress = memberRoleData[_memberRoleId].memberAddress[index];
return (memberAddress, memberRoleData[_memberRoleId].memberActive[memberAddress]);
}
function membersLength(uint _memberRoleId) external view returns (uint) {
return memberRoleData[_memberRoleId].memberAddress.length;
}
}
// File: nexusmutual-contracts/contracts/ProposalCategory.sol
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity 0.5.7;
contract ProposalCategory is Governed, IProposalCategory, Iupgradable {
bool public constructorCheck;
MemberRoles internal mr;
struct CategoryStruct {
uint memberRoleToVote;
uint majorityVotePerc;
uint quorumPerc;
uint[] allowedToCreateProposal;
uint closingTime;
uint minStake;
}
struct CategoryAction {
uint defaultIncentive;
address contractAddress;
bytes2 contractName;
}
CategoryStruct[] internal allCategory;
mapping (uint => CategoryAction) internal categoryActionData;
mapping (uint => uint) public categoryABReq;
mapping (uint => uint) public isSpecialResolution;
mapping (uint => bytes) public categoryActionHashes;
bool public categoryActionHashUpdated;
/**
* @dev Restricts calls to deprecated functions
*/
modifier deprecated() {
revert("Function deprecated");
_;
}
/**
* @dev Adds new category (Discontinued, moved functionality to newCategory)
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function addCategory(
string calldata _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] calldata _allowedToCreateProposal,
uint _closingTime,
string calldata _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] calldata _incentives
)
external
deprecated
{
}
/**
* @dev Initiates Default settings for Proposal Category contract (Adding default categories)
*/
function proposalCategoryInitiate() external deprecated { //solhint-disable-line
}
/**
* @dev Initiates Default action function hashes for existing categories
* To be called after the contract has been upgraded by governance
*/
function updateCategoryActionHashes() external onlyOwner {
require(!categoryActionHashUpdated, "Category action hashes already updated");
categoryActionHashUpdated = true;
categoryActionHashes[1] = abi.encodeWithSignature("addRole(bytes32,string,address)");
categoryActionHashes[2] = abi.encodeWithSignature("updateRole(address,uint256,bool)");
categoryActionHashes[3] = abi.encodeWithSignature("newCategory(string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)");//solhint-disable-line
categoryActionHashes[4] = abi.encodeWithSignature("editCategory(uint256,string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)");//solhint-disable-line
categoryActionHashes[5] = abi.encodeWithSignature("upgradeContractImplementation(bytes2,address)");
categoryActionHashes[6] = abi.encodeWithSignature("startEmergencyPause()");
categoryActionHashes[7] = abi.encodeWithSignature("addEmergencyPause(bool,bytes4)");
categoryActionHashes[8] = abi.encodeWithSignature("burnCAToken(uint256,uint256,address)");
categoryActionHashes[9] = abi.encodeWithSignature("setUserClaimVotePausedOn(address)");
categoryActionHashes[12] = abi.encodeWithSignature("transferEther(uint256,address)");
categoryActionHashes[13] = abi.encodeWithSignature("addInvestmentAssetCurrency(bytes4,address,bool,uint64,uint64,uint8)");//solhint-disable-line
categoryActionHashes[14] = abi.encodeWithSignature("changeInvestmentAssetHoldingPerc(bytes4,uint64,uint64)");
categoryActionHashes[15] = abi.encodeWithSignature("changeInvestmentAssetStatus(bytes4,bool)");
categoryActionHashes[16] = abi.encodeWithSignature("swapABMember(address,address)");
categoryActionHashes[17] = abi.encodeWithSignature("addCurrencyAssetCurrency(bytes4,address,uint256)");
categoryActionHashes[20] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[21] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[22] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[23] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[24] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[25] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[26] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[27] = abi.encodeWithSignature("updateAddressParameters(bytes8,address)");
categoryActionHashes[28] = abi.encodeWithSignature("updateOwnerParameters(bytes8,address)");
categoryActionHashes[29] = abi.encodeWithSignature("upgradeContract(bytes2,address)");
categoryActionHashes[30] = abi.encodeWithSignature("changeCurrencyAssetAddress(bytes4,address)");
categoryActionHashes[31] = abi.encodeWithSignature("changeCurrencyAssetBaseMin(bytes4,uint256)");
categoryActionHashes[32] = abi.encodeWithSignature("changeInvestmentAssetAddressAndDecimal(bytes4,address,uint8)");//solhint-disable-line
categoryActionHashes[33] = abi.encodeWithSignature("externalLiquidityTrade()");
}
/**
* @dev Gets Total number of categories added till now
*/
function totalCategories() external view returns(uint) {
return allCategory.length;
}
/**
* @dev Gets category details
*/
function category(uint _categoryId) external view returns(uint, uint, uint, uint, uint[] memory, uint, uint) {
return(
_categoryId,
allCategory[_categoryId].memberRoleToVote,
allCategory[_categoryId].majorityVotePerc,
allCategory[_categoryId].quorumPerc,
allCategory[_categoryId].allowedToCreateProposal,
allCategory[_categoryId].closingTime,
allCategory[_categoryId].minStake
);
}
/**
* @dev Gets category ab required and isSpecialResolution
* @return the category id
* @return if AB voting is required
* @return is category a special resolution
*/
function categoryExtendedData(uint _categoryId) external view returns(uint, uint, uint) {
return(
_categoryId,
categoryABReq[_categoryId],
isSpecialResolution[_categoryId]
);
}
/**
* @dev Gets the category acion details
* @param _categoryId is the category id in concern
* @return the category id
* @return the contract address
* @return the contract name
* @return the default incentive
*/
function categoryAction(uint _categoryId) external view returns(uint, address, bytes2, uint) {
return(
_categoryId,
categoryActionData[_categoryId].contractAddress,
categoryActionData[_categoryId].contractName,
categoryActionData[_categoryId].defaultIncentive
);
}
/**
* @dev Gets the category acion details of a category id
* @param _categoryId is the category id in concern
* @return the category id
* @return the contract address
* @return the contract name
* @return the default incentive
* @return action function hash
*/
function categoryActionDetails(uint _categoryId) external view returns(uint, address, bytes2, uint, bytes memory) {
return(
_categoryId,
categoryActionData[_categoryId].contractAddress,
categoryActionData[_categoryId].contractName,
categoryActionData[_categoryId].defaultIncentive,
categoryActionHashes[_categoryId]
);
}
/**
* @dev Updates dependant contract addresses
*/
function changeDependentContractAddress() public {
mr = MemberRoles(ms.getLatestAddress("MR"));
}
/**
* @dev Adds new category
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
* @param _functionHash function signature to be executed
*/
function newCategory(
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives,
string memory _functionHash
)
public
onlyAuthorizedToGovern
{
require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage");
require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0);
require(_incentives[3] <= 1, "Invalid special resolution flag");
//If category is special resolution role authorized should be member
if (_incentives[3] == 1) {
require(_memberRoleToVote == uint(MemberRoles.Role.Member));
_majorityVotePerc = 0;
_quorumPerc = 0;
}
_addCategory(
_name,
_memberRoleToVote,
_majorityVotePerc,
_quorumPerc,
_allowedToCreateProposal,
_closingTime,
_actionHash,
_contractAddress,
_contractName,
_incentives
);
if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) {
categoryActionHashes[allCategory.length - 1] = abi.encodeWithSignature(_functionHash);
}
}
/**
* @dev Changes the master address and update it's instance
* @param _masterAddress is the new master address
*/
function changeMasterAddress(address _masterAddress) public {
if (masterAddress != address(0))
require(masterAddress == msg.sender);
masterAddress = _masterAddress;
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
/**
* @dev Updates category details (Discontinued, moved functionality to editCategory)
* @param _categoryId Category id that needs to be updated
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function updateCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
)
public
deprecated
{
}
/**
* @dev Updates category details
* @param _categoryId Category id that needs to be updated
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
* @param _functionHash function signature to be executed
*/
function editCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives,
string memory _functionHash
)
public
onlyAuthorizedToGovern
{
require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role");
require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage");
require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0);
require(_incentives[3] <= 1, "Invalid special resolution flag");
//If category is special resolution role authorized should be member
if (_incentives[3] == 1) {
require(_memberRoleToVote == uint(MemberRoles.Role.Member));
_majorityVotePerc = 0;
_quorumPerc = 0;
}
delete categoryActionHashes[_categoryId];
if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) {
categoryActionHashes[_categoryId] = abi.encodeWithSignature(_functionHash);
}
allCategory[_categoryId].memberRoleToVote = _memberRoleToVote;
allCategory[_categoryId].majorityVotePerc = _majorityVotePerc;
allCategory[_categoryId].closingTime = _closingTime;
allCategory[_categoryId].allowedToCreateProposal = _allowedToCreateProposal;
allCategory[_categoryId].minStake = _incentives[0];
allCategory[_categoryId].quorumPerc = _quorumPerc;
categoryActionData[_categoryId].defaultIncentive = _incentives[1];
categoryActionData[_categoryId].contractName = _contractName;
categoryActionData[_categoryId].contractAddress = _contractAddress;
categoryABReq[_categoryId] = _incentives[2];
isSpecialResolution[_categoryId] = _incentives[3];
emit Category(_categoryId, _name, _actionHash);
}
/**
* @dev Internal call to add new category
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function _addCategory(
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
)
internal
{
require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role");
allCategory.push(
CategoryStruct(
_memberRoleToVote,
_majorityVotePerc,
_quorumPerc,
_allowedToCreateProposal,
_closingTime,
_incentives[0]
)
);
uint categoryId = allCategory.length - 1;
categoryActionData[categoryId] = CategoryAction(_incentives[1], _contractAddress, _contractName);
categoryABReq[categoryId] = _incentives[2];
isSpecialResolution[categoryId] = _incentives[3];
emit Category(categoryId, _name, _actionHash);
}
/**
* @dev Internal call to check if given roles are valid or not
*/
function _verifyMemberRoles(uint _memberRoleToVote, uint[] memory _allowedToCreateProposal)
internal view returns(uint) {
uint totalRoles = mr.totalRoles();
if (_memberRoleToVote >= totalRoles) {
return 0;
}
for (uint i = 0; i < _allowedToCreateProposal.length; i++) {
if (_allowedToCreateProposal[i] >= totalRoles) {
return 0;
}
}
return 1;
}
}
// File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IGovernance.sol
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity 0.5.7;
contract IGovernance {
event Proposal(
address indexed proposalOwner,
uint256 indexed proposalId,
uint256 dateAdd,
string proposalTitle,
string proposalSD,
string proposalDescHash
);
event Solution(
uint256 indexed proposalId,
address indexed solutionOwner,
uint256 indexed solutionId,
string solutionDescHash,
uint256 dateAdd
);
event Vote(
address indexed from,
uint256 indexed proposalId,
uint256 indexed voteId,
uint256 dateAdd,
uint256 solutionChosen
);
event RewardClaimed(
address indexed member,
uint gbtReward
);
/// @dev VoteCast event is called whenever a vote is cast that can potentially close the proposal.
event VoteCast (uint256 proposalId);
/// @dev ProposalAccepted event is called when a proposal is accepted so that a server can listen that can
/// call any offchain actions
event ProposalAccepted (uint256 proposalId);
/// @dev CloseProposalOnTime event is called whenever a proposal is created or updated to close it on time.
event CloseProposalOnTime (
uint256 indexed proposalId,
uint256 time
);
/// @dev ActionSuccess event is called whenever an onchain action is executed.
event ActionSuccess (
uint256 proposalId
);
/// @dev Creates a new proposal
/// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
/// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
function createProposal(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId
)
external;
/// @dev Edits the details of an existing proposal and creates new version
/// @param _proposalId Proposal id that details needs to be updated
/// @param _proposalDescHash Proposal description hash having long and short description of proposal.
function updateProposal(
uint _proposalId,
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash
)
external;
/// @dev Categorizes proposal to proceed further. Categories shows the proposal objective.
function categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentives
)
external;
/// @dev Initiates add solution
/// @param _solutionHash Solution hash having required data against adding solution
function addSolution(
uint _proposalId,
string calldata _solutionHash,
bytes calldata _action
)
external;
/// @dev Opens proposal for voting
function openProposalForVoting(uint _proposalId) external;
/// @dev Submit proposal with solution
/// @param _proposalId Proposal id
/// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
function submitProposalWithSolution(
uint _proposalId,
string calldata _solutionHash,
bytes calldata _action
)
external;
/// @dev Creates a new proposal with solution and votes for the solution
/// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
/// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
/// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
function createProposalwithSolution(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId,
string calldata _solutionHash,
bytes calldata _action
)
external;
/// @dev Casts vote
/// @param _proposalId Proposal id
/// @param _solutionChosen solution chosen while voting. _solutionChosen[0] is the chosen solution
function submitVote(uint _proposalId, uint _solutionChosen) external;
function closeProposal(uint _proposalId) external;
function claimReward(address _memberAddress, uint _maxRecords) external returns(uint pendingDAppReward);
function proposal(uint _proposalId)
external
view
returns(
uint proposalId,
uint category,
uint status,
uint finalVerdict,
uint totalReward
);
function canCloseProposal(uint _proposalId) public view returns(uint closeValue);
function pauseProposal(uint _proposalId) public;
function resumeProposal(uint _proposalId) public;
function allowedToCatgorize() public view returns(uint roleId);
}
// File: nexusmutual-contracts/contracts/Governance.sol
// /* Copyright (C) 2017 GovBlocks.io
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity 0.5.7;
contract Governance is IGovernance, Iupgradable {
using SafeMath for uint;
enum ProposalStatus {
Draft,
AwaitingSolution,
VotingStarted,
Accepted,
Rejected,
Majority_Not_Reached_But_Accepted,
Denied
}
struct ProposalData {
uint propStatus;
uint finalVerdict;
uint category;
uint commonIncentive;
uint dateUpd;
address owner;
}
struct ProposalVote {
address voter;
uint proposalId;
uint dateAdd;
}
struct VoteTally {
mapping(uint=>uint) memberVoteValue;
mapping(uint=>uint) abVoteValue;
uint voters;
}
struct DelegateVote {
address follower;
address leader;
uint lastUpd;
}
ProposalVote[] internal allVotes;
DelegateVote[] public allDelegation;
mapping(uint => ProposalData) internal allProposalData;
mapping(uint => bytes[]) internal allProposalSolutions;
mapping(address => uint[]) internal allVotesByMember;
mapping(uint => mapping(address => bool)) public rewardClaimed;
mapping (address => mapping(uint => uint)) public memberProposalVote;
mapping (address => uint) public followerDelegation;
mapping (address => uint) internal followerCount;
mapping (address => uint[]) internal leaderDelegation;
mapping (uint => VoteTally) public proposalVoteTally;
mapping (address => bool) public isOpenForDelegation;
mapping (address => uint) public lastRewardClaimed;
bool internal constructorCheck;
uint public tokenHoldingTime;
uint internal roleIdAllowedToCatgorize;
uint internal maxVoteWeigthPer;
uint internal specialResolutionMajPerc;
uint internal maxFollowers;
uint internal totalProposals;
uint internal maxDraftTime;
MemberRoles internal memberRole;
ProposalCategory internal proposalCategory;
TokenController internal tokenInstance;
mapping(uint => uint) public proposalActionStatus;
mapping(uint => uint) internal proposalExecutionTime;
mapping(uint => mapping(address => bool)) public proposalRejectedByAB;
mapping(uint => uint) internal actionRejectedCount;
bool internal actionParamsInitialised;
uint internal actionWaitingTime;
uint constant internal AB_MAJ_TO_REJECT_ACTION = 3;
enum ActionStatus {
Pending,
Accepted,
Rejected,
Executed,
NoAction
}
/**
* @dev Called whenever an action execution is failed.
*/
event ActionFailed (
uint256 proposalId
);
/**
* @dev Called whenever an AB member rejects the action execution.
*/
event ActionRejected (
uint256 indexed proposalId,
address rejectedBy
);
/**
* @dev Checks if msg.sender is proposal owner
*/
modifier onlyProposalOwner(uint _proposalId) {
require(msg.sender == allProposalData[_proposalId].owner, "Not allowed");
_;
}
/**
* @dev Checks if proposal is opened for voting
*/
modifier voteNotStarted(uint _proposalId) {
require(allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted));
_;
}
/**
* @dev Checks if msg.sender is allowed to create proposal under given category
*/
modifier isAllowed(uint _categoryId) {
require(allowedToCreateProposal(_categoryId), "Not allowed");
_;
}
/**
* @dev Checks if msg.sender is allowed categorize proposal under given category
*/
modifier isAllowedToCategorize() {
require(memberRole.checkRole(msg.sender, roleIdAllowedToCatgorize), "Not allowed");
_;
}
/**
* @dev Checks if msg.sender had any pending rewards to be claimed
*/
modifier checkPendingRewards {
require(getPendingReward(msg.sender) == 0, "Claim reward");
_;
}
/**
* @dev Event emitted whenever a proposal is categorized
*/
event ProposalCategorized(
uint indexed proposalId,
address indexed categorizedBy,
uint categoryId
);
/**
* @dev Removes delegation of an address.
* @param _add address to undelegate.
*/
function removeDelegation(address _add) external onlyInternal {
_unDelegate(_add);
}
/**
* @dev Creates a new proposal
* @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
* @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
*/
function createProposal(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId
)
external isAllowed(_categoryId)
{
require(ms.isMember(msg.sender), "Not Member");
_createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId);
}
/**
* @dev Edits the details of an existing proposal
* @param _proposalId Proposal id that details needs to be updated
* @param _proposalDescHash Proposal description hash having long and short description of proposal.
*/
function updateProposal(
uint _proposalId,
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash
)
external onlyProposalOwner(_proposalId)
{
require(
allProposalSolutions[_proposalId].length < 2,
"Not allowed"
);
allProposalData[_proposalId].propStatus = uint(ProposalStatus.Draft);
allProposalData[_proposalId].category = 0;
allProposalData[_proposalId].commonIncentive = 0;
emit Proposal(
allProposalData[_proposalId].owner,
_proposalId,
now,
_proposalTitle,
_proposalSD,
_proposalDescHash
);
}
/**
* @dev Categorizes proposal to proceed further. Categories shows the proposal objective.
*/
function categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentive
)
external
voteNotStarted(_proposalId) isAllowedToCategorize
{
_categorizeProposal(_proposalId, _categoryId, _incentive);
}
/**
* @dev Initiates add solution
* To implement the governance interface
*/
function addSolution(uint, string calldata, bytes calldata) external {
}
/**
* @dev Opens proposal for voting
* To implement the governance interface
*/
function openProposalForVoting(uint) external {
}
/**
* @dev Submit proposal with solution
* @param _proposalId Proposal id
* @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
*/
function submitProposalWithSolution(
uint _proposalId,
string calldata _solutionHash,
bytes calldata _action
)
external
onlyProposalOwner(_proposalId)
{
require(allProposalData[_proposalId].propStatus == uint(ProposalStatus.AwaitingSolution));
_proposalSubmission(_proposalId, _solutionHash, _action);
}
/**
* @dev Creates a new proposal with solution
* @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
* @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
* @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
*/
function createProposalwithSolution(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId,
string calldata _solutionHash,
bytes calldata _action
)
external isAllowed(_categoryId)
{
uint proposalId = totalProposals;
_createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId);
require(_categoryId > 0);
_proposalSubmission(
proposalId,
_solutionHash,
_action
);
}
/**
* @dev Submit a vote on the proposal.
* @param _proposalId to vote upon.
* @param _solutionChosen is the chosen vote.
*/
function submitVote(uint _proposalId, uint _solutionChosen) external {
require(allProposalData[_proposalId].propStatus ==
uint(Governance.ProposalStatus.VotingStarted), "Not allowed");
require(_solutionChosen < allProposalSolutions[_proposalId].length);
_submitVote(_proposalId, _solutionChosen);
}
/**
* @dev Closes the proposal.
* @param _proposalId of proposal to be closed.
*/
function closeProposal(uint _proposalId) external {
uint category = allProposalData[_proposalId].category;
uint _memberRole;
if (allProposalData[_proposalId].dateUpd.add(maxDraftTime) <= now &&
allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)) {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
} else {
require(canCloseProposal(_proposalId) == 1);
(, _memberRole, , , , , ) = proposalCategory.category(allProposalData[_proposalId].category);
if (_memberRole == uint(MemberRoles.Role.AdvisoryBoard)) {
_closeAdvisoryBoardVote(_proposalId, category);
} else {
_closeMemberVote(_proposalId, category);
}
}
}
/**
* @dev Claims reward for member.
* @param _memberAddress to claim reward of.
* @param _maxRecords maximum number of records to claim reward for.
_proposals list of proposals of which reward will be claimed.
* @return amount of pending reward.
*/
function claimReward(address _memberAddress, uint _maxRecords)
external returns(uint pendingDAppReward)
{
uint voteId;
address leader;
uint lastUpd;
require(msg.sender == ms.getLatestAddress("CR"));
uint delegationId = followerDelegation[_memberAddress];
DelegateVote memory delegationData = allDelegation[delegationId];
if (delegationId > 0 && delegationData.leader != address(0)) {
leader = delegationData.leader;
lastUpd = delegationData.lastUpd;
} else
leader = _memberAddress;
uint proposalId;
uint totalVotes = allVotesByMember[leader].length;
uint lastClaimed = totalVotes;
uint j;
uint i;
for (i = lastRewardClaimed[_memberAddress]; i < totalVotes && j < _maxRecords; i++) {
voteId = allVotesByMember[leader][i];
proposalId = allVotes[voteId].proposalId;
if (proposalVoteTally[proposalId].voters > 0 && (allVotes[voteId].dateAdd > (
lastUpd.add(tokenHoldingTime)) || leader == _memberAddress)) {
if (allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) {
if (!rewardClaimed[voteId][_memberAddress]) {
pendingDAppReward = pendingDAppReward.add(
allProposalData[proposalId].commonIncentive.div(
proposalVoteTally[proposalId].voters
)
);
rewardClaimed[voteId][_memberAddress] = true;
j++;
}
} else {
if (lastClaimed == totalVotes) {
lastClaimed = i;
}
}
}
}
if (lastClaimed == totalVotes) {
lastRewardClaimed[_memberAddress] = i;
} else {
lastRewardClaimed[_memberAddress] = lastClaimed;
}
if (j > 0) {
emit RewardClaimed(
_memberAddress,
pendingDAppReward
);
}
}
/**
* @dev Sets delegation acceptance status of individual user
* @param _status delegation acceptance status
*/
function setDelegationStatus(bool _status) external isMemberAndcheckPause checkPendingRewards {
isOpenForDelegation[msg.sender] = _status;
}
/**
* @dev Delegates vote to an address.
* @param _add is the address to delegate vote to.
*/
function delegateVote(address _add) external isMemberAndcheckPause checkPendingRewards {
require(ms.masterInitialized());
require(allDelegation[followerDelegation[_add]].leader == address(0));
if (followerDelegation[msg.sender] > 0) {
require((allDelegation[followerDelegation[msg.sender]].lastUpd).add(tokenHoldingTime) < now);
}
require(!alreadyDelegated(msg.sender));
require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.Owner)));
require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)));
require(followerCount[_add] < maxFollowers);
if (allVotesByMember[msg.sender].length > 0) {
require((allVotes[allVotesByMember[msg.sender][allVotesByMember[msg.sender].length - 1]].dateAdd).add(tokenHoldingTime)
< now);
}
require(ms.isMember(_add));
require(isOpenForDelegation[_add]);
allDelegation.push(DelegateVote(msg.sender, _add, now));
followerDelegation[msg.sender] = allDelegation.length - 1;
leaderDelegation[_add].push(allDelegation.length - 1);
followerCount[_add]++;
lastRewardClaimed[msg.sender] = allVotesByMember[_add].length;
}
/**
* @dev Undelegates the sender
*/
function unDelegate() external isMemberAndcheckPause checkPendingRewards {
_unDelegate(msg.sender);
}
/**
* @dev Triggers action of accepted proposal after waiting time is finished
*/
function triggerAction(uint _proposalId) external {
require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted) && proposalExecutionTime[_proposalId] <= now, "Cannot trigger");
_triggerAction(_proposalId, allProposalData[_proposalId].category);
}
/**
* @dev Provides option to Advisory board member to reject proposal action execution within actionWaitingTime, if found suspicious
*/
function rejectAction(uint _proposalId) external {
require(memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && proposalExecutionTime[_proposalId] > now);
require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted));
require(!proposalRejectedByAB[_proposalId][msg.sender]);
require(
keccak256(proposalCategory.categoryActionHashes(allProposalData[_proposalId].category))
!= keccak256(abi.encodeWithSignature("swapABMember(address,address)"))
);
proposalRejectedByAB[_proposalId][msg.sender] = true;
actionRejectedCount[_proposalId]++;
emit ActionRejected(_proposalId, msg.sender);
if (actionRejectedCount[_proposalId] == AB_MAJ_TO_REJECT_ACTION) {
proposalActionStatus[_proposalId] = uint(ActionStatus.Rejected);
}
}
/**
* @dev Sets intial actionWaitingTime value
* To be called after governance implementation has been updated
*/
function setInitialActionParameters() external onlyOwner {
require(!actionParamsInitialised);
actionParamsInitialised = true;
actionWaitingTime = 24 * 1 hours;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) {
codeVal = code;
if (code == "GOVHOLD") {
val = tokenHoldingTime / (1 days);
} else if (code == "MAXFOL") {
val = maxFollowers;
} else if (code == "MAXDRFT") {
val = maxDraftTime / (1 days);
} else if (code == "EPTIME") {
val = ms.pauseTime() / (1 days);
} else if (code == "ACWT") {
val = actionWaitingTime / (1 hours);
}
}
/**
* @dev Gets all details of a propsal
* @param _proposalId whose details we want
* @return proposalId
* @return category
* @return status
* @return finalVerdict
* @return totalReward
*/
function proposal(uint _proposalId)
external
view
returns(
uint proposalId,
uint category,
uint status,
uint finalVerdict,
uint totalRewar
)
{
return(
_proposalId,
allProposalData[_proposalId].category,
allProposalData[_proposalId].propStatus,
allProposalData[_proposalId].finalVerdict,
allProposalData[_proposalId].commonIncentive
);
}
/**
* @dev Gets some details of a propsal
* @param _proposalId whose details we want
* @return proposalId
* @return number of all proposal solutions
* @return amount of votes
*/
function proposalDetails(uint _proposalId) external view returns(uint, uint, uint) {
return(
_proposalId,
allProposalSolutions[_proposalId].length,
proposalVoteTally[_proposalId].voters
);
}
/**
* @dev Gets solution action on a proposal
* @param _proposalId whose details we want
* @param _solution whose details we want
* @return action of a solution on a proposal
*/
function getSolutionAction(uint _proposalId, uint _solution) external view returns(uint, bytes memory) {
return (
_solution,
allProposalSolutions[_proposalId][_solution]
);
}
/**
* @dev Gets length of propsal
* @return length of propsal
*/
function getProposalLength() external view returns(uint) {
return totalProposals;
}
/**
* @dev Get followers of an address
* @return get followers of an address
*/
function getFollowers(address _add) external view returns(uint[] memory) {
return leaderDelegation[_add];
}
/**
* @dev Gets pending rewards of a member
* @param _memberAddress in concern
* @return amount of pending reward
*/
function getPendingReward(address _memberAddress)
public view returns(uint pendingDAppReward)
{
uint delegationId = followerDelegation[_memberAddress];
address leader;
uint lastUpd;
DelegateVote memory delegationData = allDelegation[delegationId];
if (delegationId > 0 && delegationData.leader != address(0)) {
leader = delegationData.leader;
lastUpd = delegationData.lastUpd;
} else
leader = _memberAddress;
uint proposalId;
for (uint i = lastRewardClaimed[_memberAddress]; i < allVotesByMember[leader].length; i++) {
if (allVotes[allVotesByMember[leader][i]].dateAdd > (
lastUpd.add(tokenHoldingTime)) || leader == _memberAddress) {
if (!rewardClaimed[allVotesByMember[leader][i]][_memberAddress]) {
proposalId = allVotes[allVotesByMember[leader][i]].proposalId;
if (proposalVoteTally[proposalId].voters > 0 && allProposalData[proposalId].propStatus
> uint(ProposalStatus.VotingStarted)) {
pendingDAppReward = pendingDAppReward.add(
allProposalData[proposalId].commonIncentive.div(
proposalVoteTally[proposalId].voters
)
);
}
}
}
}
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "GOVHOLD") {
tokenHoldingTime = val * 1 days;
} else if (code == "MAXFOL") {
maxFollowers = val;
} else if (code == "MAXDRFT") {
maxDraftTime = val * 1 days;
} else if (code == "EPTIME") {
ms.updatePauseTime(val * 1 days);
} else if (code == "ACWT") {
actionWaitingTime = val * 1 hours;
} else {
revert("Invalid code");
}
}
/**
* @dev Updates all dependency addresses to latest ones from Master
*/
function changeDependentContractAddress() public {
tokenInstance = TokenController(ms.dAppLocker());
memberRole = MemberRoles(ms.getLatestAddress("MR"));
proposalCategory = ProposalCategory(ms.getLatestAddress("PC"));
}
/**
* @dev Checks if msg.sender is allowed to create a proposal under given category
*/
function allowedToCreateProposal(uint category) public view returns(bool check) {
if (category == 0)
return true;
uint[] memory mrAllowed;
(, , , , mrAllowed, , ) = proposalCategory.category(category);
for (uint i = 0; i < mrAllowed.length; i++) {
if (mrAllowed[i] == 0 || memberRole.checkRole(msg.sender, mrAllowed[i]))
return true;
}
}
/**
* @dev Checks if an address is already delegated
* @param _add in concern
* @return bool value if the address is delegated or not
*/
function alreadyDelegated(address _add) public view returns(bool delegated) {
for (uint i=0; i < leaderDelegation[_add].length; i++) {
if (allDelegation[leaderDelegation[_add][i]].leader == _add) {
return true;
}
}
}
/**
* @dev Pauses a proposal
* To implement govblocks interface
*/
function pauseProposal(uint) public {
}
/**
* @dev Resumes a proposal
* To implement govblocks interface
*/
function resumeProposal(uint) public {
}
/**
* @dev Checks If the proposal voting time is up and it's ready to close
* i.e. Closevalue is 1 if proposal is ready to be closed, 2 if already closed, 0 otherwise!
* @param _proposalId Proposal id to which closing value is being checked
*/
function canCloseProposal(uint _proposalId)
public
view
returns(uint)
{
uint dateUpdate;
uint pStatus;
uint _closingTime;
uint _roleId;
uint majority;
pStatus = allProposalData[_proposalId].propStatus;
dateUpdate = allProposalData[_proposalId].dateUpd;
(, _roleId, majority, , , _closingTime, ) = proposalCategory.category(allProposalData[_proposalId].category);
if (
pStatus == uint(ProposalStatus.VotingStarted)
) {
uint numberOfMembers = memberRole.numberOfMembers(_roleId);
if (_roleId == uint(MemberRoles.Role.AdvisoryBoard)) {
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority
|| proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0]) == numberOfMembers
|| dateUpdate.add(_closingTime) <= now) {
return 1;
}
} else {
if (numberOfMembers == proposalVoteTally[_proposalId].voters
|| dateUpdate.add(_closingTime) <= now)
return 1;
}
} else if (pStatus > uint(ProposalStatus.VotingStarted)) {
return 2;
} else {
return 0;
}
}
/**
* @dev Gets Id of member role allowed to categorize the proposal
* @return roleId allowed to categorize the proposal
*/
function allowedToCatgorize() public view returns(uint roleId) {
return roleIdAllowedToCatgorize;
}
/**
* @dev Gets vote tally data
* @param _proposalId in concern
* @param _solution of a proposal id
* @return member vote value
* @return advisory board vote value
* @return amount of votes
*/
function voteTallyData(uint _proposalId, uint _solution) public view returns(uint, uint, uint) {
return (proposalVoteTally[_proposalId].memberVoteValue[_solution],
proposalVoteTally[_proposalId].abVoteValue[_solution], proposalVoteTally[_proposalId].voters);
}
/**
* @dev Internal call to create proposal
* @param _proposalTitle of proposal
* @param _proposalSD is short description of proposal
* @param _proposalDescHash IPFS hash value of propsal
* @param _categoryId of proposal
*/
function _createProposal(
string memory _proposalTitle,
string memory _proposalSD,
string memory _proposalDescHash,
uint _categoryId
)
internal
{
require(proposalCategory.categoryABReq(_categoryId) == 0 || _categoryId == 0);
uint _proposalId = totalProposals;
allProposalData[_proposalId].owner = msg.sender;
allProposalData[_proposalId].dateUpd = now;
allProposalSolutions[_proposalId].push("");
totalProposals++;
emit Proposal(
msg.sender,
_proposalId,
now,
_proposalTitle,
_proposalSD,
_proposalDescHash
);
if (_categoryId > 0)
_categorizeProposal(_proposalId, _categoryId, 0);
}
/**
* @dev Internal call to categorize a proposal
* @param _proposalId of proposal
* @param _categoryId of proposal
* @param _incentive is commonIncentive
*/
function _categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentive
)
internal
{
require(
_categoryId > 0 && _categoryId < proposalCategory.totalCategories(),
"Invalid category"
);
allProposalData[_proposalId].category = _categoryId;
allProposalData[_proposalId].commonIncentive = _incentive;
allProposalData[_proposalId].propStatus = uint(ProposalStatus.AwaitingSolution);
emit ProposalCategorized(_proposalId, msg.sender, _categoryId);
}
/**
* @dev Internal call to add solution to a proposal
* @param _proposalId in concern
* @param _action on that solution
* @param _solutionHash string value
*/
function _addSolution(uint _proposalId, bytes memory _action, string memory _solutionHash)
internal
{
allProposalSolutions[_proposalId].push(_action);
emit Solution(_proposalId, msg.sender, allProposalSolutions[_proposalId].length - 1, _solutionHash, now);
}
/**
* @dev Internal call to add solution and open proposal for voting
*/
function _proposalSubmission(
uint _proposalId,
string memory _solutionHash,
bytes memory _action
)
internal
{
uint _categoryId = allProposalData[_proposalId].category;
if (proposalCategory.categoryActionHashes(_categoryId).length == 0) {
require(keccak256(_action) == keccak256(""));
proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction);
}
_addSolution(
_proposalId,
_action,
_solutionHash
);
_updateProposalStatus(_proposalId, uint(ProposalStatus.VotingStarted));
(, , , , , uint closingTime, ) = proposalCategory.category(_categoryId);
emit CloseProposalOnTime(_proposalId, closingTime.add(now));
}
/**
* @dev Internal call to submit vote
* @param _proposalId of proposal in concern
* @param _solution for that proposal
*/
function _submitVote(uint _proposalId, uint _solution) internal {
uint delegationId = followerDelegation[msg.sender];
uint mrSequence;
uint majority;
uint closingTime;
(, mrSequence, majority, , , closingTime, ) = proposalCategory.category(allProposalData[_proposalId].category);
require(allProposalData[_proposalId].dateUpd.add(closingTime) > now, "Closed");
require(memberProposalVote[msg.sender][_proposalId] == 0, "Not allowed");
require((delegationId == 0) || (delegationId > 0 && allDelegation[delegationId].leader == address(0) &&
_checkLastUpd(allDelegation[delegationId].lastUpd)));
require(memberRole.checkRole(msg.sender, mrSequence), "Not Authorized");
uint totalVotes = allVotes.length;
allVotesByMember[msg.sender].push(totalVotes);
memberProposalVote[msg.sender][_proposalId] = totalVotes;
allVotes.push(ProposalVote(msg.sender, _proposalId, now));
emit Vote(msg.sender, _proposalId, totalVotes, now, _solution);
if (mrSequence == uint(MemberRoles.Role.Owner)) {
if (_solution == 1)
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), allProposalData[_proposalId].category, 1, MemberRoles.Role.Owner);
else
_updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected));
} else {
uint numberOfMembers = memberRole.numberOfMembers(mrSequence);
_setVoteTally(_proposalId, _solution, mrSequence);
if (mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) {
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers)
>= majority
|| (proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0])) == numberOfMembers) {
emit VoteCast(_proposalId);
}
} else {
if (numberOfMembers == proposalVoteTally[_proposalId].voters)
emit VoteCast(_proposalId);
}
}
}
/**
* @dev Internal call to set vote tally of a proposal
* @param _proposalId of proposal in concern
* @param _solution of proposal in concern
* @param mrSequence number of members for a role
*/
function _setVoteTally(uint _proposalId, uint _solution, uint mrSequence) internal
{
uint categoryABReq;
uint isSpecialResolution;
(, categoryABReq, isSpecialResolution) = proposalCategory.categoryExtendedData(allProposalData[_proposalId].category);
if (memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && (categoryABReq > 0) ||
mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) {
proposalVoteTally[_proposalId].abVoteValue[_solution]++;
}
tokenInstance.lockForMemberVote(msg.sender, tokenHoldingTime);
if (mrSequence != uint(MemberRoles.Role.AdvisoryBoard)) {
uint voteWeight;
uint voters = 1;
uint tokenBalance = tokenInstance.totalBalanceOf(msg.sender);
uint totalSupply = tokenInstance.totalSupply();
if (isSpecialResolution == 1) {
voteWeight = tokenBalance.add(10**18);
} else {
voteWeight = (_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10**18);
}
DelegateVote memory delegationData;
for (uint i = 0; i < leaderDelegation[msg.sender].length; i++) {
delegationData = allDelegation[leaderDelegation[msg.sender][i]];
if (delegationData.leader == msg.sender &&
_checkLastUpd(delegationData.lastUpd)) {
if (memberRole.checkRole(delegationData.follower, mrSequence)) {
tokenBalance = tokenInstance.totalBalanceOf(delegationData.follower);
tokenInstance.lockForMemberVote(delegationData.follower, tokenHoldingTime);
voters++;
if (isSpecialResolution == 1) {
voteWeight = voteWeight.add(tokenBalance.add(10**18));
} else {
voteWeight = voteWeight.add((_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10**18));
}
}
}
}
proposalVoteTally[_proposalId].memberVoteValue[_solution] = proposalVoteTally[_proposalId].memberVoteValue[_solution].add(voteWeight);
proposalVoteTally[_proposalId].voters = proposalVoteTally[_proposalId].voters + voters;
}
}
/**
* @dev Gets minimum of two numbers
* @param a one of the two numbers
* @param b one of the two numbers
* @return minimum number out of the two
*/
function _minOf(uint a, uint b) internal pure returns(uint res) {
res = a;
if (res > b)
res = b;
}
/**
* @dev Check the time since last update has exceeded token holding time or not
* @param _lastUpd is last update time
* @return the bool which tells if the time since last update has exceeded token holding time or not
*/
function _checkLastUpd(uint _lastUpd) internal view returns(bool) {
return (now - _lastUpd) > tokenHoldingTime;
}
/**
* @dev Checks if the vote count against any solution passes the threshold value or not.
*/
function _checkForThreshold(uint _proposalId, uint _category) internal view returns(bool check) {
uint categoryQuorumPerc;
uint roleAuthorized;
(, roleAuthorized, , categoryQuorumPerc, , , ) = proposalCategory.category(_category);
check = ((proposalVoteTally[_proposalId].memberVoteValue[0]
.add(proposalVoteTally[_proposalId].memberVoteValue[1]))
.mul(100))
.div(
tokenInstance.totalSupply().add(
memberRole.numberOfMembers(roleAuthorized).mul(10 ** 18)
)
) >= categoryQuorumPerc;
}
/**
* @dev Called when vote majority is reached
* @param _proposalId of proposal in concern
* @param _status of proposal in concern
* @param category of proposal in concern
* @param max vote value of proposal in concern
*/
function _callIfMajReached(uint _proposalId, uint _status, uint category, uint max, MemberRoles.Role role) internal {
allProposalData[_proposalId].finalVerdict = max;
_updateProposalStatus(_proposalId, _status);
emit ProposalAccepted(_proposalId);
if (proposalActionStatus[_proposalId] != uint(ActionStatus.NoAction)) {
if (role == MemberRoles.Role.AdvisoryBoard) {
_triggerAction(_proposalId, category);
} else {
proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted);
proposalExecutionTime[_proposalId] = actionWaitingTime.add(now);
}
}
}
/**
* @dev Internal function to trigger action of accepted proposal
*/
function _triggerAction(uint _proposalId, uint _categoryId) internal {
proposalActionStatus[_proposalId] = uint(ActionStatus.Executed);
bytes2 contractName;
address actionAddress;
bytes memory _functionHash;
(, actionAddress, contractName, , _functionHash) = proposalCategory.categoryActionDetails(_categoryId);
if (contractName == "MS") {
actionAddress = address(ms);
} else if (contractName != "EX") {
actionAddress = ms.getLatestAddress(contractName);
}
(bool actionStatus, ) = actionAddress.call(abi.encodePacked(_functionHash, allProposalSolutions[_proposalId][1]));
if (actionStatus) {
emit ActionSuccess(_proposalId);
} else {
proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted);
emit ActionFailed(_proposalId);
}
}
/**
* @dev Internal call to update proposal status
* @param _proposalId of proposal in concern
* @param _status of proposal to set
*/
function _updateProposalStatus(uint _proposalId, uint _status) internal {
if (_status == uint(ProposalStatus.Rejected) || _status == uint(ProposalStatus.Denied)) {
proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction);
}
allProposalData[_proposalId].dateUpd = now;
allProposalData[_proposalId].propStatus = _status;
}
/**
* @dev Internal call to undelegate a follower
* @param _follower is address of follower to undelegate
*/
function _unDelegate(address _follower) internal {
uint followerId = followerDelegation[_follower];
if (followerId > 0) {
followerCount[allDelegation[followerId].leader] = followerCount[allDelegation[followerId].leader].sub(1);
allDelegation[followerId].leader = address(0);
allDelegation[followerId].lastUpd = now;
lastRewardClaimed[_follower] = allVotesByMember[_follower].length;
}
}
/**
* @dev Internal call to close member voting
* @param _proposalId of proposal in concern
* @param category of proposal in concern
*/
function _closeMemberVote(uint _proposalId, uint category) internal {
uint isSpecialResolution;
uint abMaj;
(, abMaj, isSpecialResolution) = proposalCategory.categoryExtendedData(category);
if (isSpecialResolution == 1) {
uint acceptedVotePerc = proposalVoteTally[_proposalId].memberVoteValue[1].mul(100)
.div(
tokenInstance.totalSupply().add(
memberRole.numberOfMembers(uint(MemberRoles.Role.Member)).mul(10**18)
));
if (acceptedVotePerc >= specialResolutionMajPerc) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
} else {
if (_checkForThreshold(_proposalId, category)) {
uint majorityVote;
(, , majorityVote, , , , ) = proposalCategory.category(category);
if (
((proposalVoteTally[_proposalId].memberVoteValue[1].mul(100))
.div(proposalVoteTally[_proposalId].memberVoteValue[0]
.add(proposalVoteTally[_proposalId].memberVoteValue[1])
))
>= majorityVote
) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected));
}
} else {
if (abMaj > 0 && proposalVoteTally[_proposalId].abVoteValue[1].mul(100)
.div(memberRole.numberOfMembers(uint(MemberRoles.Role.AdvisoryBoard))) >= abMaj) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
}
}
if (proposalVoteTally[_proposalId].voters > 0) {
tokenInstance.mint(ms.getLatestAddress("CR"), allProposalData[_proposalId].commonIncentive);
}
}
/**
* @dev Internal call to close advisory board voting
* @param _proposalId of proposal in concern
* @param category of proposal in concern
*/
function _closeAdvisoryBoardVote(uint _proposalId, uint category) internal {
uint _majorityVote;
MemberRoles.Role _roleId = MemberRoles.Role.AdvisoryBoard;
(, , _majorityVote, , , , ) = proposalCategory.category(category);
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100)
.div(memberRole.numberOfMembers(uint(_roleId))) >= _majorityVote) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, _roleId);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
}
}
|
Provides details of a holded cover Id _hcid holded cover Id return scAddress SmartCover address of cover. return coverCurr currency of cover. return coverPeriod Cover Period of cover (in days).
|
function getHoldedCoverDetailsByID1(
uint _hcid
)
external
view
returns (
uint hcid,
address scAddress,
bytes4 coverCurr,
uint16 coverPeriod
)
{
return (
_hcid,
allCoverHolded[_hcid].scAddress,
allCoverHolded[_hcid].coverCurr,
allCoverHolded[_hcid].coverPeriod
);
}
| 7,286,913 |
./full_match/80001/0x7634F67cB9C73cC924E499044310B1f902F321E8/sources/project_/contracts/Limits.sol
|
After calling this function the {_defaultSecondaryTradingLimit} will apply to addresses from array `_accountsToReset` instead of there {individualSecondaryTradingLimit} (if they had it) Allowed only for ComplianceOfficer. _accountsToReset array of addresses to reset limit to default
|
function resetSecondaryTradingLimitToDefault(
address[] calldata _accountsToReset
) external ifTokenNotPaused onlyComplianceOfficer {
for (uint256 i = 0; i < _accountsToReset.length; i++) {
userData[_accountsToReset[i]].hasOwnSecondaryLimit = false;
}
}
| 5,603,842 |
// pragma solidity ^0.4.25;
pragma solidity ^0.8.0;
// It's important to avoid vulnerabilities due to numeric overflow bugs
// OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs
// More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/
import "../node_modules/openzeppelin-solidity/contracts/utils/math/SafeMath.sol";
import "./FlightSuretyData.sol"; // this is not required since interface is defined at the end of this file for reference.
/************************************************** */
/* FlightSurety Smart Contract */
/************************************************** */
contract FlightSuretyApp {
using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript)
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
// operational flag
bool private operational = true;
// registration fee
uint256 public constant registrationFee = 10 ether;
uint16 public constant PAYOUT_PERCENT = 150;
// Flight status codes. For status codes 20, 40, 50 airline pays out to the insured customer.
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
address private contractOwner; // Account used to deploy contract
// reference to Data Contract
FlightSuretyData private flightSuretyData;
/**** moved to Data Contract
struct Flight {
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
}
mapping(bytes32 => Flight) private flights;
***************/
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
// Modify to call data contract's status
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
modifier requireRegisteredAirline() {
require(flightSuretyData.isAirlineRegistered(msg.sender),"Invalid caller - not registered");
_;
}
/*****
modifier requireRegisteredAndPaidAirline() {
require(flightSuretyData.isAirlineRegisteredAndPaid(msg.sender),"Invalid caller - not registerede and paid");
_;
}
*******/
modifier requireFlightNotRegistered(string memory flightId, address airline, uint256 timestamp) {
string memory rflightId;
uint256 flightTime;
address airlineAddress;
bool isRegistered;
uint8 statusCode;
bytes32 flightKey = getFlightKey(airline, flightId, timestamp);
(rflightId, airlineAddress, flightTime, isRegistered, statusCode) =
flightSuretyData.getFlight(flightKey);
require(!isRegistered, "Flight already registered");
_;
}
modifier requireFlightRegistered(string memory flightId, address airline, uint256 timestamp) {
string memory rflightId;
uint256 flightTime;
address airlineAddress;
bool isRegistered;
uint8 statusCode;
bytes32 flightKey = getFlightKey(airline, flightId, timestamp);
(rflightId, airlineAddress, flightTime, isRegistered, statusCode) =
flightSuretyData.getFlight(flightKey);
require(isRegistered, "Flight not registered for insurance purchase");
_;
}
modifier requireNotPaid() {
address airlineAddress;
string memory airlineName;
bool regPaid;
bool isReg;
uint256 paidAmt;
(airlineAddress, airlineName, regPaid, paidAmt, isReg) = flightSuretyData.getAirline(msg.sender);
require(regPaid == false, "Registration has been paid");
_;
}
modifier requireRegAmount() {
require(msg.value >= 1, "Minimum of 1 ether required for registration amount");
_;
}
modifier requireCustomerNotPaid(string memory flightId, address airline, uint256 flightTime) {
bytes32 flightKey = getFlightKey(airline, flightId, flightTime);
require(!flightSuretyData.hasCustomerPaid(msg.sender, flightKey));
_;
}
/********************************************************************************************/
/* CONSTRUCTOR */
/********************************************************************************************/
/**
* @dev Contract constructor
*
*/
constructor(address _flightSuretyData, address firstAirline)
{
contractOwner = msg.sender;
flightSuretyData = FlightSuretyData(payable(_flightSuretyData));
// flightSuretyData.authorizeContract(address(this));
// flightSuretyData.authorizeContract(firstAirline); // done from deployment script
// flightSuretyData.registerAirline(firstAirline); // done from deployment script
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
function isOperational()
public
view
returns(bool)
{
return operational; // Modify to call data contract's status
}
function setOperatingStatus
(
bool mode
)
external
requireContractOwner
{
operational = mode;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
// Airline making payment for registration. This method accepts payment from airlines for
// registration. This is a prerequisite for registration. Until airlines have paid, other
// airline cannot propose to register an airline.
function makeRegPayment(string memory airlineName) requireIsOperational
requireNotPaid
requireRegAmount
external
payable
{
uint256 paidAmount = msg.value;
// registration amount required is 1 ether. Return excess value
uint256 surplus = paidAmount - registrationFee;
// change state (effects)
bool regPaid = true;
flightSuretyData.acceptPayment{value: msg.value}(msg.sender, registrationFee, airlineName,regPaid);
// do interaction
payable(msg.sender).transfer(surplus);
}
/**
* @dev Add an airline to the registration queue
*
*/
function registerAirline(address airline) requireIsOperational requireRegisteredAirline external
// returns(bool success, uint256 votes)
{
if (!flightSuretyData.isAirlineRegistered(airline))
{
// check the number of alirline registered
if (flightSuretyData.getRegisteredAirlines().length < 4)
{
// register the airline
flightSuretyData.registerAirline(airline);
}
else
{
// reg airline count is >=4, put it in reg queue
// if 50% of vote is there, then register the airline
if (!flightSuretyData.hasSenderVoted(msg.sender, airline))
{
// add the votef
flightSuretyData.addVote(msg.sender, airline);
// get the number of votes. if > 50% of reg airlines, register the airline
uint voteCount = flightSuretyData.getVotes(airline).length;
uint regAirlineCount = flightSuretyData.getRegisteredAirlines().length;
// if (voteCount >= regAirlineCount/2) {
if ((voteCount*100)/regAirlineCount >= 50) {
// register the airline. All conditions are satisfied
flightSuretyData.registerAirline(airline);
// TODO: clean (delete) the reg queue for the airline
}
}
}
}
// return (success, 0);
}
function isAirlineRegistered(address airline) requireRegisteredAirline view external returns(bool)
{
return flightSuretyData.isAirlineRegistered(airline);
}
function getRegisteredAirlines() requireRegisteredAirline view external returns(address[] memory)
{
return flightSuretyData.getRegisteredAirlines();
}
/**
* @dev Register a future flight for insuring.
*
*/
function registerFlight (string memory flightId, uint256 flightTime)
requireIsOperational
requireRegisteredAirline
requireFlightNotRegistered(flightId, msg.sender, flightTime)
external
{
address airlineAddress = msg.sender;
flightSuretyData.registerFlight(airlineAddress, flightId, flightTime);
}
// purchase insurance for a flight. Customers call this method to purchase flight insurance
function purchaseFlightInsurance(string memory flightId,
address airline,
uint256 flightTime)
requireIsOperational
// requireCustomerNotPaid(flightId, airline, flightTime)
requireFlightRegistered(flightId, airline, flightTime)
external
payable
{
bytes32 flightKey = getFlightKey(airline, flightId, flightTime);
flightSuretyData.buy{value: msg.value}(flightKey, msg.sender, msg.value);
// flightSuretyData.buy{value: msg.value}(getFlightKey(airline, flightId, flightTime), msg.sender, msg.value);
}
/**
* @dev Called after oracle has updated flight status. TODO: Determine the payouts if the flight was delayed
*
*/
function processFlightStatus
(
bytes32 requestKey,
uint8 statusCode
)
internal
{
uint256 premiumAmt;
uint256 payoutAmt;
// check if status code is 20, 40 or 50.
// For these status codes, payout needds to happen to the customer.
// payout is 1.5 times.
// fetch the customers who has insured for the flight.
// multiply the paid amout by 1.5 and transfer ether from data contract to customer
if (statusCode == 20 || statusCode == 40 || statusCode == 50) {
// get insured customer list
address[] memory insuredCustomers = flightSuretyData.getInsuredCustomers(requestKey);
// get the customer premium for each insured customer and make payment
for (uint8 i; i< insuredCustomers.length; i++) {
premiumAmt = flightSuretyData.getCustomerPremium(insuredCustomers[i], requestKey);
payoutAmt = (premiumAmt * PAYOUT_PERCENT)/100;
flightSuretyData.makePayout(insuredCustomers[i],payoutAmt);
}
}
}
// Generate a request for oracles to fetch flight information
function fetchFlightStatus
(
address airline,
string memory flight,
uint256 timestamp
)
external
returns(bytes32)
{
uint8 index = getRandomIndex(msg.sender);
// Generate a unique key for storing the request
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
// my addtion to fix the compile problem
/**** Gopi commented outto replance it idfferently for solidity v > 0.7.0
oracleResponses[key] = ResponseInfo({
requester: msg.sender,
isOpen: true,
responses: newResponses
});
*/
// for solidity v0.7.0 and greater
// initialize ResponseInfof for the request
flightSuretyData.initializeRespInfo(key, msg.sender, index);
/****** moved to Data str
ResponseInfo storage newResponseInfo = oracleResponses[key];
newResponseInfo.requester = msg.sender;
newResponseInfo.isOpen = true;
****** */
emit OracleRequest(index, airline, flight, timestamp);
return key;
}
// region ORACLE MANAGEMENT
// Incremented to add pseudo-randomness at various points
uint8 private nonce = 0;
// Fee to be paid when registering oracle
uint256 public constant REGISTRATION_FEE = 1 ether;
// Number of oracles that must respond for valid status
uint256 private constant MIN_RESPONSES = 3;
/**** data structures moved from here to Data Contract */
// Event fired each time an oracle submits a response
event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status);
event OracleReport(address airline, string flight, uint256 timestamp, uint8 status);
event InsuredCustomers(address[] insuredCustomers);
event RespEventCode(uint8 statusCode);
// Event fired when flight status request is submitted
// Oracles track this and if they have a matching index
// they fetch data and submit a response
event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp);
modifier requireRegFee()
{
string memory messag = "Caller did not send registration fee of ";
string memory regFee = string(abi.encodePacked(bytes32(REGISTRATION_FEE)));
require(msg.value >= REGISTRATION_FEE, string(abi.encodePacked(messag, regFee)));
_;
}
// Register an oracle with the contract.
function registerOracle
(
)
external
payable
requireRegFee
{
// Require registration fee. Below line commented out. Functionality moved to modifier
// require(msg.value >= REGISTRATION_FEE, "Registration fee is required");
uint8[] memory indexes = generateIndexes(msg.sender);
flightSuretyData.registerOracle{value: msg.value}(msg.sender, indexes);
/**** moved to Data Contract
oracles[msg.sender] = Oracle({
isRegistered: true,
indexes: indexes
});
**** moved to data contract *****/
}
// Obtain indexes for the given oracle
function getOracle
(
address account
)
public
view
returns(uint8[] memory)
{
require(flightSuretyData.isOracleRegistered(account), "Oracle not registered");
return flightSuretyData.getOracleIndexes(account);
}
function getMyIndexes
(
)
view
public
returns(uint8[] memory)
{
// require(oracles[msg.sender].isRegistered, "Not registered as an oracle");
require(flightSuretyData.isOracleRegistered(msg.sender), "Oracle not registered");
// return oracles[msg.sender].indexes; // moved to Data contract
return flightSuretyData.getOracleIndexes(msg.sender);
}
// Called by oracle when a response is available to an outstanding request
// For the response to be accepted, there must be a pending request that is open
// and matches one of the three Indexes randomly assigned to the oracle at the
// time of registration (i.e. uninvited oracles are not welcome)
function submitOracleResponse
(
uint8 index,
address airline,
string memory flight,
uint256 timestamp,
uint8 statusCode
)
external
{
uint8[] memory orclIndexes = getOracle(msg.sender);
require((orclIndexes[0] == index) || (orclIndexes[1] == index) || (orclIndexes[2] == index), "Index does not match oracle request");
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
// ensure the index receives is the same as the index associated with the flight status request
uint8 reqIndex = flightSuretyData.getRequestIndex(key);
// require(oracleResponses[key].index == index, "index received is not the index in flight status request");
require(reqIndex == index, "index received is not the index in flight status request");
bool reqOpen = flightSuretyData.isRequestOpen(key); // should be either open or close . If close do nothing
require(reqOpen,"No longer open for response");
// add the oracle's response
flightSuretyData.addOrclResponse(key, msg.sender, statusCode);
// oracleResponses[key].responses[statusCode].push(msg.sender); // moved to Data Contract
// emit an event for each valid response received.
emit OracleReport(airline, flight, timestamp, statusCode);
// Information isn't considered verified until at least MIN_RESPONSES
// oracles respond with the *** same *** information
address[] memory orclResponses = flightSuretyData.getOrclResponses(key, statusCode);
if (orclResponses.length >= MIN_RESPONSES) {
// close the request
flightSuretyData.closeOrclResponse(key); // close the request. No further responses will be accepted.
// Handle flight status as appropriate..
// processFlightStatus(key, statusCode); // BUG was here. See the description belowmoved to Data contract
processFlightStatus(getFlightKey(airline, flight, timestamp), statusCode);
// flightSuretyData.creditInsurees(key, statusCode); // THIS WAS THE BUG. WAS HARD TO FIND WITHOUT THE console output in truffle. Used hardhat to identify it.
// flightSuretyData.creditInsurees(getFlightKey(airline, flight, timestamp), statusCode);
}
}
function getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
pure
public
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
// Returns array of three non-duplicating integers from 0-9
function generateIndexes
(
address account
)
internal
returns(uint8[] memory)
{
uint8[] memory indexes = new uint8[](3);
indexes[0] = getRandomIndex(account);
/*
indexes.push(getRandomIndex(account));
indexes.push(getRandomIndex(account));
indexes.push(getRandomIndex(account));
*/
indexes[1] = indexes[0];
while(indexes[1] == indexes[0]) {
indexes[1] = getRandomIndex(account);
}
indexes[2] = indexes[1];
while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) {
indexes[2] = getRandomIndex(account);
}
return indexes;
}
// Returns array of three non-duplicating integers from 0-9
function getRandomIndex
(
address account
)
internal
returns (uint8)
{
uint8 maxValue = 10;
// Pseudo random number...the incrementing nonce adds variation
uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue);
if (nonce > 250) {
nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt
}
if (random == 0) { random = 4;}
return random;
}
// endregion
}
/*
// add reference to FlightData Contract. Similar to itnerface
interface FlightSuretyData {
// add all the public functions here
function registerAirline(address airline) external;
function buy() external payable;
function creditInsurees() external;
function pay() external;
function fund() external payable;
function getFlightKey(address airline, string memory flight, uint256 timestamp) external returns(bytes32);
}
*/
/***** Before refactoring
function submitOracleResponse
(
uint8 index,
address airline,
string memory flight,
uint256 timestamp,
uint8 statusCode
)
external
{
require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request");
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
// ensure the index receives is the same as the index associated with the flight status request
require(oracleResponses[key].index == index, "index received is not the index in flight status request");
require(oracleResponses[key].isOpen,"No longer open for response");
oracleResponses[key].responses[statusCode].push(msg.sender);
// emit an event for each valid response received.
emit OracleReport(airline, flight, timestamp, statusCode);
// Information isn't considered verified until at least MIN_RESPONSES
// oracles respond with the *** same *** information
if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) {
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
oracleResponses[key].isOpen = false; // close the request. No further responses will be accepted.
// Handle flight status as appropriate.. TODO
processFlightStatus(airline, flight, timestamp, statusCode);
}
}
*************** */
|
Register an oracle with the contract. Require registration fee. Below line commented out. Functionality moved to modifier require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); moved to Data Contract
|
function registerOracle
(
)
external
payable
requireRegFee
{
uint8[] memory indexes = generateIndexes(msg.sender);
oracles[msg.sender] = Oracle({
isRegistered: true,
indexes: indexes
});
| 989,297 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "./ICryptoMonks.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
/**
* @dev OSMigration is bridges an Open Sea 1155 into a new 721
*/
contract OSMigration is ERC1155Holder, Ownable, ReentrancyGuard {
/**
* @dev total bridged NFTs
*/
uint32 public totalBridged;
/**
* received NFTs (not yet claimed and transformed into 721)
*/
uint256[] public idsReceived;
/**
* @dev received and successfully claimed (this contains newly 721 ids)
*/
uint16[] public idsBridged;
/**
* @dev in case something goes bad, to stop claiming
*/
bool public bridgingEnabled;
/**
* @dev keeps all the ids that are sent and the owners of them
*/
mapping(uint256 => address) public idsAndSenders;
mapping(address => uint256[]) public sendersAndIds;
/**
* @dev olds OS ids bridged
*/
mapping(address => uint256[]) public oldsIdsBridgedBySender;
bytes32 private merkleRoot;
/**
* @dev OpenSea Shared contract
*/
IERC1155 public osContract;
ICryptoMonks public migContract;
event ReceivedFromOS(address indexed _sender, address indexed _receiver, uint256 indexed _tokenId, uint256 _amount);
event ReceivedFrom721(address indexed _sender, address indexed _receiver, uint256 indexed _tokenId);
event Minted721(address indexed _sender, uint256 indexed _tokenId);
event ToggleBridging(bool _enabled);
event Transferred1155(address indexed _to, uint256 indexed _tokenId);
constructor() {}
/**
* @dev triggered by 1155 transfer only from openSea
*/
function onERC1155Received(
address _sender,
address _receiver,
uint256 _tokenId,
uint256 _amount,
bytes memory _data
) public override nonReentrant returns (bytes4) {
require(msg.sender == address(osContract), "Forbidden");
require(!bridgingEnabled, "Bridging is stopped");
triggerReceived1155(_sender, _tokenId);
emit ReceivedFromOS(_sender, _receiver, _tokenId, _amount);
return super.onERC1155Received(_sender, _receiver, _tokenId, _amount, _data);
}
/***********External**************/
/**
* @dev a user can claim a token based on a merkle proof that was precomputed and that is part of the
* merkleRoot structure
*/
function claim(
uint256 _oldId,
uint16 _newId,
bytes32 _leaf,
bytes32[] calldata _merkleProof
) external nonReentrant {
require(!bridgingEnabled, "Bridging is stopped");
//construct merkle node
bytes32 node = keccak256(abi.encodePacked(_oldId, _newId));
require(node == _leaf, "Leaf not matching the node");
require(MerkleProof.verify(_merkleProof, merkleRoot, _leaf), "Invalid proof.");
require(idsAndSenders[_oldId] == msg.sender, "Not owner of OS id");
totalBridged++;
idsBridged.push(_newId);
oldsIdsBridgedBySender[msg.sender].push(_oldId);
mintOnClaiming(msg.sender, _newId);
}
/**
* @dev owner minting 721
*/
function mint721(uint16 _tokenId, address _to) external onlyOwner {
require(_to != address(0), "Mint to address 0");
require(!migContract.exists(_tokenId), "Token exists");
if (migContract.exists(_tokenId) && migContract.ownerOf(_tokenId) == address(this)) {
migContract.safeTransferFrom(address(this), _to, _tokenId);
return;
}
_mint721(_tokenId, _to);
}
/**
* @dev transfer MIG 721 from bridge in case token gets stuck or someone is sending by mistake
*/
function transfer721(uint256 _tokenId, address _owner) external onlyOwner {
require(_owner != address(0), "Can not send to address 0");
migContract.safeTransferFrom(address(this), _owner, _tokenId);
}
/***********Private**************/
/**
* @dev minting 721 to the owner
*/
function _mint721(uint16 _tokenId, address _owner) private {
migContract.mint(_owner, uint16(_tokenId));
emit Minted721(_owner, _tokenId);
}
/**
* @dev update params once we receive a transfer from 1155
* the sender can not be address(0) and tokenId needs to be allowed
*/
function triggerReceived1155(address _sender, uint256 _tokenId) internal {
require(_sender != address(0), "Update from address 0");
idsReceived.push(_tokenId);
idsAndSenders[_tokenId] = _sender;
sendersAndIds[_sender].push(_tokenId);
}
/**
* @dev when receive token from OS, it mints a 721
*/
function mintOnClaiming(address _sender, uint16 _tokenId) internal returns (bool) {
require(_sender != address(0), "Can not mint to address 0");
require(_tokenId != 0, "New token id !exists");
require(!migContract.exists(_tokenId), "Token already minted");
migContract.mint(_sender, _tokenId);
emit Minted721(_sender, _tokenId);
return true;
}
/***********Setters**************/
/**
* @dev sets 721 token
*/
function setMIGContract(address _contract) external onlyOwner {
require(_contract != address(0), "_contract !address 0");
migContract = ICryptoMonks(_contract);
}
/**
* @dev sets OS token
*/
function setOSContract(address _contract) external onlyOwner {
require(_contract != address(0), "_contract !address 0");
osContract = IERC1155(_contract);
}
/**
* @dev sets merkle root, should be called only once
*/
function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner {
merkleRoot = _merkleRoot;
}
/***********Views**************/
/**
* @dev check a OS token balance
*/
function checkBalance(address _collector, uint256 _tokenId) external view returns (uint256) {
require(_collector != address(0), "_collector is address 0");
return osContract.balanceOf(_collector, _tokenId);
}
/**
* @dev get the ids already transferred by a collector
*/
function getTransferredByCollector(address _collector) external view returns (uint256[] memory) {
require(_collector != address(0), "_collector is address 0");
return sendersAndIds[_collector];
}
/**
* @dev get the ids that were bridged by collector
*/
function getBridgedByCollector(address _collector) external view returns (uint256[] memory) {
require(_collector != address(0), "_collector is address 0");
return oldsIdsBridgedBySender[_collector];
}
/***********Getters**************/
/**
* @dev get merkle root just by the owner
*/
function getMerkleRoot() external view onlyOwner returns (bytes32) {
return merkleRoot;
}
/**
* @dev get total transfer count
*/
function getTokenBridgedCount() external view returns (uint128) {
return totalBridged;
}
/**
* @dev get bridged ids (claimed already), this will be the new 721 ids
*/
function getBridgedTokens() external view returns (uint16[] memory) {
return idsBridged;
}
/**
* @dev get ids of tokens that were transfered to the bridge
*/
function getIdsTransfered() external view returns (uint256[] memory) {
return idsReceived;
}
/**
* @dev get 721 contract address
*/
function getMIGContract() external view returns (address) {
return address(migContract);
}
/**
* @dev get OpenSea contract address
*/
function getOSContract() external view returns (address) {
return address(osContract);
}
/***********Emergency**************/
/**
* @dev transfer MIG 1155 from bridge in case token gets stuck or someone is sending by mistake
*/
function transfer1155(uint256 _tokenId, address _owner) external onlyOwner nonReentrant {
require(_owner != address(0), "Can not send to address 0");
osContract.safeTransferFrom(address(this), _owner, _tokenId, 1, "");
emit Transferred1155(_owner, _tokenId);
}
/**
* @dev can enable/disable claiming and bridging
*/
function toggleBridging(bool _enabled) external onlyOwner {
bridgingEnabled = _enabled;
emit ToggleBridging(_enabled);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC1155Receiver.sol";
import "../../../utils/introspection/ERC165.sol";
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC1155Receiver.sol";
/**
* @dev _Available since v3.1._
*/
contract ERC1155Holder is ERC1155Receiver {
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/*
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::::::::::::;'............,::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::;,''''.............''''';:::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::;;'. .lxxxxxxxxxxxx; .;;:::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::'..',,,,:::::::::::::;,,,,...,::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::;....',;;;;;;;;;;;;;;;;;;;;;;,'...'::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::,.';:coodddddddddddddddddddddddddol:,.';:::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::. .d0000OkkkOKXXXXKXXXXXKK0kkkk0KXXK: .,:::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::;;..'d0KKOo::,cOXXXXXXXXXXXKxc:;;dKXXKc..,;;:::::::::::::::::::::::::::::
::::::::::::::::::::::::::,..;kOKKKKKOkc.;kXXXXXKXXXXXX0Od,.oKXXKOxl. ':::::::::::::::::::::::::::::
::::::::::::::::::::::::'..:lkKXXXXXKKKOxk0XXXXXXXXXXXXKK0xxOXXXKKKd. .:::::::::::::::::::::::::::::
::::::::::::::::::::::::. .d00KXXXXXKXXXXXXXXXXXXXXXXXXXXXXXXXXXXKXx. .:::::::::::::::::::::::::::::
::::::::::::::::::::::::'..:lxKKXXXXXXXXXXXXXXXXXXXXXXXKXXXXXXXXXKXx. .:::::::::::::::::::::::::::::
::::::::::::::::::::::::::,. ;O0KXXXXXXXXXXXXXXXX0OOOOOOOOOOOOOOO0Xx. .:::::::::::::::::::::::::::::
::::::::::::::::::::::::::,. ;O0KXXXXXXXXXXXKKKKKl...............lKx. .:::::::::::::::::::::::::::::
::::::::::::::::::::::::::;,''';x0KXXXXXXXXKOxo;,;::c::ccc::cc:;,,,,'';:::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::. .d00XXXXXXXXK0kxlc;,,,,,,,,,,,,,'.. .,:::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::'..:oxKKXXXXXXXXXXXKo,,''''''',''. ..;:::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::,. ;dk0KKXXXXXXXXXXKKKKKKKKKKOxl. .;:::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::;....'x00KXXXXXXXXXKXXXXXXK0Oc....'::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::;'''',,,''o0KKXXXXXXXXXXXXKKk;'',,'''.';:::::::::::::::::::::::::::::::
::::::::::::::::::::::::::;,'''';::c:,',;lkKKKKKKKKK0KKd:;'';cc::,''',;:::::::::::::::::::::::::::::
::::::::::::::::::::::::::;'.'',;:ccccc,.'okxxkxkxxxkkx:..:cccc::;'''.,:::::::::::::::::::::::::::::
::::::::::::::::::::::;;;;;;;,..',;:cccccccccccccccccccccccccc:,,'..,;;;;;;:::::::::::::::::::::::::
:::::::::::::::::::::;'......','..',;:cccccccccccccccccccccc:;,..','.......,::::::::::::::::::::::::
::::::::::::::::;'......,;;;;::::;,...',;:cc;''''''',:c:;;''...,;:::;;;;,''....',:::::::::::::::::::
::::::::::::::::;.....,;:ccccccccc:,,,,'''',''',,'''',,'.',,,,;cccccccccc:;,....,:::::::::::::::::::
::::::::::::::;;,..',;ccccccccccccccccc;''..';:cc:::,...',:cccccccccccccccc:;,..',;:::::::::::::::::
::::::::::::::,....,ccccccc::cccccccccccc:'.,ccccccc:'.;ccccc:cccccc::ccccccc:.....;::::::::::::::::
::::::::::::::,..'';cccccc:'.',,:cccccccccc:cccccccccc:ccccc;,;:ccc:'.;cccccc:,'...;::::::::::::::::
:::::::::::;'....;:ccccccc:...',:ccccccccccccccccccccccccccc;',:ccc:..,ccccccc::'....,::::::::::::::
:::::::::::;....':cccccccc:...',:ccccccccccccccccccccccccccc:;;;;:c:..,ccccccccc,....,::::::::::::::
:::::::::::;..',;:cccccccc:..',;cccccccccccccccccccccccccccccc:,',:;..,ccccccccc:;,..,::::::::::::::
:::::::::::;..,ccccccccccc:..,cccccccccccccccccccccccccccccccc:;,,''..,:cccccccccc:..,::::::::::::::
:::::::::::;..,ccccccccc:,'..,cccccccccccccccccccccccccccccccccc:;''...,;:cccccccc:..,::::::::::::::
:::::::::::;..,ccccccccc;''..,ccccccccccccccccccccccccccccccccccc;''...',:cccccccc:..,::::::::::::::
:::::::::::;..,ccccccccc;....;ccccccccccccccccccccccccccccccccccc;''....':cccccccc:..,::::::::::::::
:::::::::::;..,ccccccccc,..'';ccccccccccccccccccccccccccccccccccc:,,,'...:cccccccc:..,::::::::::::::
:::::::::::;..,cccccccc:,..'';ccccccccccccccccccccccccccccccccccccc:;,...;cccccccc:..,::::::::::::::
:::::::::::;..,cccccc:;,...',;ccccccccccccccccccccccccccccccccccccccc:,...';cccccc:..,::::::::::::::
:::::::::::;..,cccccc:,'...;:cccccccccccccccccccccccccccccccccccccc:,'.....,;:cccc:..,::::::::::::::
:::::::::::;..'::cccc:'...',;:ccccccccccccccccccccccccccccccccc:;;;,''....',::cccc:..,::::::::::::::
:::::::::::;...,;:ccc:...'''';cccccccccccccccccccccccccccccccc:,''''''...'';cccccc:..,::::::::::::::
crypto monks.
*/
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
abstract contract ICryptoMonks is Ownable, IERC721 {
function mint(address _owner, uint256 _tokenId) external virtual;
function exists(uint256 _tokenId) external view virtual returns (bool);
function getMaxSupply() external virtual returns (uint256);
function tokensOfOwner(address _owner) external view virtual returns (uint256[] memory);
}
|
See {IERC165-supportsInterface}./
|
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
}
| 26,757 |
pragma solidity 0.4.20;
/*=====================================
= [ Proof of GameKyuubi (33.33%) ] =
= https://pogk.surge.sh/ =
= https://discord.gg/ENXNGHc =
=====================================*/
/*
_____ _______ _____ _____
/\ \ /::\ \ /\ \ /\ \
/::\ \ /::::\ \ /::\ \ /::\____\
/::::\ \ /::::::\ \ /::::\ \ /:::/ /
/::::::\ \ /::::::::\ \ /::::::\ \ /:::/ /
/:::/\:::\ \ /:::/~~\:::\ \ /:::/\:::\ \ /:::/ /
/:::/__\:::\ \ /:::/ \:::\ \ /:::/ \:::\ \ /:::/____/
/::::\ \:::\ \ /:::/ / \:::\ \ /:::/ \:::\ \ /::::\ \
/::::::\ \:::\ \ /:::/____/ \:::\____\ /:::/ / \:::\ \ /::::::\____\________
/:::/\:::\ \:::\____\ |:::| | |:::| | /:::/ / \:::\ ___\ /:::/\:::::::::::\ \
/:::/ \:::\ \:::| ||:::|____| |:::| |/:::/____/ ___\:::| |/:::/ |:::::::::::\____\
\::/ \:::\ /:::|____| \:::\ \ /:::/ / \:::\ \ /\ /:::|____|\::/ |::|~~~|~~~~~
\/_____/\:::\/:::/ / \:::\ \ /:::/ / \:::\ /::\ \::/ / \/____|::| |
\::::::/ / \:::\ /:::/ / \:::\ \:::\ \/____/ |::| |
\::::/ / \:::\__/:::/ / \:::\ \:::\____\ |::| |
\::/____/ \::::::::/ / \:::\ /:::/ / |::| |
~~ \::::::/ / \:::\/:::/ / |::| |
\::::/ / \::::::/ / |::| |
\::/____/ \::::/ / \::| |
~~ \::/____/ \:| |
\|___|
* -> Features!
* All the features from all the great Po schemes, with dividend fee 33.33%:
* [x] Highly Secure: Hundreds of thousands of investers of the original PoWH3D, holding tens of thousands of ethers.
* [X] Purchase/Sell: You can perform partial sell orders. If you succumb to weak hands, you don't have to dump all of your bags.
* [x] Purchase/Sell: You can transfer tokens between wallets. Trading is possible from within the contract.
* [x] Masternodes: The implementation of Ethereum Staking in the world.
* [x] Masternodes: Holding 50 PoGK Tokens allow you to generate a Masternode link, Masternode links are used as unique entry points to the contract.
* [x] Masternodes: All players who enter the contract through your Masternode have 30% of their 33.33% dividends fee rerouted from the master-node, to the node-master.
*
* -> Who worked not this project?
* - GameKyuubi (OG HOLD MASTER)
* - Craig Grant from POOH (Marketing)
* - Carlos Matos from N.Y. (Management)
* - Mantso from PoWH 3D (Mathemagic)
*
* -> Owner of contract can:
* - Low Pre-mine (~0.33ETH)
* - And nothing else
*
* -> Owner of contract CANNOT:
* - exit scam
* - kill the contract
* - take funds
* - pause the contract
* - disable withdrawals
* - change the price of tokens
*
* -> THE FOMO IS REAL!! ** https://pogk.surge.sh/ **
*/
contract PoGKHOLD {
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "POGK Future";
string public symbol = "POGK";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 3; // 33.33% Dividends (In & Out)
uint constant internal tokenPriceInitial_ = 0.0000001 ether;
uint constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint constant internal magnitude = 2**64;
// proof of stake (defaults at 50 tokens)
uint public stakingRequirement = 50e18;
/*===============================
= STORAGE =
==============================*/
// amount of shares for each address (scaled number)
mapping(address => uint) internal tokenBalanceLedger_;
mapping(address => uint) internal referralBalance_;
mapping(address => int) internal payoutsTo_;
uint internal tokenSupply_ = 0;
uint internal profitPerShare_;
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint incomingEthereum,
uint tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint tokensBurned,
uint ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint ethereumReinvested,
uint tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint tokens
);
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) public payable returns (uint) {
purchaseTokens(msg.value, _referredBy);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() payable public {
purchaseTokens(msg.value, 0x0);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint _tokens = purchaseTokens(_dividends, 0x0);
// fire event
onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// lambo delivery service
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint _tokens = _amountOfTokens;
uint _ethereum = tokensToEthereum_(_tokens);
uint _dividends = SafeMath.div(_ethereum, dividendFee_);
uint _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int _updatedPayouts = (int) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* @dev Transfer tokens from the caller to a new holder.
* Remember, there's a 33.33% fee here as well.
*/
function transfer(address _toAddress, uint _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// liquify 33.33% of the tokens that are transfered
// these are dispersed to shareholders
uint _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_);
uint _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);
uint _dividends = tokensToEthereum_(_tokenFee);
// burn the fee tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int) (profitPerShare_ * _taxedTokens);
// disperse dividends among holders
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
// fire event
Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint) {
return this.balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint) {
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress) public view returns (uint) {
return (uint) ((int)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the buy price of 1 individual token.
function sellPrice() public view returns (uint) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint _ethereum = tokensToEthereum_(1e18);
uint _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the sell price of 1 individual token.
function buyPrice() public view returns (uint) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint _ethereum = tokensToEthereum_(1e18);
uint _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint _ethereumToSpend) public view returns (uint) {
uint _dividends = SafeMath.div(_ethereumToSpend, dividendFee_);
uint _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint _tokensToSell) public view returns (uint) {
require(_tokensToSell <= tokenSupply_);
uint _ethereum = tokensToEthereum_(_tokensToSell);
uint _dividends = SafeMath.div(_ethereum, dividendFee_);
uint _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint _incomingEthereum, address _referredBy) internal returns (uint) {
// data setup
address _customerAddress = msg.sender;
uint _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_);
uint _referralBonus = SafeMath.div(_undividedDividends, 3);
uint _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
//really i know you think you do but you don't
int _updatedPayouts = (int) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy);
return _amountOfTokens;
}
/**
* Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint _ethereum) internal view returns (uint) {
uint _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint _tokens) internal view returns (uint) {
uint tokens_ = (_tokens + 1e18);
uint _tokenSupply = (tokenSupply_ + 1e18);
uint _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint a, uint b) internal pure 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;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
}
|
Converts all of caller's dividends to tokens. fetch dividends pay out the dividends virtually retrieve ref. bonus dispatch a buy order with the virtualized "withdrawn dividends" fire event
|
function reinvest() onlyStronghands public {
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int) (_dividends * magnitude);
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
uint _tokens = purchaseTokens(_dividends, 0x0);
onReinvestment(_customerAddress, _dividends, _tokens);
}
| 5,850,778 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
/**
* @title Role based set membership.
*
* @notice Encapsulation of tracking, management and validation of role membership of addresses.
*
* A role is a bytes32 value.
*
* There are two distinct classes of roles:
* - Global; without scope limit.
* - Dao; membership scoped to that of the key (uint256).
*
* @dev Meaningful application of role membership is expected to come from derived contracts.
* e.g. access control.
*/
abstract contract RoleMembership is ContextUpgradeable {
// DAOs to their roles to members; scoped to an individual DAO
mapping(uint256 => mapping(bytes32 => mapping(address => bool)))
private _daoRoleMembers;
// Global roles to members; apply across all DAOs
mapping(bytes32 => mapping(address => bool)) private _globalRoleMembers;
event GrantDaoRole(
uint256 indexed daoId,
bytes32 indexed role,
address account,
address indexed instigator
);
event GrantGlobalRole(
bytes32 indexedrole,
address account,
address indexed instigator
);
event RevokeDaoRole(
uint256 indexed daoId,
bytes32 indexed role,
address account,
address indexed instigator
);
event RevokeGlobalRole(
bytes32 indexed role,
address account,
address indexed instigator
);
function hasGlobalRole(bytes32 role, address account)
external
view
returns (bool)
{
return _globalRoleMembers[role][account];
}
function hasDaoRole(
uint256 daoId,
bytes32 role,
address account
) external view returns (bool) {
return _daoRoleMembers[daoId][role][account];
}
function _grantDaoRole(
uint256 daoId,
bytes32 role,
address account
) internal {
if (_hasDaoRole(daoId, role, account)) {
revert(_revertMessageAlreadyHasDaoRole(daoId, role, account));
}
_daoRoleMembers[daoId][role][account] = true;
emit GrantDaoRole(daoId, role, account, _msgSender());
}
function _grantGlobalRole(bytes32 role, address account) internal {
if (_hasGlobalRole(role, account)) {
revert(_revertMessageAlreadyHasGlobalRole(role, account));
}
_globalRoleMembers[role][account] = true;
emit GrantGlobalRole(role, account, _msgSender());
}
function _revokeDaoRole(
uint256 daoId,
bytes32 role,
address account
) internal {
if (_isMissingDaoRole(daoId, role, account)) {
revert(_revertMessageMissingDaoRole(daoId, role, account));
}
delete _daoRoleMembers[daoId][role][account];
emit RevokeDaoRole(daoId, role, account, _msgSender());
}
function _revokeGlobalRole(bytes32 role, address account) internal {
if (_isMissingGlobalRole(role, account)) {
revert(_revertMessageMissingGlobalRole(role, account));
}
delete _globalRoleMembers[role][account];
emit RevokeGlobalRole(role, account, _msgSender());
}
//slither-disable-next-line naming-convention
function __RoleMembership_init() internal onlyInitializing {}
function _hasDaoRole(
uint256 daoId,
bytes32 role,
address account
) internal view returns (bool) {
return _daoRoleMembers[daoId][role][account];
}
function _hasGlobalRole(bytes32 role, address account)
internal
view
returns (bool)
{
return _globalRoleMembers[role][account];
}
function _isMissingDaoRole(
uint256 daoId,
bytes32 role,
address account
) internal view returns (bool) {
return !_daoRoleMembers[daoId][role][account];
}
function _isMissingGlobalRole(bytes32 role, address account)
internal
view
returns (bool)
{
return !_globalRoleMembers[role][account];
}
/**
* @dev Override for a custom revert message.
*/
function _revertMessageAlreadyHasGlobalRole(bytes32 role, address account)
internal
view
virtual
returns (string memory)
{
return
string(
abi.encodePacked(
"RoleMembership: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" already has role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
);
}
/**
* @dev Override the function for a custom revert message.
*/
function _revertMessageAlreadyHasDaoRole(
uint256 daoId,
bytes32 role,
address account
) internal view virtual returns (string memory) {
return
string(
abi.encodePacked(
"RoleMembership: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" already has role ",
StringsUpgradeable.toHexString(uint256(role), 32),
" in DAO ",
StringsUpgradeable.toHexString(daoId, 32)
)
);
}
/**
* @dev Override the function for a custom revert message.
*/
function _revertMessageMissingGlobalRole(bytes32 role, address account)
internal
view
virtual
returns (string memory)
{
return
string(
abi.encodePacked(
"RoleMembership: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
);
}
/**
* @dev Override the function for a custom revert message.
*/
function _revertMessageMissingDaoRole(
uint256 daoId,
bytes32 role,
address account
) internal view virtual returns (string memory) {
return
string(
abi.encodePacked(
"RoleMembership: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32),
" in DAO ",
StringsUpgradeable.toHexString(daoId, 32)
)
);
}
}
|
Override the function for a custom revert message./
|
function _revertMessageMissingGlobalRole(bytes32 role, address account)
internal
view
virtual
returns (string memory)
{
return
string(
abi.encodePacked(
"RoleMembership: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
);
}
| 12,779,027 |
./partial_match/1313161554/0xaE4fac24dCdAE0132C6d04f564dCf059616E9423/sources/AuErc20.sol
|
Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. This will revert due to insufficient balance or insufficient allowance. Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. this function doesn't work with fee-on-transfer tokens/
|
function doTransferIn(address from, uint amount) internal override returns (uint) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
token.transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
}
returndatacopy(0, 0, 32)
}
revert(0, 0)
| 16,916,529 |
./partial_match/97/0x1aBB04723FF281a45BC6A7AABF5712a740DCACdB/sources/NameChangeToken.sol
|
Take BNB home/
|
function claimBNB(uint256 tokenId) public {
require(block.timestamp >= BNB_DISTRIBUTION_TIMESTAMP, "BNB distribution is not opened yet.");
require(_tokenBNBClaimability[tokenId], "BNB has been claimed.");
require(sent, "Failed to distribute BNB");
_tokenBNBClaimability[tokenId] = false;
emit BNBClaim(tokenId, BNBDistribution);
}
| 11,343,806 |
./full_match/40/0x6D1F230f479f14e717204f2053E8e7c0397B0937/sources/contracts/Omnidex-incentives/incentives/PullRewardsIncentivesController.sol
|
@inheritdoc BaseIncentivesController IERC20(REWARD_TOKEN).safeTransferFrom(_rewardsVault, to, amount);
|
function _transferRewards(address to, uint256 amount) internal override {
TempIncentivesVault(_rewardsVault).withdraw(to, amount);
}
| 9,548,293 |
pragma solidity >=0.4.21 <0.6.0;
import "./SafeMath.sol";
contract Earnings {
using SafeMath for *;
// -------------------- mapping ------------------------ //
mapping(address => UserWithdraw) public userWithdraw; // record user withdraw reward information
// -------------------- variate ------------------------ //
uint8 constant internal percent = 100;
uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent
address public resonanceAddress;
address public owner;
// -------------------- struct ------------------------ //
struct UserWithdraw {
uint256 withdrawStraight; // withdraw straight eth amount
uint256 withdrawTeam; // withdraw team eth amount
uint256 withdrawStatic; // withdraw static eth amount
uint256 withdrawTerminator;//withdraw terminator amount
uint256 withdrawNode; // withdraw node amount
uint256 lockEth; // user lock eth
uint256 activateEth; // record user activate eth
}
constructor()
public{
owner = msg.sender;
}
// -------------------- modifier ------------------------ //
modifier onlyOwner(){
require(msg.sender == owner);
_;
}
modifier onlyResonance (){
require(msg.sender == resonanceAddress);
_;
}
// -------------------- owner api ------------------------ //
function allowResonance(address _addr) public onlyOwner() {
resonanceAddress = _addr;
}
// -------------------- Resonance api ------------------------ //
// calculate actual reinvest amount, include amount + lockEth
function calculateReinvestAmount(
address reinvestAddress,
uint256 amount,
uint256 userAmount,
uint8 requireType)//type: 1 => straightEth, 2 => teamEth, 3 => withdrawStatic, 4 => withdrawNode
public
onlyResonance()
returns (uint256)
{
if (requireType == 1) {
require(amount.add((userWithdraw[reinvestAddress].withdrawStatic).mul(100).div(80)) <= userAmount);
} else if (requireType == 2) {
require(amount.add((userWithdraw[reinvestAddress].withdrawStraight).mul(100).div(80)) <= userAmount.add(amount));
} else if (requireType == 3) {
require(amount.add((userWithdraw[reinvestAddress].withdrawTeam).mul(100).div(80)) <= userAmount.add(amount));
} else if (requireType == 5) {
require(amount.add((userWithdraw[reinvestAddress].withdrawNode).mul(100).div(80)) <= userAmount);
}
// userWithdraw[reinvestAddress].lockEth = userWithdraw[reinvestAddress].lockEth.add(amount.mul(remain).div(100));\
uint256 _active = userWithdraw[reinvestAddress].lockEth - userWithdraw[reinvestAddress].activateEth;
if (amount > _active) {
userWithdraw[reinvestAddress].activateEth += _active;
amount = amount.add(_active);
} else {
userWithdraw[reinvestAddress].activateEth = userWithdraw[reinvestAddress].activateEth.add(amount);
amount = amount.mul(2);
}
return amount;
}
function routeAddLockEth(
address withdrawAddress,
uint256 amount,
uint256 lockProfits,
uint256 userRouteEth,
uint256 routeType)
public
onlyResonance()
{
if (routeType == 1) {
addLockEthStatic(withdrawAddress, amount, lockProfits, userRouteEth);
} else if (routeType == 2) {
addLockEthStraight(withdrawAddress, amount, userRouteEth);
} else if (routeType == 3) {
addLockEthTeam(withdrawAddress, amount, userRouteEth);
} else if (routeType == 4) {
addLockEthTerminator(withdrawAddress, amount, userRouteEth);
} else if (routeType == 5) {
addLockEthNode(withdrawAddress, amount, userRouteEth);
}
}
function addLockEthStatic(address withdrawAddress, uint256 amount, uint256 lockProfits, uint256 userStatic)
internal
{
require(amount.add(userWithdraw[withdrawAddress].withdrawStatic.mul(100).div(percent - remain)) <= userStatic);
userWithdraw[withdrawAddress].lockEth += lockProfits;
userWithdraw[withdrawAddress].withdrawStatic += amount.sub(lockProfits);
}
function addLockEthStraight(address withdrawAddress, uint256 amount, uint256 userStraightEth)
internal
{
require(amount.add(userWithdraw[withdrawAddress].withdrawStraight.mul(100).div(percent - remain)) <= userStraightEth);
userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100);
userWithdraw[withdrawAddress].withdrawStraight += amount.mul(percent - remain).div(100);
}
function addLockEthTeam(address withdrawAddress, uint256 amount, uint256 userTeamEth)
internal
{
require(amount.add(userWithdraw[withdrawAddress].withdrawTeam.mul(100).div(percent - remain)) <= userTeamEth);
userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100);
userWithdraw[withdrawAddress].withdrawTeam += amount.mul(percent - remain).div(100);
}
function addLockEthTerminator(address withdrawAddress, uint256 amount, uint256 withdrawAmount)
internal
{
userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100);
userWithdraw[withdrawAddress].withdrawTerminator += withdrawAmount;
}
function addLockEthNode(address withdrawAddress, uint256 amount, uint256 userNodeEth)
internal
{
require(amount.add(userWithdraw[withdrawAddress].withdrawNode.mul(100).div(percent - remain)) <= userNodeEth);
userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100);
userWithdraw[withdrawAddress].withdrawNode += amount.mul(percent - remain).div(100);
}
function addActivateEth(address userAddress, uint256 amount)
public
onlyResonance()
{
uint256 _afterFounds = getAfterFounds(userAddress);
if (amount > _afterFounds) {
userWithdraw[userAddress].activateEth = userWithdraw[userAddress].lockEth;
}
else {
userWithdraw[userAddress].activateEth += amount;
}
}
function changeWithdrawTeamZero(address userAddress)
public
onlyResonance()
{
userWithdraw[userAddress].withdrawTeam = 0;
}
function getWithdrawStraight(address reinvestAddress)
public
view
onlyResonance()
returns (uint256)
{
return userWithdraw[reinvestAddress].withdrawStraight;
}
function getWithdrawStatic(address reinvestAddress)
public
view
onlyResonance()
returns (uint256)
{
return userWithdraw[reinvestAddress].withdrawStatic;
}
function getWithdrawTeam(address reinvestAddress)
public
view
onlyResonance()
returns (uint256)
{
return userWithdraw[reinvestAddress].withdrawTeam;
}
function getWithdrawNode(address reinvestAddress)
public
view
onlyResonance()
returns (uint256)
{
return userWithdraw[reinvestAddress].withdrawNode;
}
function getAfterFounds(address userAddress)
public
view
onlyResonance()
returns (uint256)
{
return userWithdraw[userAddress].lockEth - userWithdraw[userAddress].activateEth;
}
function getStaticAfterFounds(address reinvestAddress) public
view
onlyResonance()
returns (uint256, uint256)
{
return (userWithdraw[reinvestAddress].withdrawStatic, userWithdraw[reinvestAddress].lockEth - userWithdraw[reinvestAddress].activateEth);
}
function getStaticAfterFoundsTeam(address userAddress) public
view
onlyResonance()
returns (uint256, uint256, uint256)
{
return (userWithdraw[userAddress].withdrawStatic, userWithdraw[userAddress].lockEth - userWithdraw[userAddress].activateEth, userWithdraw[userAddress].withdrawTeam);
}
function getUserWithdrawInfo(address reinvestAddress) public
view
onlyResonance()
returns (
uint256 withdrawStraight,
uint256 withdrawTeam,
uint256 withdrawStatic,
uint256 withdrawNode
)
{
withdrawStraight = userWithdraw[reinvestAddress].withdrawStraight;
withdrawTeam = userWithdraw[reinvestAddress].withdrawTeam;
withdrawStatic = userWithdraw[reinvestAddress].withdrawStatic;
withdrawNode = userWithdraw[reinvestAddress].withdrawNode;
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "./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 `ERC20Mintable`.
*
* *For a detailed writeup see our guide [How to implement supply
* mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).*
*
* 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 IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See `IERC20.totalSupply`.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See `IERC20.balanceOf`.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See `IERC20.transfer`.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See `IERC20.allowance`.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See `IERC20.approve`.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
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 `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(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 returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to `transfer`, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a `Transfer` event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
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);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a `Transfer` event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destoys `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 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @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 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Destoys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See `_burn` and `_approve`.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount));
}
}
pragma solidity ^0.5.0;
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).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Destoys `amount` tokens from the caller.
*
* See `ERC20._burn`.
*/
function burn(uint256 amount) public {
_burn(msg.sender, amount);
}
/**
* @dev See `ERC20._burnFrom`.
*/
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
}
pragma solidity ^0.5.0;
import "./ERC20Mintable.sol";
/**
* @dev Extension of `ERC20Mintable` that adds a cap to the supply of tokens.
*/
contract ERC20Capped is ERC20Mintable {
uint256 private _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
constructor (uint256 cap) public {
require(cap > 0, "ERC20Capped: cap is 0");
_cap = cap;
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view returns (uint256) {
return _cap;
}
/**
* @dev See `ERC20Mintable.mint`.
*
* Requirements:
*
* - `value` must not cause the total supply to go over the cap.
*/
function _mint(address account, uint256 value) internal {
require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded");
super._mint(account, value);
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* > Note that 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;
}
}
pragma solidity ^0.5.0;
import "./ERC20.sol";
import "./MinterRole.sol";
/**
* @dev Extension of `ERC20` that adds a set of accounts with the `MinterRole`,
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev See `ERC20._mint`.
*
* Requirements:
*
* - the caller must have the `MinterRole`.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
}
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through `transferFrom`. This is
* zero by default.
*
* This value changes when `approve` or `transferFrom` are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* > Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to `approve`. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity >=0.4.21 <0.6.0;
import "./ERC20.sol";
import "./ERC20Detailed.sol";
import "./ERC20Capped.sol";
import "./ERC20Burnable.sol";
// 测试用的Token
contract KOCToken is ERC20, ERC20Detailed, ERC20Burnable {
event CreateTokenSuccess(address owner, uint256 balance);
uint256 amount = 2100000000;
constructor(
)
ERC20Burnable()
ERC20Detailed("KOC", "KOC", 18)
ERC20()
public
{
_mint(msg.sender, amount * (10 ** 18));
emit CreateTokenSuccess(msg.sender, balanceOf(msg.sender));
}
}
pragma solidity ^0.5.0;
import "./Roles.sol";
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), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
pragma solidity >=0.4.21 <0.6.0;
contract Recommend {
// -------------------- mapping ------------------------ //
mapping(address => RecommendRecord) internal recommendRecord; // record straight reward information
// -------------------- struct ------------------------ //
struct RecommendRecord {
uint256[] straightTime; // this record start time, 3 days timeout
address[] refeAddress; // referral address
uint256[] ethAmount; // this record buy eth amount
bool[] supported; // false means unsupported
}
// -------------------- variate ------------------------ //
address public resonanceAddress;
address public owner;
constructor()
public{
owner = msg.sender;
}
// -------------------- modifier ------------------------ //
modifier onlyOwner(){
require(msg.sender == owner);
_;
}
modifier onlyResonance (){
require(msg.sender == resonanceAddress);
_;
}
// -------------------- owner api ------------------------ //
function allowResonance(address _addr) public onlyOwner() {
resonanceAddress = _addr;
}
// -------------------- Resonance api ----------------//
function getRecommendByIndex(uint256 index, address userAddress)
public
view
// onlyResonance() TODO
returns (
uint256 straightTime,
address refeAddress,
uint256 ethAmount,
bool supported
)
{
straightTime = recommendRecord[userAddress].straightTime[index];
refeAddress = recommendRecord[userAddress].refeAddress[index];
ethAmount = recommendRecord[userAddress].ethAmount[index];
supported = recommendRecord[userAddress].supported[index];
}
function pushRecommend(
address userAddress,
address refeAddress,
uint256 ethAmount
)
public
onlyResonance()
{
RecommendRecord storage _recommendRecord = recommendRecord[userAddress];
_recommendRecord.straightTime.push(block.timestamp);
_recommendRecord.refeAddress.push(refeAddress);
_recommendRecord.ethAmount.push(ethAmount);
_recommendRecord.supported.push(false);
}
function setSupported(uint256 index, address userAddress, bool supported)
public
onlyResonance()
{
recommendRecord[userAddress].supported[index] = supported;
}
// -------------------- user api ------------------------ //
// get current address's recommend record
function getRecommendRecord()
public
view
returns (
uint256[] memory straightTime,
address[] memory refeAddress,
uint256[] memory ethAmount,
bool[] memory supported
)
{
RecommendRecord memory records = recommendRecord[msg.sender];
straightTime = records.straightTime;
refeAddress = records.refeAddress;
ethAmount = records.ethAmount;
supported = records.supported;
}
}
pragma solidity >=0.4.21 <0.6.0;
import "./SafeMath.sol";
import "./Earnings.sol";
import "./TeamRewards.sol";
import "./Terminator.sol";
import "./Recommend.sol";
import "./ResonanceF.sol";
contract Resonance is ResonanceF {
using SafeMath for uint256;
uint256 public totalSupply = 0;
uint256 constant internal bonusPrice = 0.0000001 ether; // init price
uint256 constant internal priceIncremental = 0.00000001 ether; // increase price
uint256 constant internal magnitude = 2 ** 64;
uint256 public perBonusDivide = 0; //per Profit divide
uint256 public systemRetain = 0;
uint256 public terminatorPoolAmount; //terminator award Pool Amount
uint256 public activateSystem = 20;
uint256 public activateGlobal = 20;
mapping(address => User) public userInfo; // user define all user's information
mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward
mapping(address => int256) internal payoutsTo; // record
mapping(address => uint256[11]) public userSubordinateCount;
mapping(address => uint256) public whitelistPerformance;
mapping(address => UserReinvest) public userReinvest;
mapping(address => uint256) public lastStraightLength;
uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent
uint32 constant internal ratio = 1000; // eth to erc20 token ratio
uint32 constant internal blockNumber = 40000; // straight sort reward block number
uint256 public currentBlockNumber;
uint256 public straightSortRewards = 0;
uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit
uint256 public totalEthAmount = 0; // all user total buy eth amount
uint8 constant public percent = 100;
address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address
address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD);
address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6);
address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f);
address [10] public straightSort; // straight reward
Earnings internal earningsInstance;
TeamRewards internal teamRewardInstance;
Terminator internal terminatorInstance;
Recommend internal recommendInstance;
struct User {
address userAddress; // user address
uint256 ethAmount; // user buy eth amount
uint256 profitAmount; // user profit amount
uint256 tokenAmount; // user get token amount
uint256 tokenProfit; // profit by profitAmount
uint256 straightEth; // user straight eth
uint256 lockStraight;
uint256 teamEth; // team eth reward
bool staticTimeout; // static timeout, 3 days
uint256 staticTime; // record static out time
uint8 level; // user team level
address straightAddress;
uint256 refeTopAmount; // subordinate address topmost eth amount
address refeTopAddress; // subordinate address topmost eth address
}
struct UserReinvest {
// uint256 nodeReinvest;
uint256 staticReinvest;
bool isPush;
}
uint8[7] internal rewardRatio; // [0] means market support rewards 10%
// [1] means static rewards 30%
// [2] means straight rewards 30%
// [3] means team rewards 29%
// [4] means terminator rewards 5%
// [5] means straight sort rewards 5%
// [6] means egg rewards 1%
uint8[11] internal teamRatio; // team reward ratio
modifier mustAdmin (address adminAddress){
require(adminAddress != address(0));
require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]);
_;
}
modifier mustReferralAddress (address referralAddress) {
require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]);
if (teamRewardInstance.isWhitelistAddress(msg.sender)) {
require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]);
}
_;
}
modifier limitInvestmentCondition(uint256 ethAmount){
if (initAddressAmount <= 50) {
require(ethAmount <= 5 ether);
_;
} else {
_;
}
}
modifier limitAddressReinvest() {
if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) {
require(msg.value <= userInfo[msg.sender].ethAmount.mul(3));
}
_;
}
// -------------------- modifier ------------------------ //
// --------------------- event -------------------------- //
event WithdrawStaticProfits(address indexed user, uint256 ethAmount);
event Buy(address indexed user, uint256 ethAmount, uint256 buyTime);
event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime);
event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime);
event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported);
// --------------------- event -------------------------- //
constructor(
address _erc20Address,
address _earningsAddress,
address _teamRewardsAddress,
address _terminatorAddress,
address _recommendAddress
)
public
{
earningsInstance = Earnings(_earningsAddress);
teamRewardInstance = TeamRewards(_teamRewardsAddress);
terminatorInstance = Terminator(_terminatorAddress);
kocInstance = KOCToken(_erc20Address);
recommendInstance = Recommend(_recommendAddress);
rewardRatio = [10, 30, 30, 29, 5, 5, 1];
teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1];
currentBlockNumber = block.number;
}
// -------------------- user api ----------------//
function buy(address referralAddress)
public
mustReferralAddress(referralAddress)
limitInvestmentCondition(msg.value)
payable
{
require(!teamRewardInstance.getWhitelistTime());
uint256 ethAmount = msg.value;
address userAddress = msg.sender;
User storage _user = userInfo[userAddress];
_user.userAddress = userAddress;
if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) {
teamRewardInstance.referralPeople(userAddress, referralAddress);
_user.straightAddress = referralAddress;
} else {
referralAddress == teamRewardInstance.getUserreferralAddress(userAddress);
}
address straightAddress;
address whiteAddress;
address adminAddress;
bool whitelist;
(straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress);
require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]);
if (userInfo[referralAddress].userAddress == address(0)) {
userInfo[referralAddress].userAddress = referralAddress;
}
if (userInfo[userAddress].straightAddress == address(0)) {
userInfo[userAddress].straightAddress = straightAddress;
}
// uint256 _withdrawStatic;
uint256 _lockEth;
uint256 _withdrawTeam;
(, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress);
if (ethAmount >= _lockEth) {
ethAmount = ethAmount.add(_lockEth);
if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) {
address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80)));
userInfo[userAddress].teamEth = 0;
earningsInstance.changeWithdrawTeamZero(userAddress);
}
userInfo[userAddress].staticTimeout = false;
userInfo[userAddress].staticTime = block.timestamp;
} else {
_lockEth = ethAmount;
ethAmount = ethAmount.mul(2);
}
earningsInstance.addActivateEth(userAddress, _lockEth);
if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) {
require(userInfo[userAddress].profitAmount == 0);
}
if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static
initAddressAmount++;
}
calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress);
straightReferralReward(_user, ethAmount);
// calculate straight referral reward
uint256 topProfits = whetherTheCap();
require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits);
emit Buy(userAddress, ethAmount, block.timestamp);
}
// contains some methods for buy or reinvest
function calculateBuy(
User storage user,
uint256 ethAmount,
address straightAddress,
address whiteAddress,
address adminAddress,
address users
)
internal
{
require(ethAmount > 0);
user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount);
if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) {
user.straightEth += user.lockStraight;
user.lockStraight = 0;
}
if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) {
straightInviteAddress[straightAddress].push(user.userAddress);
userReinvest[user.userAddress].isPush = true;
// record straight address
if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) {
bool has = false;
//search this address
for (uint i = 0; i < 10; i++) {
if (straightSort[i] == straightAddress) {
has = true;
}
}
if (!has) {
//search this address if not in this array,go sort after cover last
straightSort[9] = straightAddress;
}
// sort referral address
quickSort(straightSort, int(0), int(9));
// straightSortAddress(straightAddress);
}
// }
}
address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100));
// transfer to eggAddress 1% eth
straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100);
// straight sort rewards, 5% eth
teamReferralReward(ethAmount, straightAddress);
// issue team reward
terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100);
// issue terminator reward
calculateToken(user, ethAmount);
// calculate and transfer KOC token
calculateProfit(user, ethAmount, users);
// calculate user earn profit
updateTeamLevel(straightAddress);
// update team level
totalEthAmount += ethAmount;
whitelistPerformance[whiteAddress] += ethAmount;
whitelistPerformance[adminAddress] += ethAmount;
addTerminator(user.userAddress);
}
// contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards
// 3 means team rewards, 4 means terminators rewards, 5 means node rewards
function reinvest(uint256 amount, uint8 value)
public
payable
{
address reinvestAddress = msg.sender;
address straightAddress;
address whiteAddress;
address adminAddress;
(straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender);
require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303");
uint256 earningsProfits = 0;
if (value == 1) {
earningsProfits = whetherTheCap();
uint256 _withdrawStatic;
uint256 _afterFounds;
uint256 _withdrawTeam;
(_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress);
_withdrawStatic = _withdrawStatic.mul(100).div(80);
require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits);
if (amount >= _afterFounds) {
if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) {
address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80)));
userInfo[reinvestAddress].teamEth = 0;
earningsInstance.changeWithdrawTeamZero(reinvestAddress);
}
userInfo[reinvestAddress].staticTimeout = false;
userInfo[reinvestAddress].staticTime = block.timestamp;
}
userReinvest[reinvestAddress].staticReinvest += amount;
} else if (value == 2) {
//复投直推
require(userInfo[reinvestAddress].straightEth >= amount);
userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount);
earningsProfits = userInfo[reinvestAddress].straightEth;
} else if (value == 3) {
require(userInfo[reinvestAddress].teamEth >= amount);
userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount);
earningsProfits = userInfo[reinvestAddress].teamEth;
} else if (value == 4) {
terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount);
}
amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value);
calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress);
straightReferralReward(userInfo[reinvestAddress], amount);
emit Reinvest(reinvestAddress, amount, value, block.timestamp);
}
// contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards
// 3 means team rewards, 4 means terminators rewards, 5 means node rewards
function withdraw(uint256 amount, uint8 value)
public
{
address withdrawAddress = msg.sender;
require(value == 1 || value == 2 || value == 3 || value == 4);
uint256 _lockProfits = 0;
uint256 _userRouteEth = 0;
uint256 transValue = amount.mul(80).div(100);
if (value == 1) {
_userRouteEth = whetherTheCap();
_lockProfits = SafeMath.mul(amount, remain).div(100);
} else if (value == 2) {
_userRouteEth = userInfo[withdrawAddress].straightEth;
} else if (value == 3) {
if (userInfo[withdrawAddress].staticTimeout) {
require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp);
}
_userRouteEth = userInfo[withdrawAddress].teamEth;
} else if (value == 4) {
_userRouteEth = amount.mul(80).div(100);
terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth);
}
earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value);
address(uint160(withdrawAddress)).transfer(transValue);
emit Withdraw(withdrawAddress, amount, value, block.timestamp);
}
// referral address support subordinate, 10%
function supportSubordinateAddress(uint256 index, address subordinate)
public
payable
{
User storage _user = userInfo[msg.sender];
require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100));
uint256 straightTime;
address refeAddress;
uint256 ethAmount;
bool supported;
(straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress);
require(!supported);
require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10));
if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) {
_user.straightEth += ethAmount.mul(rewardRatio[2]).div(100);
} else {
_user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100);
}
address straightAddress;
address whiteAddress;
address adminAddress;
(straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate);
calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate);
recommendInstance.setSupported(index, _user.userAddress, true);
emit SupportSubordinateAddress(index, subordinate, refeAddress, supported);
}
// -------------------- internal function ----------------//
// calculate team reward and issue reward
//teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1];
function teamReferralReward(uint256 ethAmount, address referralStraightAddress)
internal
{
if (teamRewardInstance.isWhitelistAddress(msg.sender)) {
uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100);
uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100);
systemRetain += _nodeReward;
address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100));
address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100));
address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100));
} else {
uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100);
//system residue eth
uint256 residueAmount = _refeReward;
//user straight address
User memory currentUser = userInfo[referralStraightAddress];
//issue team reward
for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12
//get straight user
address straightAddress = currentUser.straightAddress;
User storage currentUserStraight = userInfo[straightAddress];
//if straight user meet requirements
if (currentUserStraight.level >= i) {
uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29);
currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward);
//sub reward amount
residueAmount = residueAmount.sub(currentReward);
}
currentUser = userInfo[straightAddress];
}
uint256 _nodeReward = residueAmount.mul(activateSystem).div(100);
systemRetain = systemRetain.add(_nodeReward);
address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100));
address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100));
address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100));
}
}
function updateTeamLevel(address refferAddress)
internal
{
User memory currentUserStraight = userInfo[refferAddress];
uint8 levelUpCount = 0;
uint256 currentInviteCount = straightInviteAddress[refferAddress].length;
if (currentInviteCount >= 2) {
levelUpCount = 2;
}
if (currentInviteCount > 12) {
currentInviteCount = 12;
}
uint256 lackCount = 0;
for (uint8 j = 2; j < currentInviteCount; j++) {
if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) {
levelUpCount = j + 1;
lackCount = 0;
} else {
lackCount++;
}
}
if (levelUpCount > currentUserStraight.level) {
uint8 oldLevel = userInfo[refferAddress].level;
userInfo[refferAddress].level = levelUpCount;
if (currentUserStraight.straightAddress != address(0)) {
if (oldLevel > 0) {
if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) {
userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1;
}
}
userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1;
updateTeamLevel(currentUserStraight.straightAddress);
}
}
}
// calculate bonus profit
function calculateProfit(User storage user, uint256 ethAmount, address users)
internal
{
if (teamRewardInstance.isWhitelistAddress(user.userAddress)) {
ethAmount = ethAmount.mul(110).div(100);
}
uint256 userBonus = ethToBonus(ethAmount);
require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply);
totalSupply += userBonus;
uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100);
getPerBonusDivide(tokenDivided, userBonus, users);
user.profitAmount += userBonus;
}
// get user bonus information for calculate static rewards
function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users)
public
{
uint256 fee = tokenDivided * magnitude;
perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply);
//calculate every bonus earnings eth
fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply))));
int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee);
payoutsTo[users] += updatedPayouts;
}
// calculate and transfer KOC token
function calculateToken(User storage user, uint256 ethAmount)
internal
{
kocInstance.transfer(user.userAddress, ethAmount.mul(ratio));
user.tokenAmount += ethAmount.mul(ratio);
}
// calculate straight reward and record referral address recommendRecord
function straightReferralReward(User memory user, uint256 ethAmount)
internal
{
address _referralAddresses = user.straightAddress;
userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount;
userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress;
recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount);
if (teamRewardInstance.isWhitelistAddress(user.userAddress)) {
uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100);
uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100);
systemRetain += _nodeReward;
address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100));
address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100));
address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100));
}
}
// sort straight address, 10
function straightSortAddress(address referralAddress)
internal
{
for (uint8 i = 0; i < 10; i++) {
if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) {
address [] memory temp;
for (uint j = i; j < 10; j++) {
temp[j] = straightSort[j];
}
straightSort[i] = referralAddress;
for (uint k = i; k < 9; k++) {
straightSort[k + 1] = temp[k];
}
}
}
}
//sort straight address, 10
function quickSort(address [10] storage arr, int left, int right) internal {
int i = left;
int j = right;
if (i == j) return;
uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]);
while (i <= j) {
while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++;
while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[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);
}
// settle straight rewards
function settleStraightRewards()
internal
{
uint256 addressAmount;
for (uint8 i = 0; i < 10; i++) {
addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]];
}
uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2);
uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount);
for (uint8 j = 0; j < 10; j++) {
address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward));
straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward));
lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length;
}
delete (straightSort);
currentBlockNumber = block.number;
}
// calculate bonus
function ethToBonus(uint256 ethereum)
internal
view
returns (uint256)
{
uint256 _price = bonusPrice * 1e18;
// calculate by wei
uint256 _tokensReceived =
(
(
SafeMath.sub(
(sqrt
(
(_price ** 2)
+
(2 * (priceIncremental * 1e18) * (ethereum * 1e18))
+
(((priceIncremental) ** 2) * (totalSupply ** 2))
+
(2 * (priceIncremental) * _price * totalSupply)
)
), _price
)
) / (priceIncremental)
) - (totalSupply);
return _tokensReceived;
}
// utils for calculate bonus
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
// get user bonus profits
function myBonusProfits(address user)
view
public
returns (uint256)
{
return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude);
}
function whetherTheCap()
internal
returns (uint256)
{
require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit);
uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120));
uint256 topProfits = _currentAmount.mul(remain + 100).div(100);
uint256 userProfits = myBonusProfits(msg.sender);
if (userProfits > topProfits) {
userInfo[msg.sender].profitAmount = 0;
payoutsTo[msg.sender] = 0;
userInfo[msg.sender].tokenProfit += topProfits;
userInfo[msg.sender].staticTime = block.timestamp;
userInfo[msg.sender].staticTimeout = true;
}
if (topProfits == 0) {
topProfits = userInfo[msg.sender].tokenProfit;
} else {
topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again
}
return topProfits;
}
// -------------------- set api ---------------- //
function setStraightSortRewards()
public
onlyAdmin()
returns (bool)
{
require(currentBlockNumber + blockNumber < block.number);
settleStraightRewards();
return true;
}
// -------------------- get api ---------------- //
// get straight sort list, 10 addresses
function getStraightSortList()
public
view
returns (address[10] memory)
{
return straightSort;
}
// get effective straight addresses current step
function getStraightInviteAddress()
public
view
returns (address[] memory)
{
return straightInviteAddress[msg.sender];
}
// get currentBlockNumber
function getcurrentBlockNumber()
public
view
returns (uint256){
return currentBlockNumber;
}
function getPurchaseTasksInfo()
public
view
returns (
uint256 ethAmount,
uint256 refeTopAmount,
address refeTopAddress,
uint256 lockStraight
)
{
User memory getUser = userInfo[msg.sender];
ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120));
refeTopAmount = getUser.refeTopAmount;
refeTopAddress = getUser.refeTopAddress;
lockStraight = getUser.lockStraight;
}
function getPersonalStatistics()
public
view
returns (
uint256 holdings,
uint256 dividends,
uint256 invites,
uint8 level,
uint256 afterFounds,
uint256 referralRewards,
uint256 teamRewards,
uint256 nodeRewards
)
{
User memory getUser = userInfo[msg.sender];
uint256 _withdrawStatic;
(_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress);
holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120));
dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender);
invites = straightInviteAddress[msg.sender].length;
level = getUser.level;
referralRewards = getUser.straightEth;
teamRewards = getUser.teamEth;
uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount);
nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards;
}
function getUserBalance()
public
view
returns (
uint256 staticBalance,
uint256 recommendBalance,
uint256 teamBalance,
uint256 terminatorBalance,
uint256 nodeBalance,
uint256 totalInvest,
uint256 totalDivided,
uint256 withdrawDivided
)
{
User memory getUser = userInfo[msg.sender];
uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120));
uint256 withdrawStraight;
uint256 withdrawTeam;
uint256 withdrawStatic;
uint256 withdrawNode;
(withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress);
// uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80));
uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0;
uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0;
staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest);
recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80));
teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80));
terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress);
nodeBalance = 0;
totalInvest = getUser.ethAmount;
totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress));
withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80);
}
// returns contract statistics
function contractStatistics()
public
view
returns (
uint256 recommendRankPool,
uint256 terminatorPool
)
{
recommendRankPool = straightSortRewards;
terminatorPool = getCurrentTerminatorAmountPool();
}
function listNodeBonus(address node)
public
view
returns (
address nodeAddress,
uint256 performance
)
{
nodeAddress = node;
performance = whitelistPerformance[node];
}
function listRankOfRecommend()
public
view
returns (
address[10] memory _straightSort,
uint256[10] memory _inviteNumber
)
{
for (uint8 i = 0; i < 10; i++) {
if (straightSort[i] == address(0)){
break;
}
_inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]);
}
_straightSort = straightSort;
}
// return current effective user for initAddressAmount
function getCurrentEffectiveUser()
public
view
returns (uint256)
{
return initAddressAmount;
}
function addTerminator(address addr)
internal
{
uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120));
uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number);
terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2));
}
function isLockWithdraw()
public
view
returns (
bool isLock,
uint256 lockTime
)
{
isLock = userInfo[msg.sender].staticTimeout;
lockTime = userInfo[msg.sender].staticTime;
}
function modifyActivateSystem(uint256 value)
mustAdmin(msg.sender)
public
{
activateSystem = value;
}
function modifyActivateGlobal(uint256 value)
mustAdmin(msg.sender)
public
{
activateGlobal = value;
}
//return Current Terminator reward pool amount
function getCurrentTerminatorAmountPool()
view public
returns(uint256 amount)
{
return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number);
}
}
pragma solidity >=0.4.21 <0.6.0;
import "./KOCToken.sol";
contract ResonanceF {
address[5] internal admin = [address(0x8434750c01D702c9cfabb3b7C5AA2774Ee67C90D), address(0xD8e79f0D2592311E740Ff097FFb0a7eaa8cb506a), address(0x740beb9fa9CCC6e971f90c25C5D5CC77063a722D), address(0x1b5bbac599f1313dB3E8061A0A65608f62897B0C), address(0x6Fd6dF175B97d2E6D651b536761e0d36b33A9495)];
address internal boosAddress = address(0x541f5417187981b28Ef9e7Df814b160Ae2Bcb72C);
KOCToken internal kocInstance;
modifier onlyAdmin () {
address adminAddress = msg.sender;
require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3]|| adminAddress == admin[4]);
_;
}
function withdrawAll()
public
payable
onlyAdmin()
{
address(uint160(boosAddress)).transfer(address(this).balance);
kocInstance.transfer(address(uint160(boosAddress)), kocInstance.balanceOf(address(this)));
}
}
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
pragma solidity >=0.4.21 <0.6.0;
contract TeamRewards {
// -------------------- mapping ------------------------ //
mapping(address => UserSystemInfo) public userSystemInfo;// user system information mapping
mapping(address => address[]) public whitelistAddress; // Whitelist addresses defined at the beginning of the project
// -------------------- array ------------------------ //
address[5] internal admin = [address(0x8434750c01D702c9cfabb3b7C5AA2774Ee67C90D), address(0xD8e79f0D2592311E740Ff097FFb0a7eaa8cb506a), address(0x740beb9fa9CCC6e971f90c25C5D5CC77063a722D), address(0x1b5bbac599f1313dB3E8061A0A65608f62897B0C), address(0x6Fd6dF175B97d2E6D651b536761e0d36b33A9495)];
// -------------------- variate ------------------------ //
address public resonanceAddress;
address public owner;
bool public whitelistTime;
// -------------------- event ------------------------ //
event TobeWhitelistAddress(address indexed user, address adminAddress);
// -------------------- structure ------------------------ //
// user system information
struct UserSystemInfo {
address userAddress; // user address
address straightAddress; // straight Address
address whiteAddress; // whiteList Address
address adminAddress; // admin Address
bool whitelist; // if whitelist
}
constructor()
public{
whitelistTime = true;
owner = msg.sender;
}
// -------------------- modifier ------------------------ //
modifier onlyOwner(){
require(msg.sender == owner);
_;
}
modifier onlyAdmin () {
address adminAddress = msg.sender;
require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]);
_;
}
modifier mustAdmin (address adminAddress){
require(adminAddress != address(0));
require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]);
_;
}
modifier onlyResonance (){
require(msg.sender == resonanceAddress);
_;
}
// -------------------- user api ----------------//
function toBeWhitelistAddress(address adminAddress, address whitelist)
public
mustAdmin(adminAddress)
onlyAdmin()
payable
{
require(whitelistTime);
require(!userSystemInfo[whitelist].whitelist);
whitelistAddress[adminAddress].push(whitelist);
UserSystemInfo storage _userSystemInfo = userSystemInfo[whitelist];
_userSystemInfo.straightAddress = adminAddress;
_userSystemInfo.whiteAddress = whitelist;
_userSystemInfo.adminAddress = adminAddress;
_userSystemInfo.whitelist = true;
emit TobeWhitelistAddress(whitelist, adminAddress);
}
// -------------------- Resonance api ----------------//
function referralPeople(address userAddress,address referralAddress)
public
onlyResonance()
{
UserSystemInfo storage _userSystemInfo = userSystemInfo[userAddress];
_userSystemInfo.straightAddress = referralAddress;
_userSystemInfo.whiteAddress = userSystemInfo[referralAddress].whiteAddress;
_userSystemInfo.adminAddress = userSystemInfo[referralAddress].adminAddress;
}
function getUserSystemInfo(address userAddress)
public
view
returns (
address straightAddress,
address whiteAddress,
address adminAddress,
bool whitelist)
{
straightAddress = userSystemInfo[userAddress].straightAddress;
whiteAddress = userSystemInfo[userAddress].whiteAddress;
adminAddress = userSystemInfo[userAddress].adminAddress;
whitelist = userSystemInfo[userAddress].whitelist;
}
function getUserreferralAddress(address userAddress)
public
view
onlyResonance()
returns (address )
{
return userSystemInfo[userAddress].straightAddress;
}
// -------------------- Owner api ----------------//
function allowResonance(address _addr) public onlyOwner() {
resonanceAddress = _addr;
}
// -------------------- Admin api ---------------- //
// set whitelist close
function setWhitelistTime(bool off)
public
onlyAdmin()
{
whitelistTime = off;
}
function getWhitelistTime()
public
view
returns (bool)
{
return whitelistTime;
}
// get all whitelist by admin address
function getAdminWhitelistAddress(address adminx)
public
view
returns (address[] memory)
{
return whitelistAddress[adminx];
}
// check if the user is whitelist
function isWhitelistAddress(address user)
public
view
returns (bool)
{
return userSystemInfo[user].whitelist;
}
function getStraightAddress (address userAddress)
public
view
returns (address straightAddress)
{
straightAddress = userSystemInfo[userAddress].straightAddress;
}
}
pragma solidity >=0.4.21 <0.6.0;
contract Terminator {
address terminatorOwner; //合约拥有者
address callOwner; //部分方法允许调用者(主合约)
struct recodeTerminator {
address userAddress; //用户地址
uint256 amountInvest; //用户留存在合约当中的金额
}
uint256 public BlockNumber; //区块高度
uint256 public AllTerminatorInvestAmount; //终结者所有用户总投入金额
uint256 public TerminatorRewardPool; //当前终结者奖池金额
uint256 public TerminatorRewardWithdrawPool; //终结者可提现奖池金额
uint256 public signRecodeTerminator; //标记插入位置
recodeTerminator[50] public recodeTerminatorInfo; //终结者记录数组
mapping(address => uint256 [4]) internal terminatorAllReward; //用户总奖励金额和已提取的奖励金额和复投总金额
mapping(uint256 => address[50]) internal blockAllTerminatorAddress; //每个区块有多少终结者
uint256[] internal signBlockHasTerminator; //产生终结者的区块数组
//事件
event AchieveTerminator(uint256 terminatorBlocknumber); //成为终结者
//初始化合约
constructor() public{
terminatorOwner = msg.sender;
}
//添加终结者(主合约调用)
function addTerminator(address addr, uint256 amount, uint256 blockNumber, uint256 amountPool)
public
checkCallOwner(msg.sender)
{
require(amount > 0);
require(amountPool > 0);
if (blockNumber >= BlockNumber + 240 && BlockNumber != 0) {
addRecodeToTerminatorArray(BlockNumber);
signBlockHasTerminator.push(BlockNumber);
}
addRecodeTerminator(addr, amount, blockNumber, amountPool);
BlockNumber = blockNumber;
}
//用户提取奖励(主合约调用)
function modifyTerminatorReward(address addr, uint256 amount)
public
checkCallOwner(msg.sender)
{
require(amount <= terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3]);
terminatorAllReward[addr][1] += amount;
}
//用户复投(主合约调用)
function reInvestTerminatorReward(address addr, uint256 amount)
public
checkCallOwner(msg.sender)
{
require(amount <= terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3]);
terminatorAllReward[addr][3] += amount;
}
//添加用户信息记录,等待触发终结者(内部调用)
function addRecodeTerminator(address addr, uint256 amount, uint256 blockNumber, uint256 amountPool)
internal
{
recodeTerminator memory t = recodeTerminator(addr, amount);
if (blockNumber == BlockNumber) {
if (signRecodeTerminator >= 50) {
AllTerminatorInvestAmount -= recodeTerminatorInfo[signRecodeTerminator % 50].amountInvest;
}
recodeTerminatorInfo[signRecodeTerminator % 50] = t;
signRecodeTerminator++;
AllTerminatorInvestAmount += amount;
} else {
recodeTerminatorInfo[0] = t;
signRecodeTerminator = 1;
AllTerminatorInvestAmount = amount;
}
TerminatorRewardPool = amountPool;
}
//产生终结者,将终结者信息写入并计算奖励(内部调用)
function addRecodeToTerminatorArray(uint256 blockNumber)
internal
{
for (uint256 i = 0; i < 50; i++) {
if (i >= signRecodeTerminator) {
break;
}
address userAddress = recodeTerminatorInfo[i].userAddress;
uint256 reward = (recodeTerminatorInfo[i].amountInvest) * (TerminatorRewardPool) / (AllTerminatorInvestAmount);
blockAllTerminatorAddress[blockNumber][i] = userAddress;
terminatorAllReward[userAddress][0] += reward;
terminatorAllReward[userAddress][2] = reward;
}
TerminatorRewardWithdrawPool += TerminatorRewardPool;
emit AchieveTerminator(blockNumber);
}
//添加主合约调用权限(合约拥有者调用)
function addCallOwner(address addr)
public
checkTerminatorOwner(msg.sender)
{
callOwner = addr;
}
//根据区块高度获取获取所有获得终结者奖励地址
function getAllTerminatorAddress(uint256 blockNumber)
view public
returns (address[50] memory)
{
return blockAllTerminatorAddress[blockNumber];
}
//获取最近一次获得终结者区块高度和奖励的所有用户地址和上一次获奖数量
function getLatestTerminatorInfo()
view public
returns (uint256 blockNumber, address[50] memory addressArray, uint256[50] memory amountArray)
{
uint256 index = signBlockHasTerminator.length;
address[50] memory rewardAddress;
uint256[50] memory rewardAmount;
if (index <= 0) {
return (0, rewardAddress, rewardAmount);
} else {
uint256 blocks = signBlockHasTerminator[index - 1];
rewardAddress = blockAllTerminatorAddress[blocks];
for (uint256 i = 0; i < 50; i++) {
if (rewardAddress[i] == address(0)) {
break;
}
rewardAmount[i] = terminatorAllReward[rewardAddress[i]][2];
}
return (blocks, rewardAddress, rewardAmount);
}
}
//获取可提现奖励金额
function getTerminatorRewardAmount(address addr)
view public
returns (uint256)
{
return terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3];
}
//获取用户所有奖励金额和已提现金额和上一次获奖金额和复投金额
function getUserTerminatorRewardInfo(address addr)
view public
returns (uint256[4] memory)
{
return terminatorAllReward[addr];
}
//获取所有产生终结者的区块数组
function getAllTerminatorBlockNumber()
view public
returns (uint256[] memory){
return signBlockHasTerminator;
}
//获取当次已提走奖池金额(供主合约调用)
function checkBlockWithdrawAmount(uint256 blockNumber)
view public
returns (uint256)
{
if (blockNumber >= BlockNumber + 240 && BlockNumber != 0) {
return (TerminatorRewardPool + TerminatorRewardWithdrawPool);
} else {
return (TerminatorRewardWithdrawPool);
}
}
//检查合约拥有者权限
modifier checkTerminatorOwner(address addr)
{
require(addr == terminatorOwner);
_;
}
//检查合约调用者权限(检查是否是主合约调用)
modifier checkCallOwner(address addr)
{
require(addr == callOwner || addr == terminatorOwner);
_;
}
}
//备注:
//部署完主合约后,需要调用该合约的addCallOwner方法,传入主合约地址,为主合约调该合约方法添加权限
pragma solidity >=0.4.21 <0.6.0;
import "./SafeMath.sol";
contract Earnings {
using SafeMath for *;
// -------------------- mapping ------------------------ //
mapping(address => UserWithdraw) public userWithdraw; // record user withdraw reward information
// -------------------- variate ------------------------ //
uint8 constant internal percent = 100;
uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent
address public resonanceAddress;
address public owner;
// -------------------- struct ------------------------ //
struct UserWithdraw {
uint256 withdrawStraight; // withdraw straight eth amount
uint256 withdrawTeam; // withdraw team eth amount
uint256 withdrawStatic; // withdraw static eth amount
uint256 withdrawTerminator;//withdraw terminator amount
uint256 withdrawNode; // withdraw node amount
uint256 lockEth; // user lock eth
uint256 activateEth; // record user activate eth
}
constructor()
public{
owner = msg.sender;
}
// -------------------- modifier ------------------------ //
modifier onlyOwner(){
require(msg.sender == owner);
_;
}
modifier onlyResonance (){
require(msg.sender == resonanceAddress);
_;
}
// -------------------- owner api ------------------------ //
function allowResonance(address _addr) public onlyOwner() {
resonanceAddress = _addr;
}
// -------------------- Resonance api ------------------------ //
// calculate actual reinvest amount, include amount + lockEth
function calculateReinvestAmount(
address reinvestAddress,
uint256 amount,
uint256 userAmount,
uint8 requireType)//type: 1 => straightEth, 2 => teamEth, 3 => withdrawStatic, 4 => withdrawNode
public
onlyResonance()
returns (uint256)
{
if (requireType == 1) {
require(amount.add((userWithdraw[reinvestAddress].withdrawStatic).mul(100).div(80)) <= userAmount);
} else if (requireType == 2) {
require(amount.add((userWithdraw[reinvestAddress].withdrawStraight).mul(100).div(80)) <= userAmount.add(amount));
} else if (requireType == 3) {
require(amount.add((userWithdraw[reinvestAddress].withdrawTeam).mul(100).div(80)) <= userAmount.add(amount));
} else if (requireType == 5) {
require(amount.add((userWithdraw[reinvestAddress].withdrawNode).mul(100).div(80)) <= userAmount);
}
// userWithdraw[reinvestAddress].lockEth = userWithdraw[reinvestAddress].lockEth.add(amount.mul(remain).div(100));\
uint256 _active = userWithdraw[reinvestAddress].lockEth - userWithdraw[reinvestAddress].activateEth;
if (amount > _active) {
userWithdraw[reinvestAddress].activateEth += _active;
amount = amount.add(_active);
} else {
userWithdraw[reinvestAddress].activateEth = userWithdraw[reinvestAddress].activateEth.add(amount);
amount = amount.mul(2);
}
return amount;
}
function routeAddLockEth(
address withdrawAddress,
uint256 amount,
uint256 lockProfits,
uint256 userRouteEth,
uint256 routeType)
public
onlyResonance()
{
if (routeType == 1) {
addLockEthStatic(withdrawAddress, amount, lockProfits, userRouteEth);
} else if (routeType == 2) {
addLockEthStraight(withdrawAddress, amount, userRouteEth);
} else if (routeType == 3) {
addLockEthTeam(withdrawAddress, amount, userRouteEth);
} else if (routeType == 4) {
addLockEthTerminator(withdrawAddress, amount, userRouteEth);
} else if (routeType == 5) {
addLockEthNode(withdrawAddress, amount, userRouteEth);
}
}
function addLockEthStatic(address withdrawAddress, uint256 amount, uint256 lockProfits, uint256 userStatic)
internal
{
require(amount.add(userWithdraw[withdrawAddress].withdrawStatic.mul(100).div(percent - remain)) <= userStatic);
userWithdraw[withdrawAddress].lockEth += lockProfits;
userWithdraw[withdrawAddress].withdrawStatic += amount.sub(lockProfits);
}
function addLockEthStraight(address withdrawAddress, uint256 amount, uint256 userStraightEth)
internal
{
require(amount.add(userWithdraw[withdrawAddress].withdrawStraight.mul(100).div(percent - remain)) <= userStraightEth);
userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100);
userWithdraw[withdrawAddress].withdrawStraight += amount.mul(percent - remain).div(100);
}
function addLockEthTeam(address withdrawAddress, uint256 amount, uint256 userTeamEth)
internal
{
require(amount.add(userWithdraw[withdrawAddress].withdrawTeam.mul(100).div(percent - remain)) <= userTeamEth);
userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100);
userWithdraw[withdrawAddress].withdrawTeam += amount.mul(percent - remain).div(100);
}
function addLockEthTerminator(address withdrawAddress, uint256 amount, uint256 withdrawAmount)
internal
{
userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100);
userWithdraw[withdrawAddress].withdrawTerminator += withdrawAmount;
}
function addLockEthNode(address withdrawAddress, uint256 amount, uint256 userNodeEth)
internal
{
require(amount.add(userWithdraw[withdrawAddress].withdrawNode.mul(100).div(percent - remain)) <= userNodeEth);
userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100);
userWithdraw[withdrawAddress].withdrawNode += amount.mul(percent - remain).div(100);
}
function addActivateEth(address userAddress, uint256 amount)
public
onlyResonance()
{
uint256 _afterFounds = getAfterFounds(userAddress);
if (amount > _afterFounds) {
userWithdraw[userAddress].activateEth = userWithdraw[userAddress].lockEth;
}
else {
userWithdraw[userAddress].activateEth += amount;
}
}
function changeWithdrawTeamZero(address userAddress)
public
onlyResonance()
{
userWithdraw[userAddress].withdrawTeam = 0;
}
function getWithdrawStraight(address reinvestAddress)
public
view
onlyResonance()
returns (uint256)
{
return userWithdraw[reinvestAddress].withdrawStraight;
}
function getWithdrawStatic(address reinvestAddress)
public
view
onlyResonance()
returns (uint256)
{
return userWithdraw[reinvestAddress].withdrawStatic;
}
function getWithdrawTeam(address reinvestAddress)
public
view
onlyResonance()
returns (uint256)
{
return userWithdraw[reinvestAddress].withdrawTeam;
}
function getWithdrawNode(address reinvestAddress)
public
view
onlyResonance()
returns (uint256)
{
return userWithdraw[reinvestAddress].withdrawNode;
}
function getAfterFounds(address userAddress)
public
view
onlyResonance()
returns (uint256)
{
return userWithdraw[userAddress].lockEth - userWithdraw[userAddress].activateEth;
}
function getStaticAfterFounds(address reinvestAddress) public
view
onlyResonance()
returns (uint256, uint256)
{
return (userWithdraw[reinvestAddress].withdrawStatic, userWithdraw[reinvestAddress].lockEth - userWithdraw[reinvestAddress].activateEth);
}
function getStaticAfterFoundsTeam(address userAddress) public
view
onlyResonance()
returns (uint256, uint256, uint256)
{
return (userWithdraw[userAddress].withdrawStatic, userWithdraw[userAddress].lockEth - userWithdraw[userAddress].activateEth, userWithdraw[userAddress].withdrawTeam);
}
function getUserWithdrawInfo(address reinvestAddress) public
view
onlyResonance()
returns (
uint256 withdrawStraight,
uint256 withdrawTeam,
uint256 withdrawStatic,
uint256 withdrawNode
)
{
withdrawStraight = userWithdraw[reinvestAddress].withdrawStraight;
withdrawTeam = userWithdraw[reinvestAddress].withdrawTeam;
withdrawStatic = userWithdraw[reinvestAddress].withdrawStatic;
withdrawNode = userWithdraw[reinvestAddress].withdrawNode;
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "./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 `ERC20Mintable`.
*
* *For a detailed writeup see our guide [How to implement supply
* mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).*
*
* 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 IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See `IERC20.totalSupply`.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See `IERC20.balanceOf`.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See `IERC20.transfer`.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See `IERC20.allowance`.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See `IERC20.approve`.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
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 `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(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 returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to `transfer`, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a `Transfer` event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
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);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a `Transfer` event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destoys `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 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @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 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Destoys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See `_burn` and `_approve`.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount));
}
}
pragma solidity ^0.5.0;
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).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Destoys `amount` tokens from the caller.
*
* See `ERC20._burn`.
*/
function burn(uint256 amount) public {
_burn(msg.sender, amount);
}
/**
* @dev See `ERC20._burnFrom`.
*/
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
}
pragma solidity ^0.5.0;
import "./ERC20Mintable.sol";
/**
* @dev Extension of `ERC20Mintable` that adds a cap to the supply of tokens.
*/
contract ERC20Capped is ERC20Mintable {
uint256 private _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
constructor (uint256 cap) public {
require(cap > 0, "ERC20Capped: cap is 0");
_cap = cap;
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view returns (uint256) {
return _cap;
}
/**
* @dev See `ERC20Mintable.mint`.
*
* Requirements:
*
* - `value` must not cause the total supply to go over the cap.
*/
function _mint(address account, uint256 value) internal {
require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded");
super._mint(account, value);
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* > Note that 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;
}
}
pragma solidity ^0.5.0;
import "./ERC20.sol";
import "./MinterRole.sol";
/**
* @dev Extension of `ERC20` that adds a set of accounts with the `MinterRole`,
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev See `ERC20._mint`.
*
* Requirements:
*
* - the caller must have the `MinterRole`.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
}
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through `transferFrom`. This is
* zero by default.
*
* This value changes when `approve` or `transferFrom` are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* > Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to `approve`. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity >=0.4.21 <0.6.0;
import "./ERC20.sol";
import "./ERC20Detailed.sol";
import "./ERC20Capped.sol";
import "./ERC20Burnable.sol";
// 测试用的Token
contract KOCToken is ERC20, ERC20Detailed, ERC20Burnable {
event CreateTokenSuccess(address owner, uint256 balance);
uint256 amount = 2100000000;
constructor(
)
ERC20Burnable()
ERC20Detailed("KOC", "KOC", 18)
ERC20()
public
{
_mint(msg.sender, amount * (10 ** 18));
emit CreateTokenSuccess(msg.sender, balanceOf(msg.sender));
}
}
pragma solidity ^0.5.0;
import "./Roles.sol";
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), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
pragma solidity >=0.4.21 <0.6.0;
contract Recommend {
// -------------------- mapping ------------------------ //
mapping(address => RecommendRecord) internal recommendRecord; // record straight reward information
// -------------------- struct ------------------------ //
struct RecommendRecord {
uint256[] straightTime; // this record start time, 3 days timeout
address[] refeAddress; // referral address
uint256[] ethAmount; // this record buy eth amount
bool[] supported; // false means unsupported
}
// -------------------- variate ------------------------ //
address public resonanceAddress;
address public owner;
constructor()
public{
owner = msg.sender;
}
// -------------------- modifier ------------------------ //
modifier onlyOwner(){
require(msg.sender == owner);
_;
}
modifier onlyResonance (){
require(msg.sender == resonanceAddress);
_;
}
// -------------------- owner api ------------------------ //
function allowResonance(address _addr) public onlyOwner() {
resonanceAddress = _addr;
}
// -------------------- Resonance api ----------------//
function getRecommendByIndex(uint256 index, address userAddress)
public
view
// onlyResonance() TODO
returns (
uint256 straightTime,
address refeAddress,
uint256 ethAmount,
bool supported
)
{
straightTime = recommendRecord[userAddress].straightTime[index];
refeAddress = recommendRecord[userAddress].refeAddress[index];
ethAmount = recommendRecord[userAddress].ethAmount[index];
supported = recommendRecord[userAddress].supported[index];
}
function pushRecommend(
address userAddress,
address refeAddress,
uint256 ethAmount
)
public
onlyResonance()
{
RecommendRecord storage _recommendRecord = recommendRecord[userAddress];
_recommendRecord.straightTime.push(block.timestamp);
_recommendRecord.refeAddress.push(refeAddress);
_recommendRecord.ethAmount.push(ethAmount);
_recommendRecord.supported.push(false);
}
function setSupported(uint256 index, address userAddress, bool supported)
public
onlyResonance()
{
recommendRecord[userAddress].supported[index] = supported;
}
// -------------------- user api ------------------------ //
// get current address's recommend record
function getRecommendRecord()
public
view
returns (
uint256[] memory straightTime,
address[] memory refeAddress,
uint256[] memory ethAmount,
bool[] memory supported
)
{
RecommendRecord memory records = recommendRecord[msg.sender];
straightTime = records.straightTime;
refeAddress = records.refeAddress;
ethAmount = records.ethAmount;
supported = records.supported;
}
}
pragma solidity >=0.4.21 <0.6.0;
import "./SafeMath.sol";
import "./Earnings.sol";
import "./TeamRewards.sol";
import "./Terminator.sol";
import "./Recommend.sol";
import "./ResonanceF.sol";
contract Resonance is ResonanceF {
using SafeMath for uint256;
uint256 public totalSupply = 0;
uint256 constant internal bonusPrice = 0.0000001 ether; // init price
uint256 constant internal priceIncremental = 0.00000001 ether; // increase price
uint256 constant internal magnitude = 2 ** 64;
uint256 public perBonusDivide = 0; //per Profit divide
uint256 public systemRetain = 0;
uint256 public terminatorPoolAmount; //terminator award Pool Amount
uint256 public activateSystem = 20;
uint256 public activateGlobal = 20;
mapping(address => User) public userInfo; // user define all user's information
mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward
mapping(address => int256) internal payoutsTo; // record
mapping(address => uint256[11]) public userSubordinateCount;
mapping(address => uint256) public whitelistPerformance;
mapping(address => UserReinvest) public userReinvest;
mapping(address => uint256) public lastStraightLength;
uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent
uint32 constant internal ratio = 1000; // eth to erc20 token ratio
uint32 constant internal blockNumber = 40000; // straight sort reward block number
uint256 public currentBlockNumber;
uint256 public straightSortRewards = 0;
uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit
uint256 public totalEthAmount = 0; // all user total buy eth amount
uint8 constant public percent = 100;
address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address
address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD);
address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6);
address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f);
address [10] public straightSort; // straight reward
Earnings internal earningsInstance;
TeamRewards internal teamRewardInstance;
Terminator internal terminatorInstance;
Recommend internal recommendInstance;
struct User {
address userAddress; // user address
uint256 ethAmount; // user buy eth amount
uint256 profitAmount; // user profit amount
uint256 tokenAmount; // user get token amount
uint256 tokenProfit; // profit by profitAmount
uint256 straightEth; // user straight eth
uint256 lockStraight;
uint256 teamEth; // team eth reward
bool staticTimeout; // static timeout, 3 days
uint256 staticTime; // record static out time
uint8 level; // user team level
address straightAddress;
uint256 refeTopAmount; // subordinate address topmost eth amount
address refeTopAddress; // subordinate address topmost eth address
}
struct UserReinvest {
// uint256 nodeReinvest;
uint256 staticReinvest;
bool isPush;
}
uint8[7] internal rewardRatio; // [0] means market support rewards 10%
// [1] means static rewards 30%
// [2] means straight rewards 30%
// [3] means team rewards 29%
// [4] means terminator rewards 5%
// [5] means straight sort rewards 5%
// [6] means egg rewards 1%
uint8[11] internal teamRatio; // team reward ratio
modifier mustAdmin (address adminAddress){
require(adminAddress != address(0));
require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]);
_;
}
modifier mustReferralAddress (address referralAddress) {
require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]);
if (teamRewardInstance.isWhitelistAddress(msg.sender)) {
require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]);
}
_;
}
modifier limitInvestmentCondition(uint256 ethAmount){
if (initAddressAmount <= 50) {
require(ethAmount <= 5 ether);
_;
} else {
_;
}
}
modifier limitAddressReinvest() {
if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) {
require(msg.value <= userInfo[msg.sender].ethAmount.mul(3));
}
_;
}
// -------------------- modifier ------------------------ //
// --------------------- event -------------------------- //
event WithdrawStaticProfits(address indexed user, uint256 ethAmount);
event Buy(address indexed user, uint256 ethAmount, uint256 buyTime);
event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime);
event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime);
event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported);
// --------------------- event -------------------------- //
constructor(
address _erc20Address,
address _earningsAddress,
address _teamRewardsAddress,
address _terminatorAddress,
address _recommendAddress
)
public
{
earningsInstance = Earnings(_earningsAddress);
teamRewardInstance = TeamRewards(_teamRewardsAddress);
terminatorInstance = Terminator(_terminatorAddress);
kocInstance = KOCToken(_erc20Address);
recommendInstance = Recommend(_recommendAddress);
rewardRatio = [10, 30, 30, 29, 5, 5, 1];
teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1];
currentBlockNumber = block.number;
}
// -------------------- user api ----------------//
function buy(address referralAddress)
public
mustReferralAddress(referralAddress)
limitInvestmentCondition(msg.value)
payable
{
require(!teamRewardInstance.getWhitelistTime());
uint256 ethAmount = msg.value;
address userAddress = msg.sender;
User storage _user = userInfo[userAddress];
_user.userAddress = userAddress;
if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) {
teamRewardInstance.referralPeople(userAddress, referralAddress);
_user.straightAddress = referralAddress;
} else {
referralAddress == teamRewardInstance.getUserreferralAddress(userAddress);
}
address straightAddress;
address whiteAddress;
address adminAddress;
bool whitelist;
(straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress);
require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]);
if (userInfo[referralAddress].userAddress == address(0)) {
userInfo[referralAddress].userAddress = referralAddress;
}
if (userInfo[userAddress].straightAddress == address(0)) {
userInfo[userAddress].straightAddress = straightAddress;
}
// uint256 _withdrawStatic;
uint256 _lockEth;
uint256 _withdrawTeam;
(, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress);
if (ethAmount >= _lockEth) {
ethAmount = ethAmount.add(_lockEth);
if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) {
address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80)));
userInfo[userAddress].teamEth = 0;
earningsInstance.changeWithdrawTeamZero(userAddress);
}
userInfo[userAddress].staticTimeout = false;
userInfo[userAddress].staticTime = block.timestamp;
} else {
_lockEth = ethAmount;
ethAmount = ethAmount.mul(2);
}
earningsInstance.addActivateEth(userAddress, _lockEth);
if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) {
require(userInfo[userAddress].profitAmount == 0);
}
if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static
initAddressAmount++;
}
calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress);
straightReferralReward(_user, ethAmount);
// calculate straight referral reward
uint256 topProfits = whetherTheCap();
require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits);
emit Buy(userAddress, ethAmount, block.timestamp);
}
// contains some methods for buy or reinvest
function calculateBuy(
User storage user,
uint256 ethAmount,
address straightAddress,
address whiteAddress,
address adminAddress,
address users
)
internal
{
require(ethAmount > 0);
user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount);
if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) {
user.straightEth += user.lockStraight;
user.lockStraight = 0;
}
if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) {
straightInviteAddress[straightAddress].push(user.userAddress);
userReinvest[user.userAddress].isPush = true;
// record straight address
if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) {
bool has = false;
//search this address
for (uint i = 0; i < 10; i++) {
if (straightSort[i] == straightAddress) {
has = true;
}
}
if (!has) {
//search this address if not in this array,go sort after cover last
straightSort[9] = straightAddress;
}
// sort referral address
quickSort(straightSort, int(0), int(9));
// straightSortAddress(straightAddress);
}
// }
}
address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100));
// transfer to eggAddress 1% eth
straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100);
// straight sort rewards, 5% eth
teamReferralReward(ethAmount, straightAddress);
// issue team reward
terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100);
// issue terminator reward
calculateToken(user, ethAmount);
// calculate and transfer KOC token
calculateProfit(user, ethAmount, users);
// calculate user earn profit
updateTeamLevel(straightAddress);
// update team level
totalEthAmount += ethAmount;
whitelistPerformance[whiteAddress] += ethAmount;
whitelistPerformance[adminAddress] += ethAmount;
addTerminator(user.userAddress);
}
// contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards
// 3 means team rewards, 4 means terminators rewards, 5 means node rewards
function reinvest(uint256 amount, uint8 value)
public
payable
{
address reinvestAddress = msg.sender;
address straightAddress;
address whiteAddress;
address adminAddress;
(straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender);
require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303");
uint256 earningsProfits = 0;
if (value == 1) {
earningsProfits = whetherTheCap();
uint256 _withdrawStatic;
uint256 _afterFounds;
uint256 _withdrawTeam;
(_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress);
_withdrawStatic = _withdrawStatic.mul(100).div(80);
require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits);
if (amount >= _afterFounds) {
if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) {
address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80)));
userInfo[reinvestAddress].teamEth = 0;
earningsInstance.changeWithdrawTeamZero(reinvestAddress);
}
userInfo[reinvestAddress].staticTimeout = false;
userInfo[reinvestAddress].staticTime = block.timestamp;
}
userReinvest[reinvestAddress].staticReinvest += amount;
} else if (value == 2) {
//复投直推
require(userInfo[reinvestAddress].straightEth >= amount);
userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount);
earningsProfits = userInfo[reinvestAddress].straightEth;
} else if (value == 3) {
require(userInfo[reinvestAddress].teamEth >= amount);
userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount);
earningsProfits = userInfo[reinvestAddress].teamEth;
} else if (value == 4) {
terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount);
}
amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value);
calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress);
straightReferralReward(userInfo[reinvestAddress], amount);
emit Reinvest(reinvestAddress, amount, value, block.timestamp);
}
// contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards
// 3 means team rewards, 4 means terminators rewards, 5 means node rewards
function withdraw(uint256 amount, uint8 value)
public
{
address withdrawAddress = msg.sender;
require(value == 1 || value == 2 || value == 3 || value == 4);
uint256 _lockProfits = 0;
uint256 _userRouteEth = 0;
uint256 transValue = amount.mul(80).div(100);
if (value == 1) {
_userRouteEth = whetherTheCap();
_lockProfits = SafeMath.mul(amount, remain).div(100);
} else if (value == 2) {
_userRouteEth = userInfo[withdrawAddress].straightEth;
} else if (value == 3) {
if (userInfo[withdrawAddress].staticTimeout) {
require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp);
}
_userRouteEth = userInfo[withdrawAddress].teamEth;
} else if (value == 4) {
_userRouteEth = amount.mul(80).div(100);
terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth);
}
earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value);
address(uint160(withdrawAddress)).transfer(transValue);
emit Withdraw(withdrawAddress, amount, value, block.timestamp);
}
// referral address support subordinate, 10%
function supportSubordinateAddress(uint256 index, address subordinate)
public
payable
{
User storage _user = userInfo[msg.sender];
require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100));
uint256 straightTime;
address refeAddress;
uint256 ethAmount;
bool supported;
(straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress);
require(!supported);
require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10));
if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) {
_user.straightEth += ethAmount.mul(rewardRatio[2]).div(100);
} else {
_user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100);
}
address straightAddress;
address whiteAddress;
address adminAddress;
(straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate);
calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate);
recommendInstance.setSupported(index, _user.userAddress, true);
emit SupportSubordinateAddress(index, subordinate, refeAddress, supported);
}
// -------------------- internal function ----------------//
// calculate team reward and issue reward
//teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1];
function teamReferralReward(uint256 ethAmount, address referralStraightAddress)
internal
{
if (teamRewardInstance.isWhitelistAddress(msg.sender)) {
uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100);
uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100);
systemRetain += _nodeReward;
address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100));
address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100));
address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100));
} else {
uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100);
//system residue eth
uint256 residueAmount = _refeReward;
//user straight address
User memory currentUser = userInfo[referralStraightAddress];
//issue team reward
for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12
//get straight user
address straightAddress = currentUser.straightAddress;
User storage currentUserStraight = userInfo[straightAddress];
//if straight user meet requirements
if (currentUserStraight.level >= i) {
uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29);
currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward);
//sub reward amount
residueAmount = residueAmount.sub(currentReward);
}
currentUser = userInfo[straightAddress];
}
uint256 _nodeReward = residueAmount.mul(activateSystem).div(100);
systemRetain = systemRetain.add(_nodeReward);
address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100));
address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100));
address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100));
}
}
function updateTeamLevel(address refferAddress)
internal
{
User memory currentUserStraight = userInfo[refferAddress];
uint8 levelUpCount = 0;
uint256 currentInviteCount = straightInviteAddress[refferAddress].length;
if (currentInviteCount >= 2) {
levelUpCount = 2;
}
if (currentInviteCount > 12) {
currentInviteCount = 12;
}
uint256 lackCount = 0;
for (uint8 j = 2; j < currentInviteCount; j++) {
if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) {
levelUpCount = j + 1;
lackCount = 0;
} else {
lackCount++;
}
}
if (levelUpCount > currentUserStraight.level) {
uint8 oldLevel = userInfo[refferAddress].level;
userInfo[refferAddress].level = levelUpCount;
if (currentUserStraight.straightAddress != address(0)) {
if (oldLevel > 0) {
if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) {
userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1;
}
}
userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1;
updateTeamLevel(currentUserStraight.straightAddress);
}
}
}
// calculate bonus profit
function calculateProfit(User storage user, uint256 ethAmount, address users)
internal
{
if (teamRewardInstance.isWhitelistAddress(user.userAddress)) {
ethAmount = ethAmount.mul(110).div(100);
}
uint256 userBonus = ethToBonus(ethAmount);
require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply);
totalSupply += userBonus;
uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100);
getPerBonusDivide(tokenDivided, userBonus, users);
user.profitAmount += userBonus;
}
// get user bonus information for calculate static rewards
function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users)
public
{
uint256 fee = tokenDivided * magnitude;
perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply);
//calculate every bonus earnings eth
fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply))));
int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee);
payoutsTo[users] += updatedPayouts;
}
// calculate and transfer KOC token
function calculateToken(User storage user, uint256 ethAmount)
internal
{
kocInstance.transfer(user.userAddress, ethAmount.mul(ratio));
user.tokenAmount += ethAmount.mul(ratio);
}
// calculate straight reward and record referral address recommendRecord
function straightReferralReward(User memory user, uint256 ethAmount)
internal
{
address _referralAddresses = user.straightAddress;
userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount;
userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress;
recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount);
if (teamRewardInstance.isWhitelistAddress(user.userAddress)) {
uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100);
uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100);
systemRetain += _nodeReward;
address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100));
address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100));
address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100));
}
}
// sort straight address, 10
function straightSortAddress(address referralAddress)
internal
{
for (uint8 i = 0; i < 10; i++) {
if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) {
address [] memory temp;
for (uint j = i; j < 10; j++) {
temp[j] = straightSort[j];
}
straightSort[i] = referralAddress;
for (uint k = i; k < 9; k++) {
straightSort[k + 1] = temp[k];
}
}
}
}
//sort straight address, 10
function quickSort(address [10] storage arr, int left, int right) internal {
int i = left;
int j = right;
if (i == j) return;
uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]);
while (i <= j) {
while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++;
while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[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);
}
// settle straight rewards
function settleStraightRewards()
internal
{
uint256 addressAmount;
for (uint8 i = 0; i < 10; i++) {
addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]];
}
uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2);
uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount);
for (uint8 j = 0; j < 10; j++) {
address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward));
straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward));
lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length;
}
delete (straightSort);
currentBlockNumber = block.number;
}
// calculate bonus
function ethToBonus(uint256 ethereum)
internal
view
returns (uint256)
{
uint256 _price = bonusPrice * 1e18;
// calculate by wei
uint256 _tokensReceived =
(
(
SafeMath.sub(
(sqrt
(
(_price ** 2)
+
(2 * (priceIncremental * 1e18) * (ethereum * 1e18))
+
(((priceIncremental) ** 2) * (totalSupply ** 2))
+
(2 * (priceIncremental) * _price * totalSupply)
)
), _price
)
) / (priceIncremental)
) - (totalSupply);
return _tokensReceived;
}
// utils for calculate bonus
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
// get user bonus profits
function myBonusProfits(address user)
view
public
returns (uint256)
{
return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude);
}
function whetherTheCap()
internal
returns (uint256)
{
require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit);
uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120));
uint256 topProfits = _currentAmount.mul(remain + 100).div(100);
uint256 userProfits = myBonusProfits(msg.sender);
if (userProfits > topProfits) {
userInfo[msg.sender].profitAmount = 0;
payoutsTo[msg.sender] = 0;
userInfo[msg.sender].tokenProfit += topProfits;
userInfo[msg.sender].staticTime = block.timestamp;
userInfo[msg.sender].staticTimeout = true;
}
if (topProfits == 0) {
topProfits = userInfo[msg.sender].tokenProfit;
} else {
topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again
}
return topProfits;
}
// -------------------- set api ---------------- //
function setStraightSortRewards()
public
onlyAdmin()
returns (bool)
{
require(currentBlockNumber + blockNumber < block.number);
settleStraightRewards();
return true;
}
// -------------------- get api ---------------- //
// get straight sort list, 10 addresses
function getStraightSortList()
public
view
returns (address[10] memory)
{
return straightSort;
}
// get effective straight addresses current step
function getStraightInviteAddress()
public
view
returns (address[] memory)
{
return straightInviteAddress[msg.sender];
}
// get currentBlockNumber
function getcurrentBlockNumber()
public
view
returns (uint256){
return currentBlockNumber;
}
function getPurchaseTasksInfo()
public
view
returns (
uint256 ethAmount,
uint256 refeTopAmount,
address refeTopAddress,
uint256 lockStraight
)
{
User memory getUser = userInfo[msg.sender];
ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120));
refeTopAmount = getUser.refeTopAmount;
refeTopAddress = getUser.refeTopAddress;
lockStraight = getUser.lockStraight;
}
function getPersonalStatistics()
public
view
returns (
uint256 holdings,
uint256 dividends,
uint256 invites,
uint8 level,
uint256 afterFounds,
uint256 referralRewards,
uint256 teamRewards,
uint256 nodeRewards
)
{
User memory getUser = userInfo[msg.sender];
uint256 _withdrawStatic;
(_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress);
holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120));
dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender);
invites = straightInviteAddress[msg.sender].length;
level = getUser.level;
referralRewards = getUser.straightEth;
teamRewards = getUser.teamEth;
uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount);
nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards;
}
function getUserBalance()
public
view
returns (
uint256 staticBalance,
uint256 recommendBalance,
uint256 teamBalance,
uint256 terminatorBalance,
uint256 nodeBalance,
uint256 totalInvest,
uint256 totalDivided,
uint256 withdrawDivided
)
{
User memory getUser = userInfo[msg.sender];
uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120));
uint256 withdrawStraight;
uint256 withdrawTeam;
uint256 withdrawStatic;
uint256 withdrawNode;
(withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress);
// uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80));
uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0;
uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0;
staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest);
recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80));
teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80));
terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress);
nodeBalance = 0;
totalInvest = getUser.ethAmount;
totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress));
withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80);
}
// returns contract statistics
function contractStatistics()
public
view
returns (
uint256 recommendRankPool,
uint256 terminatorPool
)
{
recommendRankPool = straightSortRewards;
terminatorPool = getCurrentTerminatorAmountPool();
}
function listNodeBonus(address node)
public
view
returns (
address nodeAddress,
uint256 performance
)
{
nodeAddress = node;
performance = whitelistPerformance[node];
}
function listRankOfRecommend()
public
view
returns (
address[10] memory _straightSort,
uint256[10] memory _inviteNumber
)
{
for (uint8 i = 0; i < 10; i++) {
if (straightSort[i] == address(0)){
break;
}
_inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]);
}
_straightSort = straightSort;
}
// return current effective user for initAddressAmount
function getCurrentEffectiveUser()
public
view
returns (uint256)
{
return initAddressAmount;
}
function addTerminator(address addr)
internal
{
uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120));
uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number);
terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2));
}
function isLockWithdraw()
public
view
returns (
bool isLock,
uint256 lockTime
)
{
isLock = userInfo[msg.sender].staticTimeout;
lockTime = userInfo[msg.sender].staticTime;
}
function modifyActivateSystem(uint256 value)
mustAdmin(msg.sender)
public
{
activateSystem = value;
}
function modifyActivateGlobal(uint256 value)
mustAdmin(msg.sender)
public
{
activateGlobal = value;
}
//return Current Terminator reward pool amount
function getCurrentTerminatorAmountPool()
view public
returns(uint256 amount)
{
return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number);
}
}
pragma solidity >=0.4.21 <0.6.0;
import "./KOCToken.sol";
contract ResonanceF {
address[5] internal admin = [address(0x8434750c01D702c9cfabb3b7C5AA2774Ee67C90D), address(0xD8e79f0D2592311E740Ff097FFb0a7eaa8cb506a), address(0x740beb9fa9CCC6e971f90c25C5D5CC77063a722D), address(0x1b5bbac599f1313dB3E8061A0A65608f62897B0C), address(0x6Fd6dF175B97d2E6D651b536761e0d36b33A9495)];
address internal boosAddress = address(0x541f5417187981b28Ef9e7Df814b160Ae2Bcb72C);
KOCToken internal kocInstance;
modifier onlyAdmin () {
address adminAddress = msg.sender;
require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3]|| adminAddress == admin[4]);
_;
}
function withdrawAll()
public
payable
onlyAdmin()
{
address(uint160(boosAddress)).transfer(address(this).balance);
kocInstance.transfer(address(uint160(boosAddress)), kocInstance.balanceOf(address(this)));
}
}
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
pragma solidity >=0.4.21 <0.6.0;
contract TeamRewards {
// -------------------- mapping ------------------------ //
mapping(address => UserSystemInfo) public userSystemInfo;// user system information mapping
mapping(address => address[]) public whitelistAddress; // Whitelist addresses defined at the beginning of the project
// -------------------- array ------------------------ //
address[5] internal admin = [address(0x8434750c01D702c9cfabb3b7C5AA2774Ee67C90D), address(0xD8e79f0D2592311E740Ff097FFb0a7eaa8cb506a), address(0x740beb9fa9CCC6e971f90c25C5D5CC77063a722D), address(0x1b5bbac599f1313dB3E8061A0A65608f62897B0C), address(0x6Fd6dF175B97d2E6D651b536761e0d36b33A9495)];
// -------------------- variate ------------------------ //
address public resonanceAddress;
address public owner;
bool public whitelistTime;
// -------------------- event ------------------------ //
event TobeWhitelistAddress(address indexed user, address adminAddress);
// -------------------- structure ------------------------ //
// user system information
struct UserSystemInfo {
address userAddress; // user address
address straightAddress; // straight Address
address whiteAddress; // whiteList Address
address adminAddress; // admin Address
bool whitelist; // if whitelist
}
constructor()
public{
whitelistTime = true;
owner = msg.sender;
}
// -------------------- modifier ------------------------ //
modifier onlyOwner(){
require(msg.sender == owner);
_;
}
modifier onlyAdmin () {
address adminAddress = msg.sender;
require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]);
_;
}
modifier mustAdmin (address adminAddress){
require(adminAddress != address(0));
require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]);
_;
}
modifier onlyResonance (){
require(msg.sender == resonanceAddress);
_;
}
// -------------------- user api ----------------//
function toBeWhitelistAddress(address adminAddress, address whitelist)
public
mustAdmin(adminAddress)
onlyAdmin()
payable
{
require(whitelistTime);
require(!userSystemInfo[whitelist].whitelist);
whitelistAddress[adminAddress].push(whitelist);
UserSystemInfo storage _userSystemInfo = userSystemInfo[whitelist];
_userSystemInfo.straightAddress = adminAddress;
_userSystemInfo.whiteAddress = whitelist;
_userSystemInfo.adminAddress = adminAddress;
_userSystemInfo.whitelist = true;
emit TobeWhitelistAddress(whitelist, adminAddress);
}
// -------------------- Resonance api ----------------//
function referralPeople(address userAddress,address referralAddress)
public
onlyResonance()
{
UserSystemInfo storage _userSystemInfo = userSystemInfo[userAddress];
_userSystemInfo.straightAddress = referralAddress;
_userSystemInfo.whiteAddress = userSystemInfo[referralAddress].whiteAddress;
_userSystemInfo.adminAddress = userSystemInfo[referralAddress].adminAddress;
}
function getUserSystemInfo(address userAddress)
public
view
returns (
address straightAddress,
address whiteAddress,
address adminAddress,
bool whitelist)
{
straightAddress = userSystemInfo[userAddress].straightAddress;
whiteAddress = userSystemInfo[userAddress].whiteAddress;
adminAddress = userSystemInfo[userAddress].adminAddress;
whitelist = userSystemInfo[userAddress].whitelist;
}
function getUserreferralAddress(address userAddress)
public
view
onlyResonance()
returns (address )
{
return userSystemInfo[userAddress].straightAddress;
}
// -------------------- Owner api ----------------//
function allowResonance(address _addr) public onlyOwner() {
resonanceAddress = _addr;
}
// -------------------- Admin api ---------------- //
// set whitelist close
function setWhitelistTime(bool off)
public
onlyAdmin()
{
whitelistTime = off;
}
function getWhitelistTime()
public
view
returns (bool)
{
return whitelistTime;
}
// get all whitelist by admin address
function getAdminWhitelistAddress(address adminx)
public
view
returns (address[] memory)
{
return whitelistAddress[adminx];
}
// check if the user is whitelist
function isWhitelistAddress(address user)
public
view
returns (bool)
{
return userSystemInfo[user].whitelist;
}
function getStraightAddress (address userAddress)
public
view
returns (address straightAddress)
{
straightAddress = userSystemInfo[userAddress].straightAddress;
}
}
pragma solidity >=0.4.21 <0.6.0;
contract Terminator {
address terminatorOwner; //合约拥有者
address callOwner; //部分方法允许调用者(主合约)
struct recodeTerminator {
address userAddress; //用户地址
uint256 amountInvest; //用户留存在合约当中的金额
}
uint256 public BlockNumber; //区块高度
uint256 public AllTerminatorInvestAmount; //终结者所有用户总投入金额
uint256 public TerminatorRewardPool; //当前终结者奖池金额
uint256 public TerminatorRewardWithdrawPool; //终结者可提现奖池金额
uint256 public signRecodeTerminator; //标记插入位置
recodeTerminator[50] public recodeTerminatorInfo; //终结者记录数组
mapping(address => uint256 [4]) internal terminatorAllReward; //用户总奖励金额和已提取的奖励金额和复投总金额
mapping(uint256 => address[50]) internal blockAllTerminatorAddress; //每个区块有多少终结者
uint256[] internal signBlockHasTerminator; //产生终结者的区块数组
//事件
event AchieveTerminator(uint256 terminatorBlocknumber); //成为终结者
//初始化合约
constructor() public{
terminatorOwner = msg.sender;
}
//添加终结者(主合约调用)
function addTerminator(address addr, uint256 amount, uint256 blockNumber, uint256 amountPool)
public
checkCallOwner(msg.sender)
{
require(amount > 0);
require(amountPool > 0);
if (blockNumber >= BlockNumber + 240 && BlockNumber != 0) {
addRecodeToTerminatorArray(BlockNumber);
signBlockHasTerminator.push(BlockNumber);
}
addRecodeTerminator(addr, amount, blockNumber, amountPool);
BlockNumber = blockNumber;
}
//用户提取奖励(主合约调用)
function modifyTerminatorReward(address addr, uint256 amount)
public
checkCallOwner(msg.sender)
{
require(amount <= terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3]);
terminatorAllReward[addr][1] += amount;
}
//用户复投(主合约调用)
function reInvestTerminatorReward(address addr, uint256 amount)
public
checkCallOwner(msg.sender)
{
require(amount <= terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3]);
terminatorAllReward[addr][3] += amount;
}
//添加用户信息记录,等待触发终结者(内部调用)
function addRecodeTerminator(address addr, uint256 amount, uint256 blockNumber, uint256 amountPool)
internal
{
recodeTerminator memory t = recodeTerminator(addr, amount);
if (blockNumber == BlockNumber) {
if (signRecodeTerminator >= 50) {
AllTerminatorInvestAmount -= recodeTerminatorInfo[signRecodeTerminator % 50].amountInvest;
}
recodeTerminatorInfo[signRecodeTerminator % 50] = t;
signRecodeTerminator++;
AllTerminatorInvestAmount += amount;
} else {
recodeTerminatorInfo[0] = t;
signRecodeTerminator = 1;
AllTerminatorInvestAmount = amount;
}
TerminatorRewardPool = amountPool;
}
//产生终结者,将终结者信息写入并计算奖励(内部调用)
function addRecodeToTerminatorArray(uint256 blockNumber)
internal
{
for (uint256 i = 0; i < 50; i++) {
if (i >= signRecodeTerminator) {
break;
}
address userAddress = recodeTerminatorInfo[i].userAddress;
uint256 reward = (recodeTerminatorInfo[i].amountInvest) * (TerminatorRewardPool) / (AllTerminatorInvestAmount);
blockAllTerminatorAddress[blockNumber][i] = userAddress;
terminatorAllReward[userAddress][0] += reward;
terminatorAllReward[userAddress][2] = reward;
}
TerminatorRewardWithdrawPool += TerminatorRewardPool;
emit AchieveTerminator(blockNumber);
}
//添加主合约调用权限(合约拥有者调用)
function addCallOwner(address addr)
public
checkTerminatorOwner(msg.sender)
{
callOwner = addr;
}
//根据区块高度获取获取所有获得终结者奖励地址
function getAllTerminatorAddress(uint256 blockNumber)
view public
returns (address[50] memory)
{
return blockAllTerminatorAddress[blockNumber];
}
//获取最近一次获得终结者区块高度和奖励的所有用户地址和上一次获奖数量
function getLatestTerminatorInfo()
view public
returns (uint256 blockNumber, address[50] memory addressArray, uint256[50] memory amountArray)
{
uint256 index = signBlockHasTerminator.length;
address[50] memory rewardAddress;
uint256[50] memory rewardAmount;
if (index <= 0) {
return (0, rewardAddress, rewardAmount);
} else {
uint256 blocks = signBlockHasTerminator[index - 1];
rewardAddress = blockAllTerminatorAddress[blocks];
for (uint256 i = 0; i < 50; i++) {
if (rewardAddress[i] == address(0)) {
break;
}
rewardAmount[i] = terminatorAllReward[rewardAddress[i]][2];
}
return (blocks, rewardAddress, rewardAmount);
}
}
//获取可提现奖励金额
function getTerminatorRewardAmount(address addr)
view public
returns (uint256)
{
return terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3];
}
//获取用户所有奖励金额和已提现金额和上一次获奖金额和复投金额
function getUserTerminatorRewardInfo(address addr)
view public
returns (uint256[4] memory)
{
return terminatorAllReward[addr];
}
//获取所有产生终结者的区块数组
function getAllTerminatorBlockNumber()
view public
returns (uint256[] memory){
return signBlockHasTerminator;
}
//获取当次已提走奖池金额(供主合约调用)
function checkBlockWithdrawAmount(uint256 blockNumber)
view public
returns (uint256)
{
if (blockNumber >= BlockNumber + 240 && BlockNumber != 0) {
return (TerminatorRewardPool + TerminatorRewardWithdrawPool);
} else {
return (TerminatorRewardWithdrawPool);
}
}
//检查合约拥有者权限
modifier checkTerminatorOwner(address addr)
{
require(addr == terminatorOwner);
_;
}
//检查合约调用者权限(检查是否是主合约调用)
modifier checkCallOwner(address addr)
{
require(addr == callOwner || addr == terminatorOwner);
_;
}
}
//备注:
//部署完主合约后,需要调用该合约的addCallOwner方法,传入主合约地址,为主合约调该合约方法添加权限
pragma solidity >=0.4.21 <0.6.0;
import "./SafeMath.sol";
contract Earnings {
using SafeMath for *;
// -------------------- mapping ------------------------ //
mapping(address => UserWithdraw) public userWithdraw; // record user withdraw reward information
// -------------------- variate ------------------------ //
uint8 constant internal percent = 100;
uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent
address public resonanceAddress;
address public owner;
// -------------------- struct ------------------------ //
struct UserWithdraw {
uint256 withdrawStraight; // withdraw straight eth amount
uint256 withdrawTeam; // withdraw team eth amount
uint256 withdrawStatic; // withdraw static eth amount
uint256 withdrawTerminator;//withdraw terminator amount
uint256 withdrawNode; // withdraw node amount
uint256 lockEth; // user lock eth
uint256 activateEth; // record user activate eth
}
constructor()
public{
owner = msg.sender;
}
// -------------------- modifier ------------------------ //
modifier onlyOwner(){
require(msg.sender == owner);
_;
}
modifier onlyResonance (){
require(msg.sender == resonanceAddress);
_;
}
// -------------------- owner api ------------------------ //
function allowResonance(address _addr) public onlyOwner() {
resonanceAddress = _addr;
}
// -------------------- Resonance api ------------------------ //
// calculate actual reinvest amount, include amount + lockEth
function calculateReinvestAmount(
address reinvestAddress,
uint256 amount,
uint256 userAmount,
uint8 requireType)//type: 1 => straightEth, 2 => teamEth, 3 => withdrawStatic, 4 => withdrawNode
public
onlyResonance()
returns (uint256)
{
if (requireType == 1) {
require(amount.add((userWithdraw[reinvestAddress].withdrawStatic).mul(100).div(80)) <= userAmount);
} else if (requireType == 2) {
require(amount.add((userWithdraw[reinvestAddress].withdrawStraight).mul(100).div(80)) <= userAmount.add(amount));
} else if (requireType == 3) {
require(amount.add((userWithdraw[reinvestAddress].withdrawTeam).mul(100).div(80)) <= userAmount.add(amount));
} else if (requireType == 5) {
require(amount.add((userWithdraw[reinvestAddress].withdrawNode).mul(100).div(80)) <= userAmount);
}
// userWithdraw[reinvestAddress].lockEth = userWithdraw[reinvestAddress].lockEth.add(amount.mul(remain).div(100));\
uint256 _active = userWithdraw[reinvestAddress].lockEth - userWithdraw[reinvestAddress].activateEth;
if (amount > _active) {
userWithdraw[reinvestAddress].activateEth += _active;
amount = amount.add(_active);
} else {
userWithdraw[reinvestAddress].activateEth = userWithdraw[reinvestAddress].activateEth.add(amount);
amount = amount.mul(2);
}
return amount;
}
function routeAddLockEth(
address withdrawAddress,
uint256 amount,
uint256 lockProfits,
uint256 userRouteEth,
uint256 routeType)
public
onlyResonance()
{
if (routeType == 1) {
addLockEthStatic(withdrawAddress, amount, lockProfits, userRouteEth);
} else if (routeType == 2) {
addLockEthStraight(withdrawAddress, amount, userRouteEth);
} else if (routeType == 3) {
addLockEthTeam(withdrawAddress, amount, userRouteEth);
} else if (routeType == 4) {
addLockEthTerminator(withdrawAddress, amount, userRouteEth);
} else if (routeType == 5) {
addLockEthNode(withdrawAddress, amount, userRouteEth);
}
}
function addLockEthStatic(address withdrawAddress, uint256 amount, uint256 lockProfits, uint256 userStatic)
internal
{
require(amount.add(userWithdraw[withdrawAddress].withdrawStatic.mul(100).div(percent - remain)) <= userStatic);
userWithdraw[withdrawAddress].lockEth += lockProfits;
userWithdraw[withdrawAddress].withdrawStatic += amount.sub(lockProfits);
}
function addLockEthStraight(address withdrawAddress, uint256 amount, uint256 userStraightEth)
internal
{
require(amount.add(userWithdraw[withdrawAddress].withdrawStraight.mul(100).div(percent - remain)) <= userStraightEth);
userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100);
userWithdraw[withdrawAddress].withdrawStraight += amount.mul(percent - remain).div(100);
}
function addLockEthTeam(address withdrawAddress, uint256 amount, uint256 userTeamEth)
internal
{
require(amount.add(userWithdraw[withdrawAddress].withdrawTeam.mul(100).div(percent - remain)) <= userTeamEth);
userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100);
userWithdraw[withdrawAddress].withdrawTeam += amount.mul(percent - remain).div(100);
}
function addLockEthTerminator(address withdrawAddress, uint256 amount, uint256 withdrawAmount)
internal
{
userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100);
userWithdraw[withdrawAddress].withdrawTerminator += withdrawAmount;
}
function addLockEthNode(address withdrawAddress, uint256 amount, uint256 userNodeEth)
internal
{
require(amount.add(userWithdraw[withdrawAddress].withdrawNode.mul(100).div(percent - remain)) <= userNodeEth);
userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100);
userWithdraw[withdrawAddress].withdrawNode += amount.mul(percent - remain).div(100);
}
function addActivateEth(address userAddress, uint256 amount)
public
onlyResonance()
{
uint256 _afterFounds = getAfterFounds(userAddress);
if (amount > _afterFounds) {
userWithdraw[userAddress].activateEth = userWithdraw[userAddress].lockEth;
}
else {
userWithdraw[userAddress].activateEth += amount;
}
}
function changeWithdrawTeamZero(address userAddress)
public
onlyResonance()
{
userWithdraw[userAddress].withdrawTeam = 0;
}
function getWithdrawStraight(address reinvestAddress)
public
view
onlyResonance()
returns (uint256)
{
return userWithdraw[reinvestAddress].withdrawStraight;
}
function getWithdrawStatic(address reinvestAddress)
public
view
onlyResonance()
returns (uint256)
{
return userWithdraw[reinvestAddress].withdrawStatic;
}
function getWithdrawTeam(address reinvestAddress)
public
view
onlyResonance()
returns (uint256)
{
return userWithdraw[reinvestAddress].withdrawTeam;
}
function getWithdrawNode(address reinvestAddress)
public
view
onlyResonance()
returns (uint256)
{
return userWithdraw[reinvestAddress].withdrawNode;
}
function getAfterFounds(address userAddress)
public
view
onlyResonance()
returns (uint256)
{
return userWithdraw[userAddress].lockEth - userWithdraw[userAddress].activateEth;
}
function getStaticAfterFounds(address reinvestAddress) public
view
onlyResonance()
returns (uint256, uint256)
{
return (userWithdraw[reinvestAddress].withdrawStatic, userWithdraw[reinvestAddress].lockEth - userWithdraw[reinvestAddress].activateEth);
}
function getStaticAfterFoundsTeam(address userAddress) public
view
onlyResonance()
returns (uint256, uint256, uint256)
{
return (userWithdraw[userAddress].withdrawStatic, userWithdraw[userAddress].lockEth - userWithdraw[userAddress].activateEth, userWithdraw[userAddress].withdrawTeam);
}
function getUserWithdrawInfo(address reinvestAddress) public
view
onlyResonance()
returns (
uint256 withdrawStraight,
uint256 withdrawTeam,
uint256 withdrawStatic,
uint256 withdrawNode
)
{
withdrawStraight = userWithdraw[reinvestAddress].withdrawStraight;
withdrawTeam = userWithdraw[reinvestAddress].withdrawTeam;
withdrawStatic = userWithdraw[reinvestAddress].withdrawStatic;
withdrawNode = userWithdraw[reinvestAddress].withdrawNode;
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "./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 `ERC20Mintable`.
*
* *For a detailed writeup see our guide [How to implement supply
* mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).*
*
* 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 IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See `IERC20.totalSupply`.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See `IERC20.balanceOf`.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See `IERC20.transfer`.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See `IERC20.allowance`.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See `IERC20.approve`.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
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 `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(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 returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to `transfer`, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a `Transfer` event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
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);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a `Transfer` event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destoys `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 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @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 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Destoys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See `_burn` and `_approve`.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount));
}
}
pragma solidity ^0.5.0;
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).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Destoys `amount` tokens from the caller.
*
* See `ERC20._burn`.
*/
function burn(uint256 amount) public {
_burn(msg.sender, amount);
}
/**
* @dev See `ERC20._burnFrom`.
*/
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
}
pragma solidity ^0.5.0;
import "./ERC20Mintable.sol";
/**
* @dev Extension of `ERC20Mintable` that adds a cap to the supply of tokens.
*/
contract ERC20Capped is ERC20Mintable {
uint256 private _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
constructor (uint256 cap) public {
require(cap > 0, "ERC20Capped: cap is 0");
_cap = cap;
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view returns (uint256) {
return _cap;
}
/**
* @dev See `ERC20Mintable.mint`.
*
* Requirements:
*
* - `value` must not cause the total supply to go over the cap.
*/
function _mint(address account, uint256 value) internal {
require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded");
super._mint(account, value);
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* > Note that 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;
}
}
pragma solidity ^0.5.0;
import "./ERC20.sol";
import "./MinterRole.sol";
/**
* @dev Extension of `ERC20` that adds a set of accounts with the `MinterRole`,
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev See `ERC20._mint`.
*
* Requirements:
*
* - the caller must have the `MinterRole`.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
}
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through `transferFrom`. This is
* zero by default.
*
* This value changes when `approve` or `transferFrom` are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* > Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to `approve`. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity >=0.4.21 <0.6.0;
import "./ERC20.sol";
import "./ERC20Detailed.sol";
import "./ERC20Capped.sol";
import "./ERC20Burnable.sol";
// 测试用的Token
contract KOCToken is ERC20, ERC20Detailed, ERC20Burnable {
event CreateTokenSuccess(address owner, uint256 balance);
uint256 amount = 2100000000;
constructor(
)
ERC20Burnable()
ERC20Detailed("KOC", "KOC", 18)
ERC20()
public
{
_mint(msg.sender, amount * (10 ** 18));
emit CreateTokenSuccess(msg.sender, balanceOf(msg.sender));
}
}
pragma solidity ^0.5.0;
import "./Roles.sol";
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), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
pragma solidity >=0.4.21 <0.6.0;
contract Recommend {
// -------------------- mapping ------------------------ //
mapping(address => RecommendRecord) internal recommendRecord; // record straight reward information
// -------------------- struct ------------------------ //
struct RecommendRecord {
uint256[] straightTime; // this record start time, 3 days timeout
address[] refeAddress; // referral address
uint256[] ethAmount; // this record buy eth amount
bool[] supported; // false means unsupported
}
// -------------------- variate ------------------------ //
address public resonanceAddress;
address public owner;
constructor()
public{
owner = msg.sender;
}
// -------------------- modifier ------------------------ //
modifier onlyOwner(){
require(msg.sender == owner);
_;
}
modifier onlyResonance (){
require(msg.sender == resonanceAddress);
_;
}
// -------------------- owner api ------------------------ //
function allowResonance(address _addr) public onlyOwner() {
resonanceAddress = _addr;
}
// -------------------- Resonance api ----------------//
function getRecommendByIndex(uint256 index, address userAddress)
public
view
// onlyResonance() TODO
returns (
uint256 straightTime,
address refeAddress,
uint256 ethAmount,
bool supported
)
{
straightTime = recommendRecord[userAddress].straightTime[index];
refeAddress = recommendRecord[userAddress].refeAddress[index];
ethAmount = recommendRecord[userAddress].ethAmount[index];
supported = recommendRecord[userAddress].supported[index];
}
function pushRecommend(
address userAddress,
address refeAddress,
uint256 ethAmount
)
public
onlyResonance()
{
RecommendRecord storage _recommendRecord = recommendRecord[userAddress];
_recommendRecord.straightTime.push(block.timestamp);
_recommendRecord.refeAddress.push(refeAddress);
_recommendRecord.ethAmount.push(ethAmount);
_recommendRecord.supported.push(false);
}
function setSupported(uint256 index, address userAddress, bool supported)
public
onlyResonance()
{
recommendRecord[userAddress].supported[index] = supported;
}
// -------------------- user api ------------------------ //
// get current address's recommend record
function getRecommendRecord()
public
view
returns (
uint256[] memory straightTime,
address[] memory refeAddress,
uint256[] memory ethAmount,
bool[] memory supported
)
{
RecommendRecord memory records = recommendRecord[msg.sender];
straightTime = records.straightTime;
refeAddress = records.refeAddress;
ethAmount = records.ethAmount;
supported = records.supported;
}
}
pragma solidity >=0.4.21 <0.6.0;
import "./SafeMath.sol";
import "./Earnings.sol";
import "./TeamRewards.sol";
import "./Terminator.sol";
import "./Recommend.sol";
import "./ResonanceF.sol";
contract Resonance is ResonanceF {
using SafeMath for uint256;
uint256 public totalSupply = 0;
uint256 constant internal bonusPrice = 0.0000001 ether; // init price
uint256 constant internal priceIncremental = 0.00000001 ether; // increase price
uint256 constant internal magnitude = 2 ** 64;
uint256 public perBonusDivide = 0; //per Profit divide
uint256 public systemRetain = 0;
uint256 public terminatorPoolAmount; //terminator award Pool Amount
uint256 public activateSystem = 20;
uint256 public activateGlobal = 20;
mapping(address => User) public userInfo; // user define all user's information
mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward
mapping(address => int256) internal payoutsTo; // record
mapping(address => uint256[11]) public userSubordinateCount;
mapping(address => uint256) public whitelistPerformance;
mapping(address => UserReinvest) public userReinvest;
mapping(address => uint256) public lastStraightLength;
uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent
uint32 constant internal ratio = 1000; // eth to erc20 token ratio
uint32 constant internal blockNumber = 40000; // straight sort reward block number
uint256 public currentBlockNumber;
uint256 public straightSortRewards = 0;
uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit
uint256 public totalEthAmount = 0; // all user total buy eth amount
uint8 constant public percent = 100;
address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address
address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD);
address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6);
address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f);
address [10] public straightSort; // straight reward
Earnings internal earningsInstance;
TeamRewards internal teamRewardInstance;
Terminator internal terminatorInstance;
Recommend internal recommendInstance;
struct User {
address userAddress; // user address
uint256 ethAmount; // user buy eth amount
uint256 profitAmount; // user profit amount
uint256 tokenAmount; // user get token amount
uint256 tokenProfit; // profit by profitAmount
uint256 straightEth; // user straight eth
uint256 lockStraight;
uint256 teamEth; // team eth reward
bool staticTimeout; // static timeout, 3 days
uint256 staticTime; // record static out time
uint8 level; // user team level
address straightAddress;
uint256 refeTopAmount; // subordinate address topmost eth amount
address refeTopAddress; // subordinate address topmost eth address
}
struct UserReinvest {
// uint256 nodeReinvest;
uint256 staticReinvest;
bool isPush;
}
uint8[7] internal rewardRatio; // [0] means market support rewards 10%
// [1] means static rewards 30%
// [2] means straight rewards 30%
// [3] means team rewards 29%
// [4] means terminator rewards 5%
// [5] means straight sort rewards 5%
// [6] means egg rewards 1%
uint8[11] internal teamRatio; // team reward ratio
modifier mustAdmin (address adminAddress){
require(adminAddress != address(0));
require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]);
_;
}
modifier mustReferralAddress (address referralAddress) {
require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]);
if (teamRewardInstance.isWhitelistAddress(msg.sender)) {
require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]);
}
_;
}
modifier limitInvestmentCondition(uint256 ethAmount){
if (initAddressAmount <= 50) {
require(ethAmount <= 5 ether);
_;
} else {
_;
}
}
modifier limitAddressReinvest() {
if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) {
require(msg.value <= userInfo[msg.sender].ethAmount.mul(3));
}
_;
}
// -------------------- modifier ------------------------ //
// --------------------- event -------------------------- //
event WithdrawStaticProfits(address indexed user, uint256 ethAmount);
event Buy(address indexed user, uint256 ethAmount, uint256 buyTime);
event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime);
event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime);
event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported);
// --------------------- event -------------------------- //
constructor(
address _erc20Address,
address _earningsAddress,
address _teamRewardsAddress,
address _terminatorAddress,
address _recommendAddress
)
public
{
earningsInstance = Earnings(_earningsAddress);
teamRewardInstance = TeamRewards(_teamRewardsAddress);
terminatorInstance = Terminator(_terminatorAddress);
kocInstance = KOCToken(_erc20Address);
recommendInstance = Recommend(_recommendAddress);
rewardRatio = [10, 30, 30, 29, 5, 5, 1];
teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1];
currentBlockNumber = block.number;
}
// -------------------- user api ----------------//
function buy(address referralAddress)
public
mustReferralAddress(referralAddress)
limitInvestmentCondition(msg.value)
payable
{
require(!teamRewardInstance.getWhitelistTime());
uint256 ethAmount = msg.value;
address userAddress = msg.sender;
User storage _user = userInfo[userAddress];
_user.userAddress = userAddress;
if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) {
teamRewardInstance.referralPeople(userAddress, referralAddress);
_user.straightAddress = referralAddress;
} else {
referralAddress == teamRewardInstance.getUserreferralAddress(userAddress);
}
address straightAddress;
address whiteAddress;
address adminAddress;
bool whitelist;
(straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress);
require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]);
if (userInfo[referralAddress].userAddress == address(0)) {
userInfo[referralAddress].userAddress = referralAddress;
}
if (userInfo[userAddress].straightAddress == address(0)) {
userInfo[userAddress].straightAddress = straightAddress;
}
// uint256 _withdrawStatic;
uint256 _lockEth;
uint256 _withdrawTeam;
(, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress);
if (ethAmount >= _lockEth) {
ethAmount = ethAmount.add(_lockEth);
if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) {
address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80)));
userInfo[userAddress].teamEth = 0;
earningsInstance.changeWithdrawTeamZero(userAddress);
}
userInfo[userAddress].staticTimeout = false;
userInfo[userAddress].staticTime = block.timestamp;
} else {
_lockEth = ethAmount;
ethAmount = ethAmount.mul(2);
}
earningsInstance.addActivateEth(userAddress, _lockEth);
if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) {
require(userInfo[userAddress].profitAmount == 0);
}
if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static
initAddressAmount++;
}
calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress);
straightReferralReward(_user, ethAmount);
// calculate straight referral reward
uint256 topProfits = whetherTheCap();
require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits);
emit Buy(userAddress, ethAmount, block.timestamp);
}
// contains some methods for buy or reinvest
function calculateBuy(
User storage user,
uint256 ethAmount,
address straightAddress,
address whiteAddress,
address adminAddress,
address users
)
internal
{
require(ethAmount > 0);
user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount);
if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) {
user.straightEth += user.lockStraight;
user.lockStraight = 0;
}
if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) {
straightInviteAddress[straightAddress].push(user.userAddress);
userReinvest[user.userAddress].isPush = true;
// record straight address
if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) {
bool has = false;
//search this address
for (uint i = 0; i < 10; i++) {
if (straightSort[i] == straightAddress) {
has = true;
}
}
if (!has) {
//search this address if not in this array,go sort after cover last
straightSort[9] = straightAddress;
}
// sort referral address
quickSort(straightSort, int(0), int(9));
// straightSortAddress(straightAddress);
}
// }
}
address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100));
// transfer to eggAddress 1% eth
straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100);
// straight sort rewards, 5% eth
teamReferralReward(ethAmount, straightAddress);
// issue team reward
terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100);
// issue terminator reward
calculateToken(user, ethAmount);
// calculate and transfer KOC token
calculateProfit(user, ethAmount, users);
// calculate user earn profit
updateTeamLevel(straightAddress);
// update team level
totalEthAmount += ethAmount;
whitelistPerformance[whiteAddress] += ethAmount;
whitelistPerformance[adminAddress] += ethAmount;
addTerminator(user.userAddress);
}
// contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards
// 3 means team rewards, 4 means terminators rewards, 5 means node rewards
function reinvest(uint256 amount, uint8 value)
public
payable
{
address reinvestAddress = msg.sender;
address straightAddress;
address whiteAddress;
address adminAddress;
(straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender);
require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303");
uint256 earningsProfits = 0;
if (value == 1) {
earningsProfits = whetherTheCap();
uint256 _withdrawStatic;
uint256 _afterFounds;
uint256 _withdrawTeam;
(_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress);
_withdrawStatic = _withdrawStatic.mul(100).div(80);
require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits);
if (amount >= _afterFounds) {
if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) {
address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80)));
userInfo[reinvestAddress].teamEth = 0;
earningsInstance.changeWithdrawTeamZero(reinvestAddress);
}
userInfo[reinvestAddress].staticTimeout = false;
userInfo[reinvestAddress].staticTime = block.timestamp;
}
userReinvest[reinvestAddress].staticReinvest += amount;
} else if (value == 2) {
//复投直推
require(userInfo[reinvestAddress].straightEth >= amount);
userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount);
earningsProfits = userInfo[reinvestAddress].straightEth;
} else if (value == 3) {
require(userInfo[reinvestAddress].teamEth >= amount);
userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount);
earningsProfits = userInfo[reinvestAddress].teamEth;
} else if (value == 4) {
terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount);
}
amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value);
calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress);
straightReferralReward(userInfo[reinvestAddress], amount);
emit Reinvest(reinvestAddress, amount, value, block.timestamp);
}
// contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards
// 3 means team rewards, 4 means terminators rewards, 5 means node rewards
function withdraw(uint256 amount, uint8 value)
public
{
address withdrawAddress = msg.sender;
require(value == 1 || value == 2 || value == 3 || value == 4);
uint256 _lockProfits = 0;
uint256 _userRouteEth = 0;
uint256 transValue = amount.mul(80).div(100);
if (value == 1) {
_userRouteEth = whetherTheCap();
_lockProfits = SafeMath.mul(amount, remain).div(100);
} else if (value == 2) {
_userRouteEth = userInfo[withdrawAddress].straightEth;
} else if (value == 3) {
if (userInfo[withdrawAddress].staticTimeout) {
require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp);
}
_userRouteEth = userInfo[withdrawAddress].teamEth;
} else if (value == 4) {
_userRouteEth = amount.mul(80).div(100);
terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth);
}
earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value);
address(uint160(withdrawAddress)).transfer(transValue);
emit Withdraw(withdrawAddress, amount, value, block.timestamp);
}
// referral address support subordinate, 10%
function supportSubordinateAddress(uint256 index, address subordinate)
public
payable
{
User storage _user = userInfo[msg.sender];
require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100));
uint256 straightTime;
address refeAddress;
uint256 ethAmount;
bool supported;
(straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress);
require(!supported);
require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10));
if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) {
_user.straightEth += ethAmount.mul(rewardRatio[2]).div(100);
} else {
_user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100);
}
address straightAddress;
address whiteAddress;
address adminAddress;
(straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate);
calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate);
recommendInstance.setSupported(index, _user.userAddress, true);
emit SupportSubordinateAddress(index, subordinate, refeAddress, supported);
}
// -------------------- internal function ----------------//
// calculate team reward and issue reward
//teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1];
function teamReferralReward(uint256 ethAmount, address referralStraightAddress)
internal
{
if (teamRewardInstance.isWhitelistAddress(msg.sender)) {
uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100);
uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100);
systemRetain += _nodeReward;
address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100));
address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100));
address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100));
} else {
uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100);
//system residue eth
uint256 residueAmount = _refeReward;
//user straight address
User memory currentUser = userInfo[referralStraightAddress];
//issue team reward
for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12
//get straight user
address straightAddress = currentUser.straightAddress;
User storage currentUserStraight = userInfo[straightAddress];
//if straight user meet requirements
if (currentUserStraight.level >= i) {
uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29);
currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward);
//sub reward amount
residueAmount = residueAmount.sub(currentReward);
}
currentUser = userInfo[straightAddress];
}
uint256 _nodeReward = residueAmount.mul(activateSystem).div(100);
systemRetain = systemRetain.add(_nodeReward);
address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100));
address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100));
address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100));
}
}
function updateTeamLevel(address refferAddress)
internal
{
User memory currentUserStraight = userInfo[refferAddress];
uint8 levelUpCount = 0;
uint256 currentInviteCount = straightInviteAddress[refferAddress].length;
if (currentInviteCount >= 2) {
levelUpCount = 2;
}
if (currentInviteCount > 12) {
currentInviteCount = 12;
}
uint256 lackCount = 0;
for (uint8 j = 2; j < currentInviteCount; j++) {
if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) {
levelUpCount = j + 1;
lackCount = 0;
} else {
lackCount++;
}
}
if (levelUpCount > currentUserStraight.level) {
uint8 oldLevel = userInfo[refferAddress].level;
userInfo[refferAddress].level = levelUpCount;
if (currentUserStraight.straightAddress != address(0)) {
if (oldLevel > 0) {
if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) {
userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1;
}
}
userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1;
updateTeamLevel(currentUserStraight.straightAddress);
}
}
}
// calculate bonus profit
function calculateProfit(User storage user, uint256 ethAmount, address users)
internal
{
if (teamRewardInstance.isWhitelistAddress(user.userAddress)) {
ethAmount = ethAmount.mul(110).div(100);
}
uint256 userBonus = ethToBonus(ethAmount);
require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply);
totalSupply += userBonus;
uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100);
getPerBonusDivide(tokenDivided, userBonus, users);
user.profitAmount += userBonus;
}
// get user bonus information for calculate static rewards
function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users)
public
{
uint256 fee = tokenDivided * magnitude;
perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply);
//calculate every bonus earnings eth
fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply))));
int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee);
payoutsTo[users] += updatedPayouts;
}
// calculate and transfer KOC token
function calculateToken(User storage user, uint256 ethAmount)
internal
{
kocInstance.transfer(user.userAddress, ethAmount.mul(ratio));
user.tokenAmount += ethAmount.mul(ratio);
}
// calculate straight reward and record referral address recommendRecord
function straightReferralReward(User memory user, uint256 ethAmount)
internal
{
address _referralAddresses = user.straightAddress;
userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount;
userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress;
recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount);
if (teamRewardInstance.isWhitelistAddress(user.userAddress)) {
uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100);
uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100);
systemRetain += _nodeReward;
address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100));
address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100));
address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100));
}
}
// sort straight address, 10
function straightSortAddress(address referralAddress)
internal
{
for (uint8 i = 0; i < 10; i++) {
if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) {
address [] memory temp;
for (uint j = i; j < 10; j++) {
temp[j] = straightSort[j];
}
straightSort[i] = referralAddress;
for (uint k = i; k < 9; k++) {
straightSort[k + 1] = temp[k];
}
}
}
}
//sort straight address, 10
function quickSort(address [10] storage arr, int left, int right) internal {
int i = left;
int j = right;
if (i == j) return;
uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]);
while (i <= j) {
while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++;
while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[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);
}
// settle straight rewards
function settleStraightRewards()
internal
{
uint256 addressAmount;
for (uint8 i = 0; i < 10; i++) {
addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]];
}
uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2);
uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount);
for (uint8 j = 0; j < 10; j++) {
address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward));
straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward));
lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length;
}
delete (straightSort);
currentBlockNumber = block.number;
}
// calculate bonus
function ethToBonus(uint256 ethereum)
internal
view
returns (uint256)
{
uint256 _price = bonusPrice * 1e18;
// calculate by wei
uint256 _tokensReceived =
(
(
SafeMath.sub(
(sqrt
(
(_price ** 2)
+
(2 * (priceIncremental * 1e18) * (ethereum * 1e18))
+
(((priceIncremental) ** 2) * (totalSupply ** 2))
+
(2 * (priceIncremental) * _price * totalSupply)
)
), _price
)
) / (priceIncremental)
) - (totalSupply);
return _tokensReceived;
}
// utils for calculate bonus
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
// get user bonus profits
function myBonusProfits(address user)
view
public
returns (uint256)
{
return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude);
}
function whetherTheCap()
internal
returns (uint256)
{
require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit);
uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120));
uint256 topProfits = _currentAmount.mul(remain + 100).div(100);
uint256 userProfits = myBonusProfits(msg.sender);
if (userProfits > topProfits) {
userInfo[msg.sender].profitAmount = 0;
payoutsTo[msg.sender] = 0;
userInfo[msg.sender].tokenProfit += topProfits;
userInfo[msg.sender].staticTime = block.timestamp;
userInfo[msg.sender].staticTimeout = true;
}
if (topProfits == 0) {
topProfits = userInfo[msg.sender].tokenProfit;
} else {
topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again
}
return topProfits;
}
// -------------------- set api ---------------- //
function setStraightSortRewards()
public
onlyAdmin()
returns (bool)
{
require(currentBlockNumber + blockNumber < block.number);
settleStraightRewards();
return true;
}
// -------------------- get api ---------------- //
// get straight sort list, 10 addresses
function getStraightSortList()
public
view
returns (address[10] memory)
{
return straightSort;
}
// get effective straight addresses current step
function getStraightInviteAddress()
public
view
returns (address[] memory)
{
return straightInviteAddress[msg.sender];
}
// get currentBlockNumber
function getcurrentBlockNumber()
public
view
returns (uint256){
return currentBlockNumber;
}
function getPurchaseTasksInfo()
public
view
returns (
uint256 ethAmount,
uint256 refeTopAmount,
address refeTopAddress,
uint256 lockStraight
)
{
User memory getUser = userInfo[msg.sender];
ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120));
refeTopAmount = getUser.refeTopAmount;
refeTopAddress = getUser.refeTopAddress;
lockStraight = getUser.lockStraight;
}
function getPersonalStatistics()
public
view
returns (
uint256 holdings,
uint256 dividends,
uint256 invites,
uint8 level,
uint256 afterFounds,
uint256 referralRewards,
uint256 teamRewards,
uint256 nodeRewards
)
{
User memory getUser = userInfo[msg.sender];
uint256 _withdrawStatic;
(_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress);
holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120));
dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender);
invites = straightInviteAddress[msg.sender].length;
level = getUser.level;
referralRewards = getUser.straightEth;
teamRewards = getUser.teamEth;
uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount);
nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards;
}
function getUserBalance()
public
view
returns (
uint256 staticBalance,
uint256 recommendBalance,
uint256 teamBalance,
uint256 terminatorBalance,
uint256 nodeBalance,
uint256 totalInvest,
uint256 totalDivided,
uint256 withdrawDivided
)
{
User memory getUser = userInfo[msg.sender];
uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120));
uint256 withdrawStraight;
uint256 withdrawTeam;
uint256 withdrawStatic;
uint256 withdrawNode;
(withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress);
// uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80));
uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0;
uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0;
staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest);
recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80));
teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80));
terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress);
nodeBalance = 0;
totalInvest = getUser.ethAmount;
totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress));
withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80);
}
// returns contract statistics
function contractStatistics()
public
view
returns (
uint256 recommendRankPool,
uint256 terminatorPool
)
{
recommendRankPool = straightSortRewards;
terminatorPool = getCurrentTerminatorAmountPool();
}
function listNodeBonus(address node)
public
view
returns (
address nodeAddress,
uint256 performance
)
{
nodeAddress = node;
performance = whitelistPerformance[node];
}
function listRankOfRecommend()
public
view
returns (
address[10] memory _straightSort,
uint256[10] memory _inviteNumber
)
{
for (uint8 i = 0; i < 10; i++) {
if (straightSort[i] == address(0)){
break;
}
_inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]);
}
_straightSort = straightSort;
}
// return current effective user for initAddressAmount
function getCurrentEffectiveUser()
public
view
returns (uint256)
{
return initAddressAmount;
}
function addTerminator(address addr)
internal
{
uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120));
uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number);
terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2));
}
function isLockWithdraw()
public
view
returns (
bool isLock,
uint256 lockTime
)
{
isLock = userInfo[msg.sender].staticTimeout;
lockTime = userInfo[msg.sender].staticTime;
}
function modifyActivateSystem(uint256 value)
mustAdmin(msg.sender)
public
{
activateSystem = value;
}
function modifyActivateGlobal(uint256 value)
mustAdmin(msg.sender)
public
{
activateGlobal = value;
}
//return Current Terminator reward pool amount
function getCurrentTerminatorAmountPool()
view public
returns(uint256 amount)
{
return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number);
}
}
pragma solidity >=0.4.21 <0.6.0;
import "./KOCToken.sol";
contract ResonanceF {
address[5] internal admin = [address(0x8434750c01D702c9cfabb3b7C5AA2774Ee67C90D), address(0xD8e79f0D2592311E740Ff097FFb0a7eaa8cb506a), address(0x740beb9fa9CCC6e971f90c25C5D5CC77063a722D), address(0x1b5bbac599f1313dB3E8061A0A65608f62897B0C), address(0x6Fd6dF175B97d2E6D651b536761e0d36b33A9495)];
address internal boosAddress = address(0x541f5417187981b28Ef9e7Df814b160Ae2Bcb72C);
KOCToken internal kocInstance;
modifier onlyAdmin () {
address adminAddress = msg.sender;
require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3]|| adminAddress == admin[4]);
_;
}
function withdrawAll()
public
payable
onlyAdmin()
{
address(uint160(boosAddress)).transfer(address(this).balance);
kocInstance.transfer(address(uint160(boosAddress)), kocInstance.balanceOf(address(this)));
}
}
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
pragma solidity >=0.4.21 <0.6.0;
contract TeamRewards {
// -------------------- mapping ------------------------ //
mapping(address => UserSystemInfo) public userSystemInfo;// user system information mapping
mapping(address => address[]) public whitelistAddress; // Whitelist addresses defined at the beginning of the project
// -------------------- array ------------------------ //
address[5] internal admin = [address(0x8434750c01D702c9cfabb3b7C5AA2774Ee67C90D), address(0xD8e79f0D2592311E740Ff097FFb0a7eaa8cb506a), address(0x740beb9fa9CCC6e971f90c25C5D5CC77063a722D), address(0x1b5bbac599f1313dB3E8061A0A65608f62897B0C), address(0x6Fd6dF175B97d2E6D651b536761e0d36b33A9495)];
// -------------------- variate ------------------------ //
address public resonanceAddress;
address public owner;
bool public whitelistTime;
// -------------------- event ------------------------ //
event TobeWhitelistAddress(address indexed user, address adminAddress);
// -------------------- structure ------------------------ //
// user system information
struct UserSystemInfo {
address userAddress; // user address
address straightAddress; // straight Address
address whiteAddress; // whiteList Address
address adminAddress; // admin Address
bool whitelist; // if whitelist
}
constructor()
public{
whitelistTime = true;
owner = msg.sender;
}
// -------------------- modifier ------------------------ //
modifier onlyOwner(){
require(msg.sender == owner);
_;
}
modifier onlyAdmin () {
address adminAddress = msg.sender;
require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]);
_;
}
modifier mustAdmin (address adminAddress){
require(adminAddress != address(0));
require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]);
_;
}
modifier onlyResonance (){
require(msg.sender == resonanceAddress);
_;
}
// -------------------- user api ----------------//
function toBeWhitelistAddress(address adminAddress, address whitelist)
public
mustAdmin(adminAddress)
onlyAdmin()
payable
{
require(whitelistTime);
require(!userSystemInfo[whitelist].whitelist);
whitelistAddress[adminAddress].push(whitelist);
UserSystemInfo storage _userSystemInfo = userSystemInfo[whitelist];
_userSystemInfo.straightAddress = adminAddress;
_userSystemInfo.whiteAddress = whitelist;
_userSystemInfo.adminAddress = adminAddress;
_userSystemInfo.whitelist = true;
emit TobeWhitelistAddress(whitelist, adminAddress);
}
// -------------------- Resonance api ----------------//
function referralPeople(address userAddress,address referralAddress)
public
onlyResonance()
{
UserSystemInfo storage _userSystemInfo = userSystemInfo[userAddress];
_userSystemInfo.straightAddress = referralAddress;
_userSystemInfo.whiteAddress = userSystemInfo[referralAddress].whiteAddress;
_userSystemInfo.adminAddress = userSystemInfo[referralAddress].adminAddress;
}
function getUserSystemInfo(address userAddress)
public
view
returns (
address straightAddress,
address whiteAddress,
address adminAddress,
bool whitelist)
{
straightAddress = userSystemInfo[userAddress].straightAddress;
whiteAddress = userSystemInfo[userAddress].whiteAddress;
adminAddress = userSystemInfo[userAddress].adminAddress;
whitelist = userSystemInfo[userAddress].whitelist;
}
function getUserreferralAddress(address userAddress)
public
view
onlyResonance()
returns (address )
{
return userSystemInfo[userAddress].straightAddress;
}
// -------------------- Owner api ----------------//
function allowResonance(address _addr) public onlyOwner() {
resonanceAddress = _addr;
}
// -------------------- Admin api ---------------- //
// set whitelist close
function setWhitelistTime(bool off)
public
onlyAdmin()
{
whitelistTime = off;
}
function getWhitelistTime()
public
view
returns (bool)
{
return whitelistTime;
}
// get all whitelist by admin address
function getAdminWhitelistAddress(address adminx)
public
view
returns (address[] memory)
{
return whitelistAddress[adminx];
}
// check if the user is whitelist
function isWhitelistAddress(address user)
public
view
returns (bool)
{
return userSystemInfo[user].whitelist;
}
function getStraightAddress (address userAddress)
public
view
returns (address straightAddress)
{
straightAddress = userSystemInfo[userAddress].straightAddress;
}
}
pragma solidity >=0.4.21 <0.6.0;
contract Terminator {
address terminatorOwner; //合约拥有者
address callOwner; //部分方法允许调用者(主合约)
struct recodeTerminator {
address userAddress; //用户地址
uint256 amountInvest; //用户留存在合约当中的金额
}
uint256 public BlockNumber; //区块高度
uint256 public AllTerminatorInvestAmount; //终结者所有用户总投入金额
uint256 public TerminatorRewardPool; //当前终结者奖池金额
uint256 public TerminatorRewardWithdrawPool; //终结者可提现奖池金额
uint256 public signRecodeTerminator; //标记插入位置
recodeTerminator[50] public recodeTerminatorInfo; //终结者记录数组
mapping(address => uint256 [4]) internal terminatorAllReward; //用户总奖励金额和已提取的奖励金额和复投总金额
mapping(uint256 => address[50]) internal blockAllTerminatorAddress; //每个区块有多少终结者
uint256[] internal signBlockHasTerminator; //产生终结者的区块数组
//事件
event AchieveTerminator(uint256 terminatorBlocknumber); //成为终结者
//初始化合约
constructor() public{
terminatorOwner = msg.sender;
}
//添加终结者(主合约调用)
function addTerminator(address addr, uint256 amount, uint256 blockNumber, uint256 amountPool)
public
checkCallOwner(msg.sender)
{
require(amount > 0);
require(amountPool > 0);
if (blockNumber >= BlockNumber + 240 && BlockNumber != 0) {
addRecodeToTerminatorArray(BlockNumber);
signBlockHasTerminator.push(BlockNumber);
}
addRecodeTerminator(addr, amount, blockNumber, amountPool);
BlockNumber = blockNumber;
}
//用户提取奖励(主合约调用)
function modifyTerminatorReward(address addr, uint256 amount)
public
checkCallOwner(msg.sender)
{
require(amount <= terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3]);
terminatorAllReward[addr][1] += amount;
}
//用户复投(主合约调用)
function reInvestTerminatorReward(address addr, uint256 amount)
public
checkCallOwner(msg.sender)
{
require(amount <= terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3]);
terminatorAllReward[addr][3] += amount;
}
//添加用户信息记录,等待触发终结者(内部调用)
function addRecodeTerminator(address addr, uint256 amount, uint256 blockNumber, uint256 amountPool)
internal
{
recodeTerminator memory t = recodeTerminator(addr, amount);
if (blockNumber == BlockNumber) {
if (signRecodeTerminator >= 50) {
AllTerminatorInvestAmount -= recodeTerminatorInfo[signRecodeTerminator % 50].amountInvest;
}
recodeTerminatorInfo[signRecodeTerminator % 50] = t;
signRecodeTerminator++;
AllTerminatorInvestAmount += amount;
} else {
recodeTerminatorInfo[0] = t;
signRecodeTerminator = 1;
AllTerminatorInvestAmount = amount;
}
TerminatorRewardPool = amountPool;
}
//产生终结者,将终结者信息写入并计算奖励(内部调用)
function addRecodeToTerminatorArray(uint256 blockNumber)
internal
{
for (uint256 i = 0; i < 50; i++) {
if (i >= signRecodeTerminator) {
break;
}
address userAddress = recodeTerminatorInfo[i].userAddress;
uint256 reward = (recodeTerminatorInfo[i].amountInvest) * (TerminatorRewardPool) / (AllTerminatorInvestAmount);
blockAllTerminatorAddress[blockNumber][i] = userAddress;
terminatorAllReward[userAddress][0] += reward;
terminatorAllReward[userAddress][2] = reward;
}
TerminatorRewardWithdrawPool += TerminatorRewardPool;
emit AchieveTerminator(blockNumber);
}
//添加主合约调用权限(合约拥有者调用)
function addCallOwner(address addr)
public
checkTerminatorOwner(msg.sender)
{
callOwner = addr;
}
//根据区块高度获取获取所有获得终结者奖励地址
function getAllTerminatorAddress(uint256 blockNumber)
view public
returns (address[50] memory)
{
return blockAllTerminatorAddress[blockNumber];
}
//获取最近一次获得终结者区块高度和奖励的所有用户地址和上一次获奖数量
function getLatestTerminatorInfo()
view public
returns (uint256 blockNumber, address[50] memory addressArray, uint256[50] memory amountArray)
{
uint256 index = signBlockHasTerminator.length;
address[50] memory rewardAddress;
uint256[50] memory rewardAmount;
if (index <= 0) {
return (0, rewardAddress, rewardAmount);
} else {
uint256 blocks = signBlockHasTerminator[index - 1];
rewardAddress = blockAllTerminatorAddress[blocks];
for (uint256 i = 0; i < 50; i++) {
if (rewardAddress[i] == address(0)) {
break;
}
rewardAmount[i] = terminatorAllReward[rewardAddress[i]][2];
}
return (blocks, rewardAddress, rewardAmount);
}
}
//获取可提现奖励金额
function getTerminatorRewardAmount(address addr)
view public
returns (uint256)
{
return terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3];
}
//获取用户所有奖励金额和已提现金额和上一次获奖金额和复投金额
function getUserTerminatorRewardInfo(address addr)
view public
returns (uint256[4] memory)
{
return terminatorAllReward[addr];
}
//获取所有产生终结者的区块数组
function getAllTerminatorBlockNumber()
view public
returns (uint256[] memory){
return signBlockHasTerminator;
}
//获取当次已提走奖池金额(供主合约调用)
function checkBlockWithdrawAmount(uint256 blockNumber)
view public
returns (uint256)
{
if (blockNumber >= BlockNumber + 240 && BlockNumber != 0) {
return (TerminatorRewardPool + TerminatorRewardWithdrawPool);
} else {
return (TerminatorRewardWithdrawPool);
}
}
//检查合约拥有者权限
modifier checkTerminatorOwner(address addr)
{
require(addr == terminatorOwner);
_;
}
//检查合约调用者权限(检查是否是主合约调用)
modifier checkCallOwner(address addr)
{
require(addr == callOwner || addr == terminatorOwner);
_;
}
}
//备注:
//部署完主合约后,需要调用该合约的addCallOwner方法,传入主合约地址,为主合约调该合约方法添加权限
|
产生终结者,将终结者信息写入并计算奖励(内部调用)
|
function addRecodeToTerminatorArray(uint256 blockNumber)
internal
{
for (uint256 i = 0; i < 50; i++) {
if (i >= signRecodeTerminator) {
break;
}
address userAddress = recodeTerminatorInfo[i].userAddress;
uint256 reward = (recodeTerminatorInfo[i].amountInvest) * (TerminatorRewardPool) / (AllTerminatorInvestAmount);
blockAllTerminatorAddress[blockNumber][i] = userAddress;
terminatorAllReward[userAddress][0] += reward;
terminatorAllReward[userAddress][2] = reward;
}
TerminatorRewardWithdrawPool += TerminatorRewardPool;
emit AchieveTerminator(blockNumber);
}
| 939,179 |
./partial_match/1/0xeC91E38a6Bd8D25c582d86bECdAd2003A25deECC/sources/src/WrappedReaper.sol
|
Computes how close a mint was to death. The closer to death, the higher the value. Relies on the fact that deathBlock must be >= mintBlock, and the difference between these must be <= to the Reaper's nine day grace period. Also depends on 0.8.x's builtin underflow protection. return The proximity of the token to death.
|
function proximity(uint256 deathBlock, uint256 mintBlock) public pure returns (uint256) {
return _GRACE_PERIOD - (deathBlock - mintBlock);
}
| 15,505,074 |
/**
*Submitted for verification at Etherscan.io on 2022-02-07
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
//////////////////////////////////////////////////////////////////////
// __ ___ ____ _ _____ __ //
// / |/ /_ __/ / /_(_) ___/___ ____ ____/ /__ _____ //
// / /|_/ / / / / / __/ /\__ \/ _ \/ __ \/ __ / _ \/ ___/ //
// / / / / /_/ / / /_/ /___/ / __/ / / / /_/ / __/ / //
// /_/ /_/\__,_/_/\__/_//____/\___/_/ /_/\__,_/\___/_/ //
// by 0xInuarashi.eth //
// //
//////////////////////////////////////////////////////////////////////
interface IERC20 {
function balanceOf(address address_) external view returns (uint256);
function transferFrom(address from_, address to_, uint256 amount_) external
returns (bool);
}
interface IERC721 {
function ownerOf(uint256 tokenId_) external view returns (address);
function transferFrom(address from_, address to_, uint256 tokenId_) external;
}
interface IERC1155 {
function balanceOf(address address_, uint256 tokenId_) external view
returns (uint256);
function safeTransferFrom(address from_, address to_, uint256 tokenId_,
uint256 amount_, bytes calldata data_) external;
}
contract MultiSender {
// Internal Functions
function _sendETH(address payable address_, uint256 amount_) internal {
(bool success, ) = payable(address_).call{value: amount_}("");
require(success, "Transfer failed");
}
function _calculateTotalAmounts(uint256[] memory amounts_) internal pure
returns (uint256 _totalAmount) {
for (uint256 i = 0; i < amounts_.length; i++) {
_totalAmount += amounts_[i];
}
}
function multiSendETH(address payable[] calldata addresses_,
uint256[] calldata amounts_, bool useChecks_) external payable {
require(addresses_.length == amounts_.length,
"Array lengths mismatch!");
// We use loop checks but we can opt out to save gas
if (useChecks_) {
// Get the Total Amount
uint256 _totalAmount = _calculateTotalAmounts(amounts_);
require(msg.value == _totalAmount,
"Invalid amount of ETH sent!");
}
// Multi-Send the ETHs
for (uint256 i = 0; i < addresses_.length; i++) {
_sendETH(addresses_[i], amounts_[i]);
}
}
function multiSendERC20(address erc20_, address[] calldata addresses_,
uint256[] calldata amounts_, bool useChecks_) external {
require(addresses_.length == amounts_.length,
"Array lengths mismatch!");
// We use loop checks but we can opt out to save gas
if (useChecks_) {
// Get the Total Amount
uint256 _totalAmount = _calculateTotalAmounts(amounts_);
// Make sure the msg.sender has enough ETH
require(IERC20(erc20_).balanceOf(msg.sender) >= _totalAmount,
"msg.sender does not have enough balance!");
}
// Multi-Send ERC20s
for (uint256 i = 0; i < addresses_.length; i++) {
IERC20(erc20_).transferFrom(msg.sender, addresses_[i], amounts_[i]);
}
}
function multiSendERC721(address erc721_, address[] calldata addresses_,
uint256[] calldata tokenIds_, bool useChecks_) external {
require(addresses_.length == tokenIds_.length,
"Array lengths mismatch!");
if (useChecks_) {
for (uint256 i = 0; i < tokenIds_.length; i++) {
require(msg.sender == IERC721(erc721_).ownerOf(tokenIds_[i]),
"You are not the owner of this token!");
}
}
// Multi-Send ERC721s
for (uint256 i = 0; i < addresses_.length; i++) {
IERC721(erc721_).transferFrom(msg.sender, addresses_[i], tokenIds_[i]);
}
}
function multiSendERC1155(address erc1155_, address[] calldata addresses_,
uint256[] calldata tokenIds_, uint256[] calldata amounts_,
bytes calldata data_) external {
require(addresses_.length == tokenIds_.length
&& addresses_.length == amounts_.length,
"Array lengths mismatch!");
// No checks for this one.
for (uint256 i = 0; i < addresses_.length; i++) {
IERC1155(erc1155_).safeTransferFrom(msg.sender, addresses_[i], tokenIds_[i],
amounts_[i], data_);
}
}
}
|
We use loop checks but we can opt out to save gas Get the Total Amount Make sure the msg.sender has enough ETH Multi-Send ERC20s
|
function multiSendERC20(address erc20_, address[] calldata addresses_,
uint256[] calldata amounts_, bool useChecks_) external {
require(addresses_.length == amounts_.length,
"Array lengths mismatch!");
if (useChecks_) {
uint256 _totalAmount = _calculateTotalAmounts(amounts_);
require(IERC20(erc20_).balanceOf(msg.sender) >= _totalAmount,
"msg.sender does not have enough balance!");
}
for (uint256 i = 0; i < addresses_.length; i++) {
IERC20(erc20_).transferFrom(msg.sender, addresses_[i], amounts_[i]);
}
}
| 10,838,500 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "ERC721Enumerable.sol";
import "SafeMath.sol";
import "Counters.sol";
import "Ownable.sol";
import "Pausable.sol";
import "BPC.sol";
import "BPCSenderRecipient.sol";
import "ExternalFuncs.sol";
contract BPCLottery is ERC721, ERC777SenderRecipientMock, Ownable, Pausable {
//using ExternalFuncs for *;
using Counters for Counters.Counter;
using SafeMath for uint256;
IERC777 private m_bpc;
bool private m_bpc_is_set;
modifier isTokenSet() {
require(m_bpc_is_set, "ERC777 is not set");
_;
}
address private m_company_account;
Counters.Counter private m_ticket_id;
Counters.Counter private m_lottery_id;
uint256 private m_ticket_price;
bool private is_lottery_open;
uint256 private constant m_duration = 7 days;
struct Winner {
uint256 ticket_id;
address addr;
bool isSet;
}
mapping(uint256 => uint256) private m_lottery_id_pot;
mapping(uint256 => uint256) private m_lottery_id_expires_at;
mapping(uint256 => bool) private m_lottery_id_paid;
mapping(uint256 => Winner) private m_lottery_id_winner;
event WinnerAnnounced(
address winner,
uint256 winner_id,
uint256 lottery_id,
uint256 prize_size
);
event WinnerPaid(address winner, uint256 lottery_id, uint256 prize_size);
constructor(
string memory _name,
string memory _symbol,
uint256 _ticket_price,
address _company_account
) ERC721(_name, _symbol) {
m_company_account = _company_account;
// ERC-777 receiver init
// See https://forum.openzeppelin.com/t/simple-erc777-token-example/746
_erc1820.setInterfaceImplementer(
address(this),
_TOKENS_RECIPIENT_INTERFACE_HASH,
address(this)
);
m_ticket_price = _ticket_price != 0
? _ticket_price
: 5000000000000000000; // 5 * 10^18
m_lottery_id_expires_at[m_lottery_id.current()] = block.timestamp.add(
m_duration
);
m_lottery_id_paid[m_lottery_id.current()] = false;
is_lottery_open = true;
m_bpc_is_set = false;
}
function setERC777(address _bpc) public onlyOwner {
require(_bpc != address(0), "BPC address cannot be 0");
require(
!m_bpc_is_set,
"You have already set BPC address, can't do it again"
);
m_bpc = IERC777(_bpc);
m_bpc_is_set = true;
}
function pause() public onlyOwner whenNotPaused {
_pause();
}
function unPause() public onlyOwner whenPaused {
_unpause();
}
//function paused() public view comes as a base class method of Pausable
function setTicketPrice(uint256 new_ticket_price)
public
onlyOwner
isTokenSet
{
require(new_ticket_price > 0, "Ticket price should be greater than 0");
m_ticket_price = new_ticket_price;
}
//when not paused
function getTicketPrice() public view returns (uint256) {
require(!paused(), "Lottery is paused, please come back later");
return m_ticket_price;
}
//when not paused
function buyTicket(uint256 bpc_tokens_amount, address participant)
public
isTokenSet
{
require(!paused(), "Lottery is paused, please come back later");
require(
m_bpc.isOperatorFor(msg.sender, participant),
"You MUST be an operator for participant"
);
require(
bpc_tokens_amount.mod(m_ticket_price) == 0,
"Tokens amount should be a multiple of a Ticket Price"
);
require(
m_bpc.balanceOf(participant) >= bpc_tokens_amount,
"You should have enough of Tokens in your Wallet"
);
m_bpc.operatorSend(
participant,
address(this),
bpc_tokens_amount,
bytes(""),
bytes("")
);
m_lottery_id_pot[m_lottery_id.current()] = m_lottery_id_pot[
m_lottery_id.current()
].add(bpc_tokens_amount);
uint256 tickets_count = bpc_tokens_amount.div(m_ticket_price);
for (uint256 i = 0; i != tickets_count; ++i) {
m_ticket_id.increment();
_mint(participant, m_ticket_id.current());
}
}
//when not paused
function getCurrentLotteryTicketsCount(address participant)
public
view
returns (uint256)
{
require(!paused(), "Lottery is paused, please come back later");
require(
m_bpc.isOperatorFor(msg.sender, participant),
"You MUST be an operator for participant"
);
return this.balanceOf(participant);
}
function getCurrentLotteryId() public view returns (uint256) {
return m_lottery_id.current();
}
function getCurrentLotteryPot() public view returns (uint256) {
return m_lottery_id_pot[m_lottery_id.current()];
}
function announceWinnerAndRevolve() public onlyOwner isTokenSet {
require(isLotteryPeriodOver(), "The current lottery is still running");
forceAnnounceWinnerAndRevolve();
}
function forceAnnounceWinnerAndRevolve() public onlyOwner isTokenSet {
uint256 prize_size = m_lottery_id_pot[m_lottery_id.current()].div(2);
uint256 id = m_lottery_id.current();
if (!m_lottery_id_winner[id].isSet) {
m_lottery_id_winner[id] = setWinner(prize_size);
}
if (!isEmptyWinner(m_lottery_id_winner[id]) && !m_lottery_id_paid[id]) {
splitPotWith(m_lottery_id_winner[id].addr, prize_size);
m_lottery_id_paid[id] = true;
m_lottery_id_pot[id] = 0;
}
if (!paused()) {
revolveLottery();
}
}
function isLotteryPeriodOver() private view returns (bool) {
return
m_lottery_id_expires_at[m_lottery_id.current()] < block.timestamp;
}
function getWinner(uint256 id) public view returns (address) {
require(
m_lottery_id_winner[id].isSet,
"Lottery Id Winner or Lottery Id not found"
);
return m_lottery_id_winner[id].addr;
}
function setWinner(uint256 prize_size) private returns (Winner memory) {
Winner memory winner;
winner.isSet = true;
if (m_ticket_id.current() != 0) {
winner.ticket_id = prng().mod(m_ticket_id.current()).add(1);
winner.addr = this.ownerOf(winner.ticket_id);
emit WinnerAnnounced(
winner.addr,
winner.ticket_id,
m_lottery_id.current(),
prize_size
);
} else {
winner.ticket_id = 0;
winner.addr = address(0);
}
return winner;
}
function isEmptyWinner(Winner memory winner) private pure returns (bool) {
return winner.addr == address(0);
}
function splitPotWith(address winner_address, uint256 prize_size) private {
m_bpc.operatorSend(
address(this),
winner_address,
prize_size,
bytes(""),
bytes("")
);
m_bpc.operatorSend(
address(this),
m_company_account,
prize_size,
bytes(""),
bytes("")
);
emit WinnerPaid(winner_address, m_lottery_id.current(), prize_size);
}
function revolveLottery() private {
uint256 size = m_ticket_id.current();
if (size != 0) {
for (uint256 i = 1; i <= size; ++i) {
_burn(i);
}
}
m_ticket_id.reset();
m_lottery_id.increment();
m_lottery_id_expires_at[m_lottery_id.current()] = block.timestamp.add(
m_duration
);
}
function prng() private view returns (uint256) {
return
uint256(
keccak256(
abi.encodePacked(
block.difficulty,
block.timestamp,
m_ticket_id.current()
)
)
);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "ERC721.sol";
import "IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "IERC721.sol";
import "IERC721Receiver.sol";
import "IERC721Metadata.sol";
import "Address.sol";
import "Context.sol";
import "Strings.sol";
import "ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "ERC777.sol";
import "AccessControl.sol";
import "SafeMath.sol";
import "ReentrancyGuard.sol";
contract BPC is ERC777, AccessControl, ReentrancyGuard {
using SafeMath for uint256;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
uint256 private constant m_tokens_per_eth = 100;
address private m_company_account;
uint256 private m_entry_fee;
uint256 private m_exit_fee;
uint256 private m_max_supply;
constructor(
string memory _name,
string memory _symbol,
address[] memory _default_operators,
uint256 _max_supply,
uint256 _initial_supply,
uint256 _entry_fee,
uint256 _exit_fee,
address _managing_account,
address _company_account
) ERC777(_name, _symbol, _default_operators) {
_grantRole(DEFAULT_ADMIN_ROLE, _managing_account);
_grantRole(MINTER_ROLE, _company_account);
m_max_supply = _max_supply;
_mint(_company_account, _initial_supply, "", "", false);
m_company_account = _company_account;
m_entry_fee = _entry_fee;
m_exit_fee = _exit_fee;
}
function mint(uint256 amount) public onlyRole(MINTER_ROLE) {
require(
totalSupply().add(amount) <= m_max_supply,
"Amount that is about to be minted reaches the Max Supply"
);
_mint(msg.sender, amount, bytes(""), bytes(""), false);
}
//burn and operatorBurn of ERC777 make all required checks and update _totalSupply that holds current Tokens qty
//no need to override those funcs
function fromEtherToTokens() public payable {
uint256 tokens_to_buy = msg.value * m_tokens_per_eth;
uint256 company_token_balance = this.balanceOf(m_company_account);
require(
tokens_to_buy > 0,
"You need to send some more ether, what you provide is not enough for transaction"
);
require(
tokens_to_buy <= company_token_balance,
"Not enough tokens in the reserve"
);
uint256 updated_value = getEntryFeeValue(tokens_to_buy);
_send(
m_company_account,
msg.sender,
updated_value,
bytes(""),
bytes(""),
false
);
}
function fromTokensToEther(uint256 tokens_to_sell) public nonReentrant {
require(tokens_to_sell > 0, "You need to sell at least some tokens");
// Check that the user's token balance is enough to do the swap
uint256 user_token_balance = this.balanceOf(msg.sender);
require(
user_token_balance >= tokens_to_sell,
"Your balance is lower than the amount of tokens you want to sell"
);
uint256 updated_value = getExitFeeValue(tokens_to_sell);
uint256 eth_to_transfer = updated_value / m_tokens_per_eth;
uint256 company_eth_balance = address(this).balance;
require(
company_eth_balance >= eth_to_transfer,
"BPC Owner doesn't have enough funds to accept this sell request"
);
_send(
msg.sender,
m_company_account,
tokens_to_sell,
bytes(""),
bytes(""),
false
);
payable(msg.sender).transfer(eth_to_transfer);
}
function getTokenPrice() public view returns (uint256) {
return m_tokens_per_eth;
}
function getEntryFee() public view returns (uint256) {
return m_entry_fee;
}
function getExitFee() public view returns (uint256) {
return m_exit_fee;
}
function setEntryFee(uint256 fee) public onlyRole(DEFAULT_ADMIN_ROLE) {
require(
fee >= 0 && fee <= 100,
"Fee must be an integer percentage, ie 42"
);
m_entry_fee = fee;
}
function setExitFee(uint256 fee) public onlyRole(DEFAULT_ADMIN_ROLE) {
require(
fee >= 0 && fee <= 100,
"Fee must be an integer percentage, ie 42"
);
m_exit_fee = fee;
}
function getEntryFeeValue(uint256 value) private view returns (uint256) {
if (m_entry_fee != 0) {
uint256 fee_value = (m_entry_fee * value) / 100;
uint256 updated_value = value - fee_value;
return updated_value;
} else {
return value;
}
}
function getExitFeeValue(uint256 value) private view returns (uint256) {
if (m_exit_fee != 0) {
uint256 fee_value = (m_exit_fee * value) / 100;
uint256 updated_value = value - fee_value;
return updated_value;
} else {
return value;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC777/ERC777.sol)
pragma solidity ^0.8.0;
import "IERC777.sol";
import "IERC777Recipient.sol";
import "IERC777Sender.sol";
import "IERC20.sol";
import "Address.sol";
import "Context.sol";
import "IERC1820Registry.sol";
/**
* @dev Implementation of the {IERC777} 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}.
*
* Support for ERC20 is included in this contract, as specified by the EIP: both
* the ERC777 and ERC20 interfaces can be safely used when interacting with it.
* Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token
* movements.
*
* Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there
* are no special restrictions in the amount of tokens that created, moved, or
* destroyed. This makes integration with ERC20 applications seamless.
*/
contract ERC777 is Context, IERC777, IERC20 {
using Address for address;
IERC1820Registry internal constant _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
mapping(address => uint256) private _balances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
bytes32 private constant _TOKENS_SENDER_INTERFACE_HASH = keccak256("ERC777TokensSender");
bytes32 private constant _TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient");
// This isn't ever read from - it's only used to respond to the defaultOperators query.
address[] private _defaultOperatorsArray;
// Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators).
mapping(address => bool) private _defaultOperators;
// For each account, a mapping of its operators and revoked default operators.
mapping(address => mapping(address => bool)) private _operators;
mapping(address => mapping(address => bool)) private _revokedDefaultOperators;
// ERC20-allowances
mapping(address => mapping(address => uint256)) private _allowances;
/**
* @dev `defaultOperators` may be an empty array.
*/
constructor(
string memory name_,
string memory symbol_,
address[] memory defaultOperators_
) {
_name = name_;
_symbol = symbol_;
_defaultOperatorsArray = defaultOperators_;
for (uint256 i = 0; i < defaultOperators_.length; i++) {
_defaultOperators[defaultOperators_[i]] = true;
}
// register interfaces
_ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this));
_ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this));
}
/**
* @dev See {IERC777-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC777-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {ERC20-decimals}.
*
* Always returns 18, as per the
* [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility).
*/
function decimals() public pure virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC777-granularity}.
*
* This implementation always returns `1`.
*/
function granularity() public view virtual override returns (uint256) {
return 1;
}
/**
* @dev See {IERC777-totalSupply}.
*/
function totalSupply() public view virtual override(IERC20, IERC777) returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the amount of tokens owned by an account (`tokenHolder`).
*/
function balanceOf(address tokenHolder) public view virtual override(IERC20, IERC777) returns (uint256) {
return _balances[tokenHolder];
}
/**
* @dev See {IERC777-send}.
*
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/
function send(
address recipient,
uint256 amount,
bytes memory data
) public virtual override {
_send(_msgSender(), recipient, amount, data, "", true);
}
/**
* @dev See {IERC20-transfer}.
*
* Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient}
* interface if it is a contract.
*
* Also emits a {Sent} event.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
address from = _msgSender();
_callTokensToSend(from, from, recipient, amount, "", "");
_move(from, from, recipient, amount, "", "");
_callTokensReceived(from, from, recipient, amount, "", "", false);
return true;
}
/**
* @dev See {IERC777-burn}.
*
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/
function burn(uint256 amount, bytes memory data) public virtual override {
_burn(_msgSender(), amount, data, "");
}
/**
* @dev See {IERC777-isOperatorFor}.
*/
function isOperatorFor(address operator, address tokenHolder) public view virtual override returns (bool) {
return
operator == tokenHolder ||
(_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) ||
_operators[tokenHolder][operator];
}
/**
* @dev See {IERC777-authorizeOperator}.
*/
function authorizeOperator(address operator) public virtual override {
require(_msgSender() != operator, "ERC777: authorizing self as operator");
if (_defaultOperators[operator]) {
delete _revokedDefaultOperators[_msgSender()][operator];
} else {
_operators[_msgSender()][operator] = true;
}
emit AuthorizedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-revokeOperator}.
*/
function revokeOperator(address operator) public virtual override {
require(operator != _msgSender(), "ERC777: revoking self as operator");
if (_defaultOperators[operator]) {
_revokedDefaultOperators[_msgSender()][operator] = true;
} else {
delete _operators[_msgSender()][operator];
}
emit RevokedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-defaultOperators}.
*/
function defaultOperators() public view virtual override returns (address[] memory) {
return _defaultOperatorsArray;
}
/**
* @dev See {IERC777-operatorSend}.
*
* Emits {Sent} and {IERC20-Transfer} events.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes memory data,
bytes memory operatorData
) public virtual override {
require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder");
_send(sender, recipient, amount, data, operatorData, true);
}
/**
* @dev See {IERC777-operatorBurn}.
*
* Emits {Burned} and {IERC20-Transfer} events.
*/
function operatorBurn(
address account,
uint256 amount,
bytes memory data,
bytes memory operatorData
) public virtual override {
require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder");
_burn(account, amount, data, operatorData);
}
/**
* @dev See {IERC20-allowance}.
*
* Note that operator and allowance concepts are orthogonal: operators may
* not have allowance, and accounts with allowance may not be operators
* themselves.
*/
function allowance(address holder, address spender) public view virtual override returns (uint256) {
return _allowances[holder][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function approve(address spender, uint256 value) public virtual override returns (bool) {
address holder = _msgSender();
_approve(holder, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Note that operator and allowance concepts are orthogonal: operators cannot
* call `transferFrom` (unless they have allowance), and accounts with
* allowance cannot call `operatorSend` (unless they are operators).
*
* Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events.
*/
function transferFrom(
address holder,
address recipient,
uint256 amount
) public virtual override returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
require(holder != address(0), "ERC777: transfer from the zero address");
address spender = _msgSender();
_callTokensToSend(spender, holder, recipient, amount, "", "");
_move(spender, holder, recipient, amount, "", "");
uint256 currentAllowance = _allowances[holder][spender];
require(currentAllowance >= amount, "ERC777: transfer amount exceeds allowance");
_approve(holder, spender, currentAllowance - amount);
_callTokensReceived(spender, holder, recipient, amount, "", "", false);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `operator`, `data` and `operatorData`.
*
* See {IERC777Sender} and {IERC777Recipient}.
*
* Emits {Minted} and {IERC20-Transfer} events.
*
* Requirements
*
* - `account` cannot be the zero address.
* - if `account` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function _mint(
address account,
uint256 amount,
bytes memory userData,
bytes memory operatorData
) internal virtual {
_mint(account, amount, userData, operatorData, true);
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* If `requireReceptionAck` is set to true, and if a send hook is
* registered for `account`, the corresponding function will be called with
* `operator`, `data` and `operatorData`.
*
* See {IERC777Sender} and {IERC777Recipient}.
*
* Emits {Minted} and {IERC20-Transfer} events.
*
* Requirements
*
* - `account` cannot be the zero address.
* - if `account` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function _mint(
address account,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
) internal virtual {
require(account != address(0), "ERC777: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, amount);
// Update state variables
_totalSupply += amount;
_balances[account] += amount;
_callTokensReceived(operator, address(0), account, amount, userData, operatorData, requireReceptionAck);
emit Minted(operator, account, amount, userData, operatorData);
emit Transfer(address(0), account, amount);
}
/**
* @dev Send tokens
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _send(
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
) internal virtual {
require(from != address(0), "ERC777: send from the zero address");
require(to != address(0), "ERC777: send to the zero address");
address operator = _msgSender();
_callTokensToSend(operator, from, to, amount, userData, operatorData);
_move(operator, from, to, amount, userData, operatorData);
_callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck);
}
/**
* @dev Burn tokens
* @param from address token holder address
* @param amount uint256 amount of tokens to burn
* @param data bytes extra information provided by the token holder
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _burn(
address from,
uint256 amount,
bytes memory data,
bytes memory operatorData
) internal virtual {
require(from != address(0), "ERC777: burn from the zero address");
address operator = _msgSender();
_callTokensToSend(operator, from, address(0), amount, data, operatorData);
_beforeTokenTransfer(operator, from, address(0), amount);
// Update state variables
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC777: burn amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_totalSupply -= amount;
emit Burned(operator, from, amount, data, operatorData);
emit Transfer(from, address(0), amount);
}
function _move(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
) private {
_beforeTokenTransfer(operator, from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC777: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Sent(operator, from, to, amount, userData, operatorData);
emit Transfer(from, to, amount);
}
/**
* @dev See {ERC20-_approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function _approve(
address holder,
address spender,
uint256 value
) internal {
require(holder != address(0), "ERC777: approve from the zero address");
require(spender != address(0), "ERC777: approve to the zero address");
_allowances[holder][spender] = value;
emit Approval(holder, spender, value);
}
/**
* @dev Call from.tokensToSend() if the interface is registered
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _callTokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
) private {
address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData);
}
}
/**
* @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but
* tokensReceived() was not registered for the recipient
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _callTokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
) private {
address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData);
} else if (requireReceptionAck) {
require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient");
}
}
/**
* @dev Hook that is called before any token transfer. This includes
* calls to {send}, {transfer}, {operatorSend}, 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 operator,
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC777Token standard as defined in the EIP.
*
* This contract uses the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let
* token holders and recipients react to token movements by using setting implementers
* for the associated interfaces in said registry. See {IERC1820Registry} and
* {ERC1820Implementer}.
*/
interface IERC777 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the smallest part of the token that is not divisible. This
* means all token operations (creation, movement and destruction) must have
* amounts that are a multiple of this number.
*
* For most token contracts, this value will equal 1.
*/
function granularity() external view returns (uint256);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by an account (`owner`).
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* If send or receive hooks are registered for the caller and `recipient`,
* the corresponding functions will be called with `data` and empty
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function send(
address recipient,
uint256 amount,
bytes calldata data
) external;
/**
* @dev Destroys `amount` tokens from the caller's account, reducing the
* total supply.
*
* If a send hook is registered for the caller, the corresponding function
* will be called with `data` and empty `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
*/
function burn(uint256 amount, bytes calldata data) external;
/**
* @dev Returns true if an account is an operator of `tokenHolder`.
* Operators can send and burn tokens on behalf of their owners. All
* accounts are their own operator.
*
* See {operatorSend} and {operatorBurn}.
*/
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
/**
* @dev Make an account an operator of the caller.
*
* See {isOperatorFor}.
*
* Emits an {AuthorizedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function authorizeOperator(address operator) external;
/**
* @dev Revoke an account's operator status for the caller.
*
* See {isOperatorFor} and {defaultOperators}.
*
* Emits a {RevokedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function revokeOperator(address operator) external;
/**
* @dev Returns the list of default operators. These accounts are operators
* for all token holders, even if {authorizeOperator} was never called on
* them.
*
* This list is immutable, but individual holders may revoke these via
* {revokeOperator}, in which case {isOperatorFor} will return false.
*/
function defaultOperators() external view returns (address[] memory);
/**
* @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
* be an operator of `sender`.
*
* If send or receive hooks are registered for `sender` and `recipient`,
* the corresponding functions will be called with `data` and
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - `sender` cannot be the zero address.
* - `sender` must have at least `amount` tokens.
* - the caller must be an operator for `sender`.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
/**
* @dev Destroys `amount` tokens from `account`, reducing the total supply.
* The caller must be an operator of `account`.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `data` and `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
* - the caller must be an operator for `account`.
*/
function operatorBurn(
address account,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777Recipient.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC777TokensRecipient standard as defined in the EIP.
*
* Accounts can be notified of {IERC777} tokens being sent to them by having a
* contract implement this interface (contract holders can be their own
* implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Recipient {
/**
* @dev Called by an {IERC777} token contract whenever tokens are being
* moved or created into a registered account (`to`). The type of operation
* is conveyed by `from` being the zero address or not.
*
* This call occurs _after_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the post-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777Sender.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC777TokensSender standard as defined in the EIP.
*
* {IERC777} Token holders can be notified of operations performed on their
* tokens by having a contract implement this interface (contract holders can be
* their own implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Sender {
/**
* @dev Called by an {IERC777} token contract whenever a registered holder's
* (`from`) tokens are about to be moved or destroyed. The type of operation
* is conveyed by `to` being the zero address or not.
*
* This call occurs _before_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the pre-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC1820Registry.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as ``account``'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(
address account,
bytes32 _interfaceHash,
address implementer
) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "IAccessControl.sol";
import "Context.sol";
import "Strings.sol";
import "ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been 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());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "IERC777.sol";
import "IERC777Sender.sol";
import "IERC777Recipient.sol";
import "Context.sol";
import "IERC1820Registry.sol";
import "ERC1820Implementer.sol";
contract ERC777SenderRecipientMock is Context, IERC777Sender, IERC777Recipient, ERC1820Implementer {
event TokensToSendCalled(
address operator,
address from,
address to,
uint256 amount,
bytes data,
bytes operatorData,
address token,
uint256 fromBalance,
uint256 toBalance
);
event TokensReceivedCalled(
address operator,
address from,
address to,
uint256 amount,
bytes data,
bytes operatorData,
address token,
uint256 fromBalance,
uint256 toBalance
);
// Emitted in ERC777Mock. Here for easier decoding
event BeforeTokenTransfer();
bool private _shouldRevertSend;
bool private _shouldRevertReceive;
IERC1820Registry public _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
bytes32 public constant _TOKENS_SENDER_INTERFACE_HASH = keccak256("ERC777TokensSender");
bytes32 public constant _TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient");
function tokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external override {
if (_shouldRevertSend) {
revert();
}
IERC777 token = IERC777(_msgSender());
uint256 fromBalance = token.balanceOf(from);
// when called due to burn, to will be the zero address, which will have a balance of 0
uint256 toBalance = token.balanceOf(to);
emit TokensToSendCalled(
operator,
from,
to,
amount,
userData,
operatorData,
address(token),
fromBalance,
toBalance
);
}
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external override {
if (_shouldRevertReceive) {
revert();
}
IERC777 token = IERC777(_msgSender());
uint256 fromBalance = token.balanceOf(from);
// when called due to burn, to will be the zero address, which will have a balance of 0
uint256 toBalance = token.balanceOf(to);
emit TokensReceivedCalled(
operator,
from,
to,
amount,
userData,
operatorData,
address(token),
fromBalance,
toBalance
);
}
function senderFor(address account) public {
_registerInterfaceForAddress(_TOKENS_SENDER_INTERFACE_HASH, account);
address self = address(this);
if (account == self) {
registerSender(self);
}
}
function registerSender(address sender) public {
_erc1820.setInterfaceImplementer(address(this), _TOKENS_SENDER_INTERFACE_HASH, sender);
}
function recipientFor(address account) public {
_registerInterfaceForAddress(_TOKENS_RECIPIENT_INTERFACE_HASH, account);
address self = address(this);
if (account == self) {
registerRecipient(self);
}
}
function registerRecipient(address recipient) public {
_erc1820.setInterfaceImplementer(address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, recipient);
}
function setShouldRevertSend(bool shouldRevert) public {
_shouldRevertSend = shouldRevert;
}
function setShouldRevertReceive(bool shouldRevert) public {
_shouldRevertReceive = shouldRevert;
}
function send(
IERC777 token,
address to,
uint256 amount,
bytes memory data
) public {
// This is 777's send function, not the Solidity send function
token.send(to, amount, data); // solhint-disable-line check-send-result
}
function burn(
IERC777 token,
uint256 amount,
bytes memory data
) public {
token.burn(amount, data);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC1820Implementer.sol)
pragma solidity ^0.8.0;
import "IERC1820Implementer.sol";
/**
* @dev Implementation of the {IERC1820Implementer} interface.
*
* Contracts may inherit from this and call {_registerInterfaceForAddress} to
* declare their willingness to be implementers.
* {IERC1820Registry-setInterfaceImplementer} should then be called for the
* registration to be complete.
*/
contract ERC1820Implementer is IERC1820Implementer {
bytes32 private constant _ERC1820_ACCEPT_MAGIC = keccak256("ERC1820_ACCEPT_MAGIC");
mapping(bytes32 => mapping(address => bool)) private _supportedInterfaces;
/**
* @dev See {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function canImplementInterfaceForAddress(bytes32 interfaceHash, address account)
public
view
virtual
override
returns (bytes32)
{
return _supportedInterfaces[interfaceHash][account] ? _ERC1820_ACCEPT_MAGIC : bytes32(0x00);
}
/**
* @dev Declares the contract as willing to be an implementer of
* `interfaceHash` for `account`.
*
* See {IERC1820Registry-setInterfaceImplementer} and
* {IERC1820Registry-interfaceHash}.
*/
function _registerInterfaceForAddress(bytes32 interfaceHash, address account) internal virtual {
_supportedInterfaces[interfaceHash][account] = true;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC1820Implementer.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface for an ERC1820 implementer, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820#interface-implementation-erc1820implementerinterface[EIP].
* Used by contracts that will be registered as implementers in the
* {IERC1820Registry}.
*/
interface IERC1820Implementer {
/**
* @dev Returns a special value (`ERC1820_ACCEPT_MAGIC`) if this contract
* implements `interfaceHash` for `account`.
*
* See {IERC1820Registry-setInterfaceImplementer}.
*/
function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "ABDKMath64x64.sol";
import "Strings.sol";
library ExternalFuncs {
// from here https://medium.com/coinmonks/math-in-solidity-part-4-compound-interest-512d9e13041b
/*
function pow (int128 x, uint n)
public pure returns (int128 r) {
r = ABDKMath64x64.fromUInt (1);
while (n > 0) {
if (n % 2 == 1) {
r = ABDKMath64x64.mul (r, x);
n -= 1;
} else {
x = ABDKMath64x64.mul (x, x);
n /= 2;
}
}
}
*/
function compound(
uint256 principal,
uint256 ratio,
uint256 n
) public pure returns (uint256) {
return
ABDKMath64x64.mulu(
ABDKMath64x64.pow( //pow - original code
ABDKMath64x64.add(
ABDKMath64x64.fromUInt(1),
ABDKMath64x64.divu(ratio, 10**4)
), //(1+r), where r is allowed to be one hundredth of a percent, ie 5/100/100
n
), //(1+r)^n
principal
); //A_0 * (1+r)^n
}
function Today() public view returns (uint256) {
return block.timestamp / 1 days;
}
function isStakeSizeOk(uint256 amount, uint256 decimals)
public
pure
returns (bool)
{
return
amount == 1000 * 10**decimals ||
amount == 3000 * 10**decimals ||
amount == 5000 * 10**decimals ||
amount == 10000 * 10**decimals ||
amount == 20000 * 10**decimals ||
amount == 50000 * 10**decimals ||
amount == 100000 * 10**decimals ||
amount == 250000 * 10**decimals ||
amount >= 1000000 * 10**decimals;
}
function getErrorMsg(string memory text, uint256 value)
public
pure
returns (string memory)
{
string memory _msg = string(
abi.encodePacked(text, Strings.toString(value))
);
return _msg;
}
}
// SPDX-License-Identifier: BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.8.0;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt(int256 x) internal pure returns (int128) {
unchecked {
require(x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128(x << 64);
}
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt(int128 x) internal pure returns (int64) {
unchecked {
return int64(x >> 64);
}
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt(uint256 x) internal pure returns (int128) {
unchecked {
require(x <= 0x7FFFFFFFFFFFFFFF);
return int128(int256(x << 64));
}
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt(int128 x) internal pure returns (uint64) {
unchecked {
require(x >= 0);
return uint64(uint128(x >> 64));
}
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128(int256 x) internal pure returns (int128) {
unchecked {
int256 result = x >> 64;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128(int128 x) internal pure returns (int256) {
unchecked {
return int256(x) << 64;
}
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add(int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 result = int256(x) + y;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub(int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 result = int256(x) - y;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul(int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 result = (int256(x) * y) >> 64;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli(int128 x, int256 y) internal pure returns (int256) {
unchecked {
if (x == MIN_64x64) {
require(
y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000
);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu(x, uint256(y));
if (negativeResult) {
require(
absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000
);
return -int256(absoluteResult); // We rely on overflow behavior here
} else {
require(
absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
);
return int256(absoluteResult);
}
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu(int128 x, uint256 y) internal pure returns (uint256) {
unchecked {
if (y == 0) return 0;
require(x >= 0);
uint256 lo = (uint256(int256(x)) *
(y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256(int256(x)) * (y >> 128);
require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require(
hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF -
lo
);
return hi + lo;
}
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div(int128 x, int128 y) internal pure returns (int128) {
unchecked {
require(y != 0);
int256 result = (int256(x) << 64) / y;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi(int256 x, int256 y) internal pure returns (int128) {
unchecked {
require(y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu(uint256(x), uint256(y));
if (negativeResult) {
require(absoluteResult <= 0x80000000000000000000000000000000);
return -int128(absoluteResult); // We rely on overflow behavior here
} else {
require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128(absoluteResult); // We rely on overflow behavior here
}
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu(uint256 x, uint256 y) internal pure returns (int128) {
unchecked {
require(y != 0);
uint128 result = divuu(x, y);
require(result <= uint128(MAX_64x64));
return int128(result);
}
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg(int128 x) internal pure returns (int128) {
unchecked {
require(x != MIN_64x64);
return -x;
}
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs(int128 x) internal pure returns (int128) {
unchecked {
require(x != MIN_64x64);
return x < 0 ? -x : x;
}
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv(int128 x) internal pure returns (int128) {
unchecked {
require(x != 0);
int256 result = int256(0x100000000000000000000000000000000) / x;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg(int128 x, int128 y) internal pure returns (int128) {
unchecked {
return int128((int256(x) + int256(y)) >> 1);
}
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg(int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 m = int256(x) * int256(y);
require(m >= 0);
require(
m <
0x4000000000000000000000000000000000000000000000000000000000000000
);
return int128(sqrtu(uint256(m)));
}
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow(int128 x, uint256 y) internal pure returns (int128) {
unchecked {
bool negative = x < 0 && y & 1 == 1;
uint256 absX = uint128(x < 0 ? -x : x);
uint256 absResult;
absResult = 0x100000000000000000000000000000000;
if (absX <= 0x10000000000000000) {
absX <<= 63;
while (y != 0) {
if (y & 0x1 != 0) {
absResult = (absResult * absX) >> 127;
}
absX = (absX * absX) >> 127;
if (y & 0x2 != 0) {
absResult = (absResult * absX) >> 127;
}
absX = (absX * absX) >> 127;
if (y & 0x4 != 0) {
absResult = (absResult * absX) >> 127;
}
absX = (absX * absX) >> 127;
if (y & 0x8 != 0) {
absResult = (absResult * absX) >> 127;
}
absX = (absX * absX) >> 127;
y >>= 4;
}
absResult >>= 64;
} else {
uint256 absXShift = 63;
if (absX < 0x1000000000000000000000000) {
absX <<= 32;
absXShift -= 32;
}
if (absX < 0x10000000000000000000000000000) {
absX <<= 16;
absXShift -= 16;
}
if (absX < 0x1000000000000000000000000000000) {
absX <<= 8;
absXShift -= 8;
}
if (absX < 0x10000000000000000000000000000000) {
absX <<= 4;
absXShift -= 4;
}
if (absX < 0x40000000000000000000000000000000) {
absX <<= 2;
absXShift -= 2;
}
if (absX < 0x80000000000000000000000000000000) {
absX <<= 1;
absXShift -= 1;
}
uint256 resultShift = 0;
while (y != 0) {
require(absXShift < 64);
if (y & 0x1 != 0) {
absResult = (absResult * absX) >> 127;
resultShift += absXShift;
if (absResult > 0x100000000000000000000000000000000) {
absResult >>= 1;
resultShift += 1;
}
}
absX = (absX * absX) >> 127;
absXShift <<= 1;
if (absX >= 0x100000000000000000000000000000000) {
absX >>= 1;
absXShift += 1;
}
y >>= 1;
}
require(resultShift < 64);
absResult >>= 64 - resultShift;
}
int256 result = negative ? -int256(absResult) : int256(absResult);
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt(int128 x) internal pure returns (int128) {
unchecked {
require(x >= 0);
return int128(sqrtu(uint256(int256(x)) << 64));
}
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2(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);
}
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @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(log_2(x))) *
0xB17217F7D1CF79ABC9E3B39803F2F6AF) >> 128
)
);
}
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2(int128 x) internal pure returns (int128) {
unchecked {
require(x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = (result * 0x16A09E667F3BCC908B2FB1366EA957D3E) >> 128;
if (x & 0x4000000000000000 > 0)
result = (result * 0x1306FE0A31B7152DE8D5A46305C85EDEC) >> 128;
if (x & 0x2000000000000000 > 0)
result = (result * 0x1172B83C7D517ADCDF7C8C50EB14A791F) >> 128;
if (x & 0x1000000000000000 > 0)
result = (result * 0x10B5586CF9890F6298B92B71842A98363) >> 128;
if (x & 0x800000000000000 > 0)
result = (result * 0x1059B0D31585743AE7C548EB68CA417FD) >> 128;
if (x & 0x400000000000000 > 0)
result = (result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8) >> 128;
if (x & 0x200000000000000 > 0)
result = (result * 0x10163DA9FB33356D84A66AE336DCDFA3F) >> 128;
if (x & 0x100000000000000 > 0)
result = (result * 0x100B1AFA5ABCBED6129AB13EC11DC9543) >> 128;
if (x & 0x80000000000000 > 0)
result = (result * 0x10058C86DA1C09EA1FF19D294CF2F679B) >> 128;
if (x & 0x40000000000000 > 0)
result = (result * 0x1002C605E2E8CEC506D21BFC89A23A00F) >> 128;
if (x & 0x20000000000000 > 0)
result = (result * 0x100162F3904051FA128BCA9C55C31E5DF) >> 128;
if (x & 0x10000000000000 > 0)
result = (result * 0x1000B175EFFDC76BA38E31671CA939725) >> 128;
if (x & 0x8000000000000 > 0)
result = (result * 0x100058BA01FB9F96D6CACD4B180917C3D) >> 128;
if (x & 0x4000000000000 > 0)
result = (result * 0x10002C5CC37DA9491D0985C348C68E7B3) >> 128;
if (x & 0x2000000000000 > 0)
result = (result * 0x1000162E525EE054754457D5995292026) >> 128;
if (x & 0x1000000000000 > 0)
result = (result * 0x10000B17255775C040618BF4A4ADE83FC) >> 128;
if (x & 0x800000000000 > 0)
result = (result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB) >> 128;
if (x & 0x400000000000 > 0)
result = (result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9) >> 128;
if (x & 0x200000000000 > 0)
result = (result * 0x10000162E43F4F831060E02D839A9D16D) >> 128;
if (x & 0x100000000000 > 0)
result = (result * 0x100000B1721BCFC99D9F890EA06911763) >> 128;
if (x & 0x80000000000 > 0)
result = (result * 0x10000058B90CF1E6D97F9CA14DBCC1628) >> 128;
if (x & 0x40000000000 > 0)
result = (result * 0x1000002C5C863B73F016468F6BAC5CA2B) >> 128;
if (x & 0x20000000000 > 0)
result = (result * 0x100000162E430E5A18F6119E3C02282A5) >> 128;
if (x & 0x10000000000 > 0)
result = (result * 0x1000000B1721835514B86E6D96EFD1BFE) >> 128;
if (x & 0x8000000000 > 0)
result = (result * 0x100000058B90C0B48C6BE5DF846C5B2EF) >> 128;
if (x & 0x4000000000 > 0)
result = (result * 0x10000002C5C8601CC6B9E94213C72737A) >> 128;
if (x & 0x2000000000 > 0)
result = (result * 0x1000000162E42FFF037DF38AA2B219F06) >> 128;
if (x & 0x1000000000 > 0)
result = (result * 0x10000000B17217FBA9C739AA5819F44F9) >> 128;
if (x & 0x800000000 > 0)
result = (result * 0x1000000058B90BFCDEE5ACD3C1CEDC823) >> 128;
if (x & 0x400000000 > 0)
result = (result * 0x100000002C5C85FE31F35A6A30DA1BE50) >> 128;
if (x & 0x200000000 > 0)
result = (result * 0x10000000162E42FF0999CE3541B9FFFCF) >> 128;
if (x & 0x100000000 > 0)
result = (result * 0x100000000B17217F80F4EF5AADDA45554) >> 128;
if (x & 0x80000000 > 0)
result = (result * 0x10000000058B90BFBF8479BD5A81B51AD) >> 128;
if (x & 0x40000000 > 0)
result = (result * 0x1000000002C5C85FDF84BD62AE30A74CC) >> 128;
if (x & 0x20000000 > 0)
result = (result * 0x100000000162E42FEFB2FED257559BDAA) >> 128;
if (x & 0x10000000 > 0)
result = (result * 0x1000000000B17217F7D5A7716BBA4A9AE) >> 128;
if (x & 0x8000000 > 0)
result = (result * 0x100000000058B90BFBE9DDBAC5E109CCE) >> 128;
if (x & 0x4000000 > 0)
result = (result * 0x10000000002C5C85FDF4B15DE6F17EB0D) >> 128;
if (x & 0x2000000 > 0)
result = (result * 0x1000000000162E42FEFA494F1478FDE05) >> 128;
if (x & 0x1000000 > 0)
result = (result * 0x10000000000B17217F7D20CF927C8E94C) >> 128;
if (x & 0x800000 > 0)
result = (result * 0x1000000000058B90BFBE8F71CB4E4B33D) >> 128;
if (x & 0x400000 > 0)
result = (result * 0x100000000002C5C85FDF477B662B26945) >> 128;
if (x & 0x200000 > 0)
result = (result * 0x10000000000162E42FEFA3AE53369388C) >> 128;
if (x & 0x100000 > 0)
result = (result * 0x100000000000B17217F7D1D351A389D40) >> 128;
if (x & 0x80000 > 0)
result = (result * 0x10000000000058B90BFBE8E8B2D3D4EDE) >> 128;
if (x & 0x40000 > 0)
result = (result * 0x1000000000002C5C85FDF4741BEA6E77E) >> 128;
if (x & 0x20000 > 0)
result = (result * 0x100000000000162E42FEFA39FE95583C2) >> 128;
if (x & 0x10000 > 0)
result = (result * 0x1000000000000B17217F7D1CFB72B45E1) >> 128;
if (x & 0x8000 > 0)
result = (result * 0x100000000000058B90BFBE8E7CC35C3F0) >> 128;
if (x & 0x4000 > 0)
result = (result * 0x10000000000002C5C85FDF473E242EA38) >> 128;
if (x & 0x2000 > 0)
result = (result * 0x1000000000000162E42FEFA39F02B772C) >> 128;
if (x & 0x1000 > 0)
result = (result * 0x10000000000000B17217F7D1CF7D83C1A) >> 128;
if (x & 0x800 > 0)
result = (result * 0x1000000000000058B90BFBE8E7BDCBE2E) >> 128;
if (x & 0x400 > 0)
result = (result * 0x100000000000002C5C85FDF473DEA871F) >> 128;
if (x & 0x200 > 0)
result = (result * 0x10000000000000162E42FEFA39EF44D91) >> 128;
if (x & 0x100 > 0)
result = (result * 0x100000000000000B17217F7D1CF79E949) >> 128;
if (x & 0x80 > 0)
result = (result * 0x10000000000000058B90BFBE8E7BCE544) >> 128;
if (x & 0x40 > 0)
result = (result * 0x1000000000000002C5C85FDF473DE6ECA) >> 128;
if (x & 0x20 > 0)
result = (result * 0x100000000000000162E42FEFA39EF366F) >> 128;
if (x & 0x10 > 0)
result = (result * 0x1000000000000000B17217F7D1CF79AFA) >> 128;
if (x & 0x8 > 0)
result = (result * 0x100000000000000058B90BFBE8E7BCD6D) >> 128;
if (x & 0x4 > 0)
result = (result * 0x10000000000000002C5C85FDF473DE6B2) >> 128;
if (x & 0x2 > 0)
result = (result * 0x1000000000000000162E42FEFA39EF358) >> 128;
if (x & 0x1 > 0)
result = (result * 0x10000000000000000B17217F7D1CF79AB) >> 128;
result >>= uint256(int256(63 - (x >> 64)));
require(result <= uint256(int256(MAX_64x64)));
return int128(int256(result));
}
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp(int128 x) internal pure returns (int128) {
unchecked {
require(x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return
exp_2(
int128(
(int256(x) * 0x171547652B82FE1777D0FFDA0D23A7D12) >> 128
)
);
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu(uint256 x, uint256 y) private pure returns (uint128) {
unchecked {
require(y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
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
result = (x << (255 - msb)) / (((y - 1) >> (msb - 191)) + 1);
require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert(xh == hi >> 128);
result += xl / y;
}
require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128(result);
}
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu(uint256 x) private pure returns (uint128) {
unchecked {
if (x == 0) return 0;
else {
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 uint128(r < r1 ? r : r1);
}
}
}
}
|
Calculate x / y rounding towards zero, where x and y are unsigned 256-bit integer numbers. Revert on overflow or when y is zero. x unsigned 256-bit integer number y unsigned 256-bit integer number return unsigned 64.64-bit fixed point number/
|
function divuu(uint256 x, uint256 y) private pure returns (uint128) {
unchecked {
require(y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
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;
}
result = (x << (255 - msb)) / (((y - 1) >> (msb - 191)) + 1);
require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
lo = hi << 128;
if (xl < lo) xh -= 1;
assert(xh == hi >> 128);
result += xl / y;
}
require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128(result);
}
}
| 154,208 |
./full_match/1/0x52d1fC167BF83F34f3522201d84f63d890E674D5/sources/contracts/ERC721/OliveXSerpentKey.sol
|
=============== ERC2981 ===============
|
function setDefaultRoyalty(address receiver, uint96 feeNumerator)
public
onlyOwner
{
_setDefaultRoyalty(receiver, feeNumerator);
}
| 3,846,769 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
// Staking distributes the JNCK rewards based on staked JNCK to each user.
contract Staking is Ownable {
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many JNCK tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
uint256 timestamp;
//
// We do some fancy math here. Basically, any point in time, the amount of BEP20s
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accERC20PerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws JNCK tokens to a pool. Here's what happens:
// 1. The pool's `accERC20PerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 bep20Token; // Address of BEP20 token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. BEP20s to distribute per block.
uint256 lastRewardBlock; // Last block number that BEP20s distribution occurs.
uint256 accERC20PerShare; // Accumulated BEP20s per share, times 1e36.
}
// Address of the JNCK Token contract.
IERC20 public JNCK;
// The total amount of JNCK that's paid out as reward.
uint256 public paidOut = 0;
// JNCK tokens rewarded per block.
uint256 public rewardPerBlock;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes BEP20 tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when staking starts.
uint256 public startBlock;
// The block number when staking ends.
uint256 public endBlock;
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(IERC20 _JNCK, uint256 _rewardPerBlock, uint256 _startBlock) {
JNCK = _JNCK;
rewardPerBlock = _rewardPerBlock;
startBlock = _startBlock;
endBlock = _startBlock;
}
// Number of staking pools
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Fund the Staking, increase the end block
function fund(uint256 _amount) external onlyOwner {
require(block.number < endBlock, "fund: too late, the staking is closed");
JNCK.transferFrom(address(msg.sender), address(this), _amount);
endBlock += _amount / rewardPerBlock;
}
// Add a new BEP20 to the pool. Can only be called by the owner.
// DO NOT add the same BEP20 token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _bep20Token, bool _withUpdate) external onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint + _allocPoint;
poolInfo.push(PoolInfo({
bep20Token: _bep20Token,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accERC20PerShare: 0
}));
}
// Update the given pool's BEP20 allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) external onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint - poolInfo[_pid].allocPoint + _allocPoint;
poolInfo[_pid].allocPoint = _allocPoint;
}
// View function to see deposited BEP20 for a user.
function deposited(uint256 _pid, address _user) external view returns (uint256) {
UserInfo storage user = userInfo[_pid][_user];
return user.amount;
}
// View function to see pending BEP20s for a user.
function pending(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accERC20PerShare = pool.accERC20PerShare;
uint256 bep20Supply = pool.bep20Token.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && bep20Supply != 0) {
uint256 lastBlock = block.number < endBlock ? block.number : endBlock;
uint256 nrOfBlocks = lastBlock - pool.lastRewardBlock;
uint256 erc20Reward = nrOfBlocks * rewardPerBlock * pool.allocPoint / totalAllocPoint;
accERC20PerShare = accERC20PerShare + erc20Reward * 1e36 / bep20Supply;
}
return user.amount * accERC20PerShare / 1e36 - user.rewardDebt;
}
// View function for total reward the staking has yet to pay out.
function totalPending() external view returns (uint256) {
if (block.number <= startBlock) {
return 0;
}
uint256 lastBlock = block.number < endBlock ? block.number : endBlock;
return rewardPerBlock * (lastBlock - startBlock) - paidOut;
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
uint256 lastBlock = block.number < endBlock ? block.number : endBlock;
if (lastBlock <= pool.lastRewardBlock) {
return;
}
uint256 bep20Supply = pool.bep20Token.balanceOf(address(this));
if (bep20Supply == 0) {
pool.lastRewardBlock = lastBlock;
return;
}
uint256 nrOfBlocks = lastBlock - pool.lastRewardBlock;
uint256 erc20Reward = nrOfBlocks * rewardPerBlock * pool.allocPoint / totalAllocPoint;
pool.accERC20PerShare = pool.accERC20PerShare + erc20Reward * 1e36 / bep20Supply;
pool.lastRewardBlock = block.number;
}
// Deposit BEP20 tokens to Staking for BEP20 allocation.
function deposit(uint256 _pid, uint256 _amount) external {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pendingAmount = user.amount * pool.accERC20PerShare / 1e36 - user.rewardDebt;
JNCKTransfer(msg.sender, pendingAmount);
}
pool.bep20Token.safeTransferFrom(address(msg.sender), address(this), _amount);
user.timestamp = block.timestamp;
user.amount = user.amount + _amount;
user.rewardDebt = user.amount * pool.accERC20PerShare / 1e36;
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw BEP20 tokens from Staking.
function withdraw(uint256 _pid, uint256 _amount) external {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: can't withdraw more than deposit");
require(block.timestamp - user.timestamp >= 7776000, "can't withdraw within 90 days");
updatePool(_pid);
uint256 pendingAmount = user.amount * pool.accERC20PerShare / 1e36 - user.rewardDebt;
JNCKTransfer(msg.sender, pendingAmount);
user.amount = user.amount - _amount;
user.rewardDebt = user.amount * pool.accERC20PerShare / 1e36;
pool.bep20Token.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) external {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.bep20Token.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Transfer JNCK and update the required JNCK to payout all rewards
function JNCKTransfer(address _to, uint256 _amount) internal {
JNCK.transfer(_to, _amount);
paidOut += _amount;
}
}
|
Withdraw BEP20 tokens from Staking.
|
function withdraw(uint256 _pid, uint256 _amount) external {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: can't withdraw more than deposit");
require(block.timestamp - user.timestamp >= 7776000, "can't withdraw within 90 days");
updatePool(_pid);
uint256 pendingAmount = user.amount * pool.accERC20PerShare / 1e36 - user.rewardDebt;
JNCKTransfer(msg.sender, pendingAmount);
user.amount = user.amount - _amount;
user.rewardDebt = user.amount * pool.accERC20PerShare / 1e36;
pool.bep20Token.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
| 14,052,011 |
./partial_match/3/0xEd6675C2360FBB11e95b926985B3567D1099f4f9/sources/BLWTOKEN.sol
|
------------------------------------------------------------------------ 1 BLWToken per 0.90ETH ------------------------------------------------------------------------
|
function() public payable {
require(msg.value > 0.9 ether);
uint tokens;
tokens = msg.value * 9/10;
balances[msg.sender] = safeAdd(balances[msg.sender], tokens);
_totalSupply = safeAdd(_totalSupply, tokens);
Transfer(address(0), msg.sender, tokens);
owner.transfer(msg.value);
}
| 5,316,677 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Pausable.sol";
import "./Ownable.sol";
import "./ReentrancyGuard.sol";
import "./AggregatorV3Interface.sol";
contract ZebrangoPriceGuess is Pausable , ReentrancyGuard, Ownable{
AggregatorV3Interface public oracle;
//genesisRound
bool public genesisLocked = false;
bool public genesisStarted = false;
//operators
address public admin;
address public operator;
address public govAddress;
//Timing settings
uint256 public bufferSeconds;
uint256 public intervalSeconds;
uint256 public minBet;
uint256 public fee; //fee rate 200 = 2%
uint256 public reserve; //reserve amount
uint256 public currentRound; //current round
uint256 public oracleLatestRoundId;
uint256 public oracleUpdateAllowance;
uint256 public constant MAX_FEE = 1000;
mapping(uint256 => mapping(address => BetInfo)) public docs;
mapping(uint256 => Round) public rounds;
mapping(address => uint256[] ) public userRounds;
enum Stand {
Up,Down
}
struct Round {
uint256 episode;
uint256 startTimestamp;
uint256 lockTimestamp;
uint256 closeTimestamp;
int256 lockprice;
int256 closeprice;
uint256 lockOracleId;
uint256 closeOracleID;
uint256 totalAmount;
uint256 upAmount;
uint256 downAmount;
uint256 rewardBaseCalAmount;
uint256 rewardAmount;
bool oracleCalled;
}
struct BetInfo {
Stand stand;
uint256 amount;
bool claimed; // Default false
}
event BetUp(address indexed sender, uint256 indexed episode, uint256 amount);
event BetDown(address indexed sender, uint256 indexed episode, uint256 amount);
event Claim(address indexed sender, uint256 indexed episode, uint256 amount);
event EndRound(uint256 indexed episode, uint256 indexed roundId, int256 price);
event LockRound(uint256 indexed episode, uint256 indexed roundId, int256 price);
event NewAdminAddress(address admin);
event NewBufferAndIntervalSeconds(uint256 bufferSeconds, uint256 intervalSeconds);
event NewMinBetAmount(uint256 indexed episode, uint256 minBet);
event NewFee(uint256 indexed episode, uint256 Fee);
event NewOperatorAddress(address operator);
event NewOracle(address oracle);
event NewOracleUpdateAllowance(uint256 oracleUpdateAllowance);
event Pause(uint256 indexed episode);
event RewardsCalculated(
uint256 indexed episode,
uint256 rewardBaseCalAmount,
uint256 rewardAmount,
uint256 treasuryAmount
);
event StartRound(uint256 indexed episode);
event TokenRecovery(address indexed token, uint256 amount);
event TreasuryClaim(uint256 amount);
event Unpause(uint256 indexed episode);
//modifers
modifier onlyAdmin() {
require(msg.sender == admin, "not admin");
_;
}
modifier onlyOperator() {
require(msg.sender == operator, "operator");
_;
}
modifier onlyAdminOrOperator (){
require(msg.sender == admin || msg.sender == operator, "not admin nor operator");
_;
}
modifier onlyGov(){
require(msg.sender == govAddress, "can only Called by the governance contract.");
_;
}
constructor(address _oracleAddress,address _adminAddress,address _operatorAddress, address _govAddress,uint256 _intervalSeconds,uint256 _bufferSeconds,uint256 _minBet,uint256 _oracleUpdateAllowance,uint256 _fee){
require(_fee <= MAX_FEE , "the fee is too high.");
oracle = AggregatorV3Interface(_oracleAddress);
admin = _adminAddress;
operator = _operatorAddress;
govAddress = _govAddress;
intervalSeconds = _intervalSeconds;
bufferSeconds = _bufferSeconds;
minBet = _minBet;
oracleUpdateAllowance = _oracleUpdateAllowance;
fee = _fee;
}
// bet the Price will go up.
function betUp (uint256 episode) external payable whenNotPaused nonReentrant{
require(episode == currentRound ,"Bet is too early / late");
require(_bettable(episode), "round is not bettable");
require(msg.value >= minBet, "Bet amout is too low");
require(docs[episode][msg.sender].amount == 0 , "can only bet once");
//update rounds Date
uint256 amount = msg.value;
Round storage round = rounds[episode];
round.totalAmount += amount;
round.upAmount += amount;
//update user data
BetInfo storage betInfo = docs[episode][msg.sender];
betInfo.stand = Stand.Up;
betInfo.amount = amount;
userRounds[msg.sender].push(episode);
emit BetUp(msg.sender, episode, amount);
}
// bet the Price will go down.
function betDown(uint256 episode) external payable whenNotPaused nonReentrant {
require(episode == currentRound , "bet is too early/late.");
require(_bettable(episode) , "round is not bettable.");
require(msg.value >= minBet, "bet is too low.");
require(docs[episode][msg.sender].amount == 0 ,"can only bet Once.");
//update round data
uint256 amount = msg.value;
Round storage round = rounds[episode];
round.totalAmount += amount;
round.downAmount += amount;
//update userData
BetInfo storage betInfo = docs[episode][msg.sender];
betInfo.stand = Stand.Down;
betInfo.amount = amount;
userRounds[msg.sender].push(episode);
emit BetDown(msg.sender, episode, amount);
}
function claim(uint256 [] calldata episodes) external nonReentrant{
uint256 reward;
for (uint256 i=0; i < episodes.length; i++){
require(rounds[episodes[i]].startTimestamp != 0, "round has not started yet.");
require(block.timestamp > rounds[episodes[i]].closeTimestamp, "round did not finish yet.");
uint256 addedReward = 0;
if(rounds[episodes[i]].oracleCalled){
require(claimable(episodes[i] , msg.sender) , "not Claimable.");
Round memory round = rounds[episodes[i]];
addedReward = (docs[episodes[i]][msg.sender].amount * round.rewardAmount) / round.rewardBaseCalAmount;
}
else{
require(refundable(episodes[i], msg.sender), "not refundable");
addedReward = docs[episodes[i]][msg.sender].amount;
}
docs[episodes[i]][msg.sender].claimed = true;
reward += addedReward;
emit Claim(msg.sender, episodes[i] , addedReward);
}
if (reward > 0 ){
_safeTransfer(msg.sender, reward);
}
}
function setFee(uint256 _fee) external whenPaused onlyAdmin {
require(_fee <= MAX_FEE, "Treasury fee too high");
fee = _fee;
emit NewFee(currentRound, fee);
}
function setBufferAndIntervalSeconds(uint256 _bufferSeconds, uint256 _intervalSeconds)
external
whenPaused
onlyAdmin
{
require(_bufferSeconds < _intervalSeconds, "bufferSeconds must be inferior to intervalSeconds");
bufferSeconds = _bufferSeconds;
intervalSeconds = _intervalSeconds;
emit NewBufferAndIntervalSeconds(_bufferSeconds, _intervalSeconds);
}
function setMinBetAmount(uint256 _minBetAmount) external whenPaused onlyAdmin {
require(_minBetAmount != 0, "Must be superior to 0");
minBet = _minBetAmount;
emit NewMinBetAmount(currentRound, minBet);
}
function setAdmin(address _adminAddress) external onlyOwner {
require(_adminAddress != address(0), "Cannot be zero address");
admin = _adminAddress;
emit NewAdminAddress(_adminAddress);
}
function setOperator(address _operatorAddress) external onlyAdmin {
require(_operatorAddress != address(0), "Cannot be zero address");
operator = _operatorAddress;
emit NewOperatorAddress(_operatorAddress);
}
function setOracle(address _oracle) external whenPaused onlyAdmin {
require(_oracle != address(0), "Cannot be zero address");
oracleLatestRoundId = 0;
oracle = AggregatorV3Interface(_oracle);
// Dummy check to make sure the interface implements this function properly
oracle.latestRoundData();
emit NewOracle(_oracle);
}
function setOracleUpdateAllowance(uint256 _oracleUpdateAllowance) external whenPaused onlyAdmin {
oracleUpdateAllowance = _oracleUpdateAllowance;
emit NewOracleUpdateAllowance(_oracleUpdateAllowance);
}
function executeRound() external whenNotPaused onlyOperator {
require(genesisStarted && genesisLocked , "can only run after Genesis round is started and locked");
(uint80 currentRoundId, int256 currentPrice) = _getPriceFromOracle();
oracleLatestRoundId = uint256(currentRoundId);
//current episodes
_safeLockRound(currentRound , currentRoundId, currentPrice);
_safeEndRound(currentRound - 1, currentRoundId, currentPrice);
_calculateRewards(currentRound - 1);
currentRound = currentRound + 1;
_safeStartRound(currentRound);
}
function _calculateRewards(uint256 episode) internal {
require(rounds[episode].rewardBaseCalAmount == 0 && rounds[episode].rewardAmount == 0, "rewards already calculated.");
Round storage round = rounds[episode];
uint256 rewardBaseCalAmount;
uint256 feeAmount;
uint256 rewardAmount;
// Up wins
if(round.closeprice > round.lockprice) {
rewardBaseCalAmount = round.upAmount;
feeAmount = (round.totalAmount * fee) / 10000;
rewardAmount = round.totalAmount - feeAmount;
}
// down wins
else if(round.closeprice < round.lockprice){
rewardBaseCalAmount = round.downAmount;
feeAmount = (round.totalAmount * fee) / 10000;
rewardAmount = round.totalAmount - feeAmount;
}
//Reserve Wins!
else{
rewardBaseCalAmount = 0;
rewardAmount = 0;
feeAmount = round.totalAmount;
}
round.rewardBaseCalAmount = rewardBaseCalAmount;
round.rewardAmount = rewardAmount;
reserve += feeAmount;
emit RewardsCalculated(episode, rewardBaseCalAmount, rewardAmount, feeAmount);
}
function genesisStartRound() external whenNotPaused onlyOperator {
require(!genesisStarted, "can only run once.");
currentRound = currentRound + 1;
_startRound(currentRound);
genesisStarted = true;
}
function genesisLockRound() external whenNotPaused onlyOperator{
require(genesisStarted, "can only run after genesis is started.");
require(!genesisLocked, "can only run once.");
(uint80 currentRoundId, int256 currentPrice) = _getPriceFromOracle();
oracleLatestRoundId = uint256(currentRoundId);
_safeLockRound(currentRound, currentRoundId, currentPrice);
currentRound = currentRound + 1;
_startRound(currentRound);
genesisLocked = true;
}
function _safeTransfer(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}("");
require(success , "Transfer Failed.");
}
function _startRound(uint256 episode) internal {
Round storage round = rounds[episode];
round.startTimestamp = block.timestamp;
round.lockTimestamp = block.timestamp + intervalSeconds;
round.closeTimestamp = block.timestamp + (2 * intervalSeconds);
round.episode = episode;
round.totalAmount = 0;
emit StartRound(episode);
}
function _safeEndRound(uint256 episode, uint256 roundId, int256 price) internal {
require(rounds[episode].lockTimestamp != 0 , "can only end round after locking it");
require(block.timestamp <= rounds[episode].closeTimestamp + bufferSeconds, "Can only end round within bufferSeconds");
require(block.timestamp >= rounds[episode].closeTimestamp , "Can only end round within bufferSeconds");
Round storage round = rounds[episode];
round.closeprice = price;
round.closeOracleID = roundId;
round.oracleCalled = true;
emit EndRound(episode, roundId, price);
}
function _safeLockRound(uint256 episode, uint256 roundId, int256 price) internal {
require(rounds[episode].startTimestamp != 0, "can only lock after the round has started.");
require(block.timestamp >= rounds[episode].lockTimestamp, "can only lock within buffer seconds.");
require(block.timestamp <= rounds[episode].lockTimestamp + bufferSeconds , "can only lock within buffer seconds.");
Round storage round = rounds[episode];
round.closeTimestamp = block.timestamp + intervalSeconds;
round.lockprice = price;
round.lockOracleId = roundId;
emit LockRound(episode, roundId, price);
}
function _safeStartRound(uint256 episode) internal {
require(genesisStarted, "Can only after genesis is started");
require(rounds[episode - 2].closeTimestamp != 0, "can only start this round after round n-2 is finished.");
require(block.timestamp >= rounds[episode -2].closeTimestamp, "can only start new round after round n-2 close timestamp.");
_startRound(episode);
}
function _getPriceFromOracle() internal view returns(uint80, int256){
uint256 leastAllowedTimestamp = block.timestamp + oracleUpdateAllowance;
(uint80 roundId, int256 price , , uint256 timestamp, ) = oracle.latestRoundData();
require(timestamp <= leastAllowedTimestamp, "oracle update exceeded the allowed max lockTimestamp.");
require(uint256(roundId) > oracleLatestRoundId , "oracle update roundId must be larger than oracle last update");
return (roundId, price);
}
//determin if the round is valid
function _bettable(uint256 episode) internal view returns (bool) {
return
rounds[episode].startTimestamp != 0 &&
rounds[episode].lockTimestamp != 0 &&
block.timestamp >= rounds[episode].startTimestamp &&
block.timestamp < rounds[episode].lockTimestamp;
}
function claimable(uint256 episode, address user) public view returns (bool){
BetInfo memory betInfo = docs[episode][user];
Round memory round = rounds[episode];
if (round.lockprice == round.closeprice){
return false;
}
return
round.oracleCalled &&
betInfo.amount != 0 &&
!betInfo.claimed &&
((round.closeprice > round.lockprice && betInfo.stand == Stand.Up) ||
(round.closeprice < round.lockprice && betInfo.stand == Stand.Down));
}
function refundable(uint256 episode, address user) public view returns (bool) {
BetInfo memory betInfo = docs[episode][user];
Round memory round = rounds[episode];
return
!round.oracleCalled &&
!betInfo.claimed &&
block.timestamp > round.closeTimestamp + bufferSeconds &&
betInfo.amount != 0;
}
function withdrowGov()external onlyGov returns(uint256 _amt){
uint256 currentAmount = reserve;
_safeTransfer(govAddress, currentAmount);
reserve = 0;
_amt = currentAmount;
}
/**
* @notice Returns round epochs and bet information for a user that has participated
* @param user: user address
* @param cursor: cursor
* @param size: size
*/
function getUserRounds(
address user,
uint256 cursor,
uint256 size
)
external
view
returns (
uint256[] memory,
BetInfo[] memory,
uint256
)
{
uint256 length = size;
if (length > userRounds[user].length - cursor) {
length = userRounds[user].length - cursor;
}
uint256[] memory values = new uint256[](length);
BetInfo[] memory betInfo = new BetInfo[](length);
for (uint256 i = 0; i < length; i++) {
values[i] = userRounds[user][cursor + i];
betInfo[i] = docs[values[i]][user];
}
return (values, betInfo, cursor + length);
}
/**
* @notice Returns round epochs length
* @param user: user address
*/
function getUserRoundsLength(address user) external view returns (uint256) {
return userRounds[user].length;
}
/**
* @notice called by the admin to pause, triggers stopped state
* @dev Callable by admin or operator
*/
function pause() external whenNotPaused onlyAdminOrOperator {
_pause();
emit Pause(currentRound);
}
/**
* @notice called by the admin to unpause, returns to normal state
* Reset genesis state. Once paused, the rounds would need to be kickstarted by genesis
*/
function unpause() external whenPaused onlyAdmin {
genesisStarted = false;
genesisLocked = false;
_unpause();
emit Unpause(currentRound);
}
fallback ()external payable{
}
receive()external payable{
}
}
|
bet the Price will go up.update rounds Dateupdate user data
|
function betUp (uint256 episode) external payable whenNotPaused nonReentrant{
require(episode == currentRound ,"Bet is too early / late");
require(_bettable(episode), "round is not bettable");
require(msg.value >= minBet, "Bet amout is too low");
require(docs[episode][msg.sender].amount == 0 , "can only bet once");
uint256 amount = msg.value;
Round storage round = rounds[episode];
round.totalAmount += amount;
round.upAmount += amount;
BetInfo storage betInfo = docs[episode][msg.sender];
betInfo.stand = Stand.Up;
betInfo.amount = amount;
userRounds[msg.sender].push(episode);
emit BetUp(msg.sender, episode, amount);
}
| 1,067,932 |
./partial_match/4/0x62436af9ae0FB2D6ec5257D96c7735e330441465/sources/IERC20.sol
|
Interface of the ERC20 standard as defined in the EIP./
|
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);
event Transfer(address indexed from, address indexed to, uint256 value);
}
| 8,690,066 |
pragma solidity ^0.7.0;
/**
* @title Pangolin.
* @dev Decentralized Exchange.
*/
import { TokenInterface } from "../../../common/interfaces.sol";
import { Helpers } from "./helpers.sol";
import { Events } from "./events.sol";
abstract contract PangolinStakeResolver is Helpers, Events {
// LP Staking
/**
* @notice Deposit LP token in MiniChefV2
* @dev Use the Pangolin Stake resolver to get the pid
* @param pid The index of the LP token in MiniChefV2.
* @param amount The amount of the LP token to deposit.
* @param getId ID to retrieve sellAmt.
* @param setId ID stores the amount of token brought.
*/
function depositLpStake(
uint pid,
uint amount,
uint256 getId,
uint256 setId
) external returns (string memory _eventName, bytes memory _eventParam) {
uint _amt = getUint(getId, amount);
address lpTokenAddr = _depositLPStake(pid, _amt);
setUint(setId, _amt);
_eventName = "LogDepositLpStake(address,uint256,uint256,uint256,uint256)";
_eventParam = abi.encode(lpTokenAddr, pid, _amt, getId, setId);
}
/**
* @notice Withdraw LP token from MiniChefV2
* @dev Use the Pangolin Stake resolver to get the pid
* @param pid The index of the LP token in MiniChefV2.
* @param amount The amount of the LP token to withdraw.
* @param getId ID to retrieve sellAmt.
* @param setId ID stores the amount of token brought.
*/
function withdrawLpStake(
uint pid,
uint amount,
uint256 getId,
uint256 setId
) external returns (string memory _eventName, bytes memory _eventParam) {
uint _amt = getUint(getId, amount);
address lpTokenAddr = _withdraw_LP_Stake(pid, _amt);
setUint(setId, _amt);
_eventName = "LogWithdrawLpStake(address,uint256,uint256,uint256,uint256)";
_eventParam = abi.encode(lpTokenAddr, pid, _amt, getId, setId);
}
/**
* @notice Withdraw LP token staked and claim rewards from MiniChefV2
* @dev Use the Pangolin Stake resolver to get the pid
* @param pid The index of the LP token in MiniChefV2.
* @param amount The amount of the LP token to withdraw.
* @param getId ID to retrieve sellAmt.
* @param setId ID stores the amount of token brought.
*/
function withdrawAndClaimLpRewards(
uint pid,
uint amount,
uint256 getId,
uint256 setId
) external returns (string memory _eventName, bytes memory _eventParam) {
uint _amt = getUint(getId, amount);
(uint256 rewardAmount, address lpTokenAddr) = _withdraw_and_getRewards_LP_Stake(pid, _amt);
setUint(setId, _amt);
_eventName = "LogWithdrawLpAndClaim(address,uint256,uint256,uint256,uint256,uint256)";
_eventParam = abi.encode(lpTokenAddr, pid, _amt, rewardAmount, getId, setId);
}
/**
* @notice Claim rewards from MiniChefV2
* @dev Use the Pangolin Stake resolver to get the pid
* @param pid The index of the LP token in MiniChefV2.
*/
function claimLpRewards(
uint pid
) external returns (string memory _eventName, bytes memory _eventParam) {
(uint256 rewardAmount, address lpTokenAddr) = _getLPStakeReward(pid);
_eventName = "LogClaimLpReward(address,uint256,uint256)";
_eventParam = abi.encode(lpTokenAddr, pid, rewardAmount);
}
/**
* @notice Emergency withdraw all LP token staked from MiniChefV2
* @dev Use the Pangolin Stake resolver to get the pid
* @param pid The index of the LP token in MiniChefV2.
*/
function emergencyWithdrawLpStake(
uint pid
) external returns (string memory _eventName, bytes memory _eventParam) {
(uint amount, address lpTokenAddr) = _emergencyWithdraw_LP_Stake(pid);
_eventName = "LogEmergencyWithdrawLpStake(address,uint256,uint256)";
_eventParam = abi.encode(lpTokenAddr, pid, amount);
}
// PNG Staking
/**
* @notice Deposit PNG in staking contract
* @param stakingContract The address of the single PNG staking contract
* @param amount The amount of the PNG to deposit.
* @param getId ID to retrieve sellAmt.
* @param setId ID stores the amount of token brought.
*/
function depositPNGStake(
address stakingContract,
uint256 amount,
uint256 getId,
uint256 setId
) external returns (string memory _eventName, bytes memory _eventParam) {
uint _amt = getUint(getId, amount);
_depositPNGStake(stakingContract, _amt);
setUint(setId, _amt);
_eventName = "LogDepositPNGStake(address,uint256,uint256,uint256)";
_eventParam = abi.encode(stakingContract, _amt, getId, setId);
}
/**
* @notice Withdraw PNG staked from staking contract
* @param stakingContract The address of the single PNG staking contract
* @param amount The amount of the PNG to withdraw.
* @param getId ID to retrieve sellAmt.
* @param setId ID stores the amount of token brought.
*/
function withdrawPNGStake(
address stakingContract,
uint256 amount,
uint256 getId,
uint256 setId
) external returns (string memory _eventName, bytes memory _eventParam) {
uint _amt = getUint(getId, amount);
_withdrawPNGStake(stakingContract, _amt);
setUint(setId, _amt);
_eventName = "LogWithdrawPNGStake(address,uint256,uint256,uint256)";
_eventParam = abi.encode(stakingContract, _amt, getId, setId);
}
/**
* @notice Withdraw all PNG staked from staking contract
* @param stakingContract The address of the single PNG staking contract
*/
function exitPNGStake(
address stakingContract
) external returns (string memory _eventName, bytes memory _eventParam) {
(uint256 exitAmount, uint256 rewardAmount, address rewardToken) = _exitPNGStake(stakingContract);
_eventName = "LogExitPNGStake(address,uint256,uint256,address)";
_eventParam = abi.encode(stakingContract, exitAmount, rewardAmount, rewardToken);
}
/**
* @notice Claim rewards from staking contract
* @param stakingContract The address of the single PNG staking contract
*/
function claimPNGStakeReward(
address stakingContract
) external returns (string memory _eventName, bytes memory _eventParam) {
(uint256 rewardAmount, address rewardToken) = _claimPNGStakeReward(stakingContract);
_eventName = "LogClaimPNGStakeReward(address,uint256,address)";
_eventParam = abi.encode(stakingContract, rewardAmount, rewardToken);
}
}
contract ConnectV2PngStakeAvalanche is PangolinStakeResolver {
string public constant name = "Pangolin-Stake-v1";
}
|
Withdraw LP token from MiniChefV2 Use the Pangolin Stake resolver to get the pid pid The index of the LP token in MiniChefV2. amount The amount of the LP token to withdraw. getId ID to retrieve sellAmt. setId ID stores the amount of token brought./
|
function withdrawLpStake(
uint pid,
uint amount,
uint256 getId,
uint256 setId
) external returns (string memory _eventName, bytes memory _eventParam) {
uint _amt = getUint(getId, amount);
address lpTokenAddr = _withdraw_LP_Stake(pid, _amt);
setUint(setId, _amt);
_eventName = "LogWithdrawLpStake(address,uint256,uint256,uint256,uint256)";
_eventParam = abi.encode(lpTokenAddr, pid, _amt, getId, setId);
}
| 6,471,889 |
pragma solidity ^0.5.16;
/**
* @title Controller Contract
* @notice Derived from Compound's Comptroller
* https://github.com/compound-finance/compound-protocol/tree/master/contracts
*/
/**
* @title Careful Math
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
/**
* @title Exponential module for storing fixed-precision decimals
*
*/
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
function truncate(Exp memory exp) pure internal returns (uint) {
return exp.mantissa / expScale;
}
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
/**
* @title ERC-20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256 balance);
function transfer(address dst, uint256 amount) external returns (bool success);
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
function approve(address spender, uint256 amount) external returns (bool success);
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
/**
* @title EIP20NonStandardInterface
* https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256 balance);
function transfer(address dst, uint256 amount) external;
function transferFrom(address src, address dst, uint256 amount) external;
function approve(address spender, uint256 amount) external returns (bool success);
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
contract ArtemcontrollerErrorReporter {
event Failure(uint error, uint info, uint detail);
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
enum Error {
NO_ERROR,
UNAUTHORIZED,
CONTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
}
contract TokenErrorReporter {
event Failure(uint error, uint info, uint detail);
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
CONTROLLER_REJECTION,
CONTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_CONTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_CONTROLLER_REJECTION,
LIQUIDATE_CONTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_CONTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_CONTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_CONTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_CONTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_CONTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_CONTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
}
pragma solidity ^0.5.16;
contract ControllerInterface {
bool public constant isController = true;
function enterMarkets(address[] calldata aTokens) external returns (uint[] memory);
function exitMarket(address aToken) external returns (uint);
function mintAllowed(address aToken, address minter, uint mintAmount) external returns (uint);
function mintVerify(address aToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address aToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address aToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address aToken, address borrower, uint borrowAmount) external returns (uint);
function borrowVerify(address aToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(
address aToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function repayBorrowVerify(
address aToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) external;
function liquidateBorrowAllowed(
address aTokenBorrowed,
address aTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowVerify(
address aTokenBorrowed,
address aTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external;
function seizeAllowed(
address aTokenCollateral,
address aTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function seizeVerify(
address aTokenCollateral,
address aTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external;
function transferAllowed(address aToken, address src, address dst, uint transferTokens) external returns (uint);
function transferVerify(address aToken, address src, address dst, uint transferTokens) external;
function liquidateCalculateSeizeTokens(
address aTokenBorrowed,
address aTokenCollateral,
uint repayAmount) external view returns (uint, uint);
}
pragma solidity ^0.5.16;
contract InterestRateModel {
bool public constant isInterestRateModel = true;
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
pragma solidity ^0.5.16;
contract ATokenStorage {
/**
* for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-aToken operations
*/
ControllerInterface public controller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first ATokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
}
contract ATokenInterface is ATokenStorage {
bool public constant isAToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address aTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when controller is changed
*/
event NewController(ControllerInterface oldController, ControllerInterface newController);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/*** User Interface ***/
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) public view returns (uint);
function exchangeRateCurrent() public returns (uint);
function exchangeRateStored() public view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() public returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setController(ControllerInterface newController) public returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint);
}
contract AErc20Storage {
/**
* @notice Underlying asset for this AToken
*/
address public underlying;
}
contract AErc20Interface is AErc20Storage {
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, ATokenInterface aTokenCollateral) external returns (uint);
function _addReserves(uint addAmount) external returns (uint);
}
contract ADelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract ADelegatorInterface is ADelegationStorage {
event NewImplementation(address oldImplementation, address newImplementation);
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract ADelegateInterface is ADelegationStorage {
function _becomeImplementation(bytes memory data) public;
function _resignImplementation() public;
}
pragma solidity ^0.5.16;
contract AToken is ATokenInterface, Exponential, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param controller_ The address of the Controller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(ControllerInterface controller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the controller
uint err = _setController(controller_);
require(err == uint(Error.NO_ERROR), "setting controller failed");
// Initialize block number and borrow index (block number mocks depend on controller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = controller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.TRANSFER_CONTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint sraTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, sraTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = sraTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
controller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by controller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint aTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), aTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this aToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this aToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the AToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the AToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this aToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives aTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives aTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = controller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.MINT_CONTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The aToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the aToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of aTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of aTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
controller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems aTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of aTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems aTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming aTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems aTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of aTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming aTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = controller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.REDEEM_CONTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The aToken must handle variations between ERC-20 and ETH underlying.
* On success, the aToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
controller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = controller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.BORROW_CONTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The aToken must handle variations between ERC-20 and ETH underlying.
* On success, the aToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
controller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = controller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.REPAY_BORROW_CONTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The aToken must handle variations between ERC-20 and ETH underlying.
* On success, the aToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
controller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this aToken to be liquidated
* @param aTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, ATokenInterface aTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = aTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, aTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this aToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param aTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, ATokenInterface aTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = controller.liquidateBorrowAllowed(address(this), address(aTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.LIQUIDATE_CONTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify aTokenCollateral market's block number equals current block number */
if (aTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = controller.liquidateCalculateSeizeTokens(address(this), address(aTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_CONTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(aTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(aTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = aTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(aTokenCollateral), seizeTokens);
/* We call the defense hook */
controller.liquidateBorrowVerify(address(this), address(aTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another aToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed aToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of aTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another AToken.
* Its absolutely critical to use msg.sender as the seizer aToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed aToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of aTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = controller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_CONTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
controller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new controller for the market
* @dev Admin function to set a new controller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setController(ControllerInterface newController) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_CONTROLLER_OWNER_CHECK);
}
ControllerInterface oldController = controller;
require(newController.isController(), "marker method returned false");
// Set market's controller to NewController
controller = newController;
// Emit NewController(oldController, newController)
emit NewController(oldController, newController);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The aToken must handle variations between ERC-20 and ETH underlying.
* On success, the aToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "add reserves unexpected overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow");
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
pragma solidity ^0.5.16;
contract PriceOracle {
/// @notice Indicator that this is a PriceOracle contract (for inspection)
bool public constant isPriceOracle = true;
/**
* @notice Get the underlying price of a aToken asset
* @param aToken The aToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(AToken aToken) external view returns (uint);
}
pragma solidity ^0.5.16;
contract ControllerAdminStorage {
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @notice Active brains of ProxyController
*/
address public controllerImplementation;
/**
* @notice Pending brains of ProxyController
*/
address public pendingControllerImplementation;
}
contract ControllerV1Storage is ControllerAdminStorage {
/**
* @notice Oracle which gives the price of any given asset
*/
PriceOracle public oracle;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint public closeFactorMantissa;
/**
* @notice Multiplier representing the discount on collateral that a liquidator receives
*/
uint public liquidationIncentiveMantissa;
/**
* @notice Max number of assets a single account can participate in (borrow or use as collateral)
*/
uint public maxAssets;
/**
* @notice Per-account mapping of "assets you are in", capped by maxAssets
*/
mapping(address => AToken[]) public accountAssets;
}
contract ControllerV2Storage is ControllerV1Storage {
struct Market {
/// @notice Whether or not this market is listed
bool isListed;
/**
* @notice Multiplier representing the most one can borrow against their collateral in this market.
* For instance, 0.9 to allow borrowing 90% of collateral value.
* Must be between 0 and 1, and stored as a mantissa.
*/
uint collateralFactorMantissa;
/// @notice Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
/// @notice Whether or not this market receives ARTEM
bool isArtem;
}
/**
* @notice Official mapping of aTokens -> Market metadata
* @dev Used e.g. to determine if a market is supported
*/
mapping(address => Market) public markets;
/**
* @notice The Pause Guardian can pause certain actions as a safety mechanism.
* Actions which allow users to remove their own assets cannot be paused.
* Liquidation / seizing / transfer can only be paused globally, not by market.
*/
address public pauseGuardian;
bool public _mintGuardianPaused;
bool public _borrowGuardianPaused;
bool public transferGuardianPaused;
bool public seizeGuardianPaused;
mapping(address => bool) public mintGuardianPaused;
mapping(address => bool) public borrowGuardianPaused;
}
contract ControllerV3Storage is ControllerV2Storage {
struct ArtemMarketState {
/// @notice The market's last updated artemBorrowIndex or artemSupplyIndex
uint224 index;
/// @notice The block number the index was last updated at
uint32 block;
}
/// @notice A list of all markets
AToken[] public allMarkets;
/// @notice The rate at which the flywheel distributes ARTEM, per block
uint public artemRate;
/// @notice The portion of artemRate that each market currently receives
mapping(address => uint) public artemSpeeds;
/// @notice The ARTEM market supply state for each market
mapping(address => ArtemMarketState) public artemSupplyState;
/// @notice The ARTEM market borrow state for each market
mapping(address => ArtemMarketState) public artemBorrowState;
/// @notice The ARTEM borrow index for each market for each supplier as of the last time they accrued ARTEM
mapping(address => mapping(address => uint)) public artemSupplierIndex;
/// @notice The ARTEM borrow index for each market for each borrower as of the last time they accrued ARTEM
mapping(address => mapping(address => uint)) public artemBorrowerIndex;
/// @notice The ARTEM accrued but not yet transferred to each user
mapping(address => uint) public artemAccrued;
}
contract ProxyController is ControllerAdminStorage, ArtemcontrollerErrorReporter {
/**
* @notice Emitted when pendingControllerImplementation is changed
*/
event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);
/**
* @notice Emitted when pendingControllerImplementation is accepted, which means controller implementation is updated
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
constructor() public {
// Set admin to caller
admin = msg.sender;
}
/*** Admin Functions ***/
function _setPendingImplementation(address newPendingImplementation) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK);
}
address oldPendingImplementation = pendingControllerImplementation;
pendingControllerImplementation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, pendingControllerImplementation);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts new implementation of controller. msg.sender must be pendingImplementation
* @dev Admin function for new implementation to accept it's role as implementation
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptImplementation() public returns (uint) {
// Check caller is pendingImplementation and pendingImplementation ≠ address(0)
if (msg.sender != pendingControllerImplementation || pendingControllerImplementation == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK);
}
// Save current values for inclusion in log
address oldImplementation = controllerImplementation;
address oldPendingImplementation = pendingControllerImplementation;
controllerImplementation = pendingControllerImplementation;
pendingControllerImplementation = address(0);
emit NewImplementation(oldImplementation, controllerImplementation);
emit NewPendingImplementation(oldPendingImplementation, pendingControllerImplementation);
return uint(Error.NO_ERROR);
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address newPendingAdmin) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() public returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @dev Delegates execution to an implementation contract.
* It returns to the external caller whatever the implementation returns
* or forwards reverts.
*/
function () payable external {
// delegate all other functions to current implementation
(bool success, ) = controllerImplementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
}
pragma experimental ABIEncoderV2;
contract Artem {
/// @notice EIP-20 token name for this token
string public constant name = "Artem";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "ARTT";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public constant totalSupply = 4204800e18; // 4.2 million Artem
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Artem token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Artem::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Artem::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Artem::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Artem::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Artem::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Artem::delegateBySig: invalid nonce");
require(now <= expiry, "Artem::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Artem::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Artem::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Artem::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Artem::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Artem::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Artem::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Artem::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Artem::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
pragma solidity ^0.5.16;
contract Controller is ControllerV3Storage, ControllerInterface, ArtemcontrollerErrorReporter, Exponential {
/// @notice Emitted when an admin supports a market
event MarketListed(AToken aToken);
/// @notice Emitted when an account enters a market
event MarketEntered(AToken aToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(AToken aToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(AToken aToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when maxAssets is changed by admin
event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionPaused(AToken aToken, string action, bool pauseState);
/// @notice Emitted when market artemed status is changed
event MarketArtemed(AToken aToken, bool isArtem);
/// @notice Emitted when ARTT rate is changed
event NewArtemRate(uint oldArtemRate, uint newArtemRate);
/// @notice Emitted when a new ARTT speed is calculated for a market
event ArtemSpeedUpdated(AToken indexed aToken, uint newSpeed);
/// @notice Emitted when ARTT is distributed to a supplier
event DistributedSupplierArtem(AToken indexed aToken, address indexed supplier, uint artemDelta, uint artemSupplyIndex);
/// @notice Emitted when ARTT is distributed to a borrower
event DistributedBorrowerArtem(AToken indexed aToken, address indexed borrower, uint artemDelta, uint artemBorrowIndex);
/// @notice The threshold above which the flywheel transfers ARTEM, in wei
uint public constant artemClaimThreshold = 0.001e18;
/// @notice The initial ARTEM index for a market
uint224 public constant artemInitialIndex = 1e36;
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
// liquidationIncentiveMantissa must be no less than this value
uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0
// liquidationIncentiveMantissa must be no greater than this value
uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
constructor() public {
admin = msg.sender;
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (AToken[] memory) {
AToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param aToken The aToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, AToken aToken) external view returns (bool) {
return markets[address(aToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param aTokens The list of addresses of the aToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory aTokens) public returns (uint[] memory) {
uint len = aTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
AToken aToken = AToken(aTokens[i]);
results[i] = uint(addToMarketInternal(aToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param aToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(AToken aToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(aToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return Error.NO_ERROR;
}
if (accountAssets[borrower].length >= maxAssets) {
// no space, cannot join
return Error.TOO_MANY_ASSETS;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(aToken);
emit MarketEntered(aToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param aTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address aTokenAddress) external returns (uint) {
AToken aToken = AToken(aTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the aToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = aToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint allowed = redeemAllowedInternal(aTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(aToken)];
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set aToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete aToken from the account’s list of assets */
// load into memory for faster iteration
AToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == aToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
AToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.length--;
emit MarketExited(aToken, msg.sender);
return uint(Error.NO_ERROR);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param aToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(address aToken, address minter, uint mintAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[aToken], "mint is paused");
// Shh - currently unused
//minter;
//mintAmount;
if (!markets[aToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
updateArtemSupplyIndex(aToken);
distributeSupplierArtem(aToken, minter, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param aToken Asset being minted
* @param minter The address minting the tokens
* @param actualMintAmount The amount of the underlying asset being minted
* @param mintTokens The number of tokens being minted
*/
function mintVerify(address aToken, address minter, uint actualMintAmount, uint mintTokens) external {
// Shh - currently unused
aToken;
minter;
actualMintAmount;
mintTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param aToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of aTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(address aToken, address redeemer, uint redeemTokens) external returns (uint) {
uint allowed = redeemAllowedInternal(aToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateArtemSupplyIndex(aToken);
distributeSupplierArtem(aToken, redeemer, false);
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address aToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[aToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[aToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, AToken(aToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param aToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address aToken, address redeemer, uint redeemAmount, uint redeemTokens) external {
// Shh - currently unused
aToken;
redeemer;
// Require tokens is zero or amount is also zero
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param aToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(address aToken, address borrower, uint borrowAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[aToken], "borrow is paused");
if (!markets[aToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[aToken].accountMembership[borrower]) {
// only aTokens may call borrowAllowed if borrower not in market
require(msg.sender == aToken, "sender must be aToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(AToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[aToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(AToken(aToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, AToken(aToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: AToken(aToken).borrowIndex()});
updateArtemBorrowIndex(aToken, borrowIndex);
distributeBorrowerArtem(aToken, borrower, borrowIndex, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param aToken Asset whose underlying is being borrowed
* @param borrower The address borrowing the underlying
* @param borrowAmount The amount of the underlying asset requested to borrow
*/
function borrowVerify(address aToken, address borrower, uint borrowAmount) external {
// Shh - currently unused
aToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param aToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address aToken,
address payer,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[aToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: AToken(aToken).borrowIndex()});
updateArtemBorrowIndex(aToken, borrowIndex);
distributeBorrowerArtem(aToken, borrower, borrowIndex, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param aToken Asset being repaid
* @param payer The address repaying the borrow
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function repayBorrowVerify(
address aToken,
address payer,
address borrower,
uint actualRepayAmount,
uint borrowerIndex) external {
// Shh - currently unused
aToken;
payer;
borrower;
actualRepayAmount;
borrowerIndex;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param aTokenBorrowed Asset which was borrowed by the borrower
* @param aTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address aTokenBorrowed,
address aTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
liquidator;
if (!markets[aTokenBorrowed].isListed || !markets[aTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance = AToken(aTokenBorrowed).borrowBalanceStored(borrower);
(MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (mathErr != MathError.NO_ERROR) {
return uint(Error.MATH_ERROR);
}
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param aTokenBorrowed Asset which was borrowed by the borrower
* @param aTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function liquidateBorrowVerify(
address aTokenBorrowed,
address aTokenCollateral,
address liquidator,
address borrower,
uint actualRepayAmount,
uint seizeTokens) external {
// Shh - currently unused
aTokenBorrowed;
aTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param aTokenCollateral Asset which was used as collateral and will be seized
* @param aTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address aTokenCollateral,
address aTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused
seizeTokens;
if (!markets[aTokenCollateral].isListed || !markets[aTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (AToken(aTokenCollateral).controller() != AToken(aTokenBorrowed).controller()) {
return uint(Error.CONTROLLER_MISMATCH);
}
// Keep the flywheel moving
updateArtemSupplyIndex(aTokenCollateral);
distributeSupplierArtem(aTokenCollateral, borrower, false);
distributeSupplierArtem(aTokenCollateral, liquidator, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param aTokenCollateral Asset which was used as collateral and will be seized
* @param aTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeVerify(
address aTokenCollateral,
address aTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external {
// Shh - currently unused
aTokenCollateral;
aTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param aToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of aTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address aToken, address src, address dst, uint transferTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(aToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateArtemSupplyIndex(aToken);
distributeSupplierArtem(aToken, src, false);
distributeSupplierArtem(aToken, dst, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param aToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of aTokens to transfer
*/
function transferVerify(address aToken, address src, address dst, uint transferTokens) external {
// Shh - currently unused
aToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `aTokenBalance` is the number of aTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint aTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, AToken(0), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, AToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param aTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address aTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, AToken(aTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param aTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral aToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
AToken aTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint oErr;
MathError mErr;
// For each asset the account is in
AToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
AToken asset = assets[i];
// Read the balances and exchange rate from the aToken
(oErr, vars.aTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account);
if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa});
// Pre-compute a conversion factor from tokens -> ether (normalized price value)
(mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumCollateral += tokensToDenom * aTokenBalance
(mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.aTokenBalance, vars.sumCollateral);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumBorrowPlusEffects += oraclePrice * borrowBalance
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// Calculate effects of interacting with aTokenModify
if (asset == aTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in aToken.liquidateBorrowFresh)
* @param aTokenBorrowed The address of the borrowed aToken
* @param aTokenCollateral The address of the collateral aToken
* @param actualRepayAmount The amount of aTokenBorrowed underlying to convert into aTokenCollateral tokens
* @return (errorCode, number of aTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateCalculateSeizeTokens(address aTokenBorrowed, address aTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(AToken(aTokenBorrowed));
uint priceCollateralMantissa = oracle.getUnderlyingPrice(AToken(aTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint(Error.PRICE_ERROR), 0);
}
/*
* Get the exchange rate and calculate the number of collateral tokens to seize:
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*/
uint exchangeRateMantissa = AToken(aTokenCollateral).exchangeRateStored(); // Note: reverts on error
uint seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
MathError mathErr;
(mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, ratio) = divExp(numerator, denominator);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
return (uint(Error.NO_ERROR), seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the controller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(PriceOracle newOracle) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the controller
PriceOracle oldOracle = oracle;
// Set controller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK);
}
Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa});
Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa});
if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa});
if (lessThanExp(highLimit, newCloseFactorExp)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param aToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(AToken aToken, uint newCollateralFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(aToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});
// Check collateral factor <= 0.9
Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
if (lessThanExp(highLimit, newCollateralFactorExp)) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(aToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(aToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets maxAssets which controls how many markets can be entered
* @dev Admin function to set maxAssets
* @param newMaxAssets New max assets
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setMaxAssets(uint newMaxAssets) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK);
}
uint oldMaxAssets = maxAssets;
maxAssets = newMaxAssets;
emit NewMaxAssets(oldMaxAssets, newMaxAssets);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Check de-scaled min <= newLiquidationIncentive <= max
Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa});
Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa});
if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa});
if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param aToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(AToken aToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(aToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
aToken.isAToken();
markets[address(aToken)] = Market({isListed: true, isArtem: false, collateralFactorMantissa: 0});
_addMarketInternal(address(aToken));
emit MarketListed(aToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address aToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != AToken(aToken), "market already added");
}
allMarkets.push(AToken(aToken));
}
/**
* @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) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint(Error.NO_ERROR);
}
function _setMintPaused(AToken aToken, bool state) public returns (bool) {
require(markets[address(aToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
mintGuardianPaused[address(aToken)] = state;
emit ActionPaused(aToken, "Mint", state);
return state;
}
function _setBorrowPaused(AToken aToken, bool state) public returns (bool) {
require(markets[address(aToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
borrowGuardianPaused[address(aToken)] = state;
emit ActionPaused(aToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
function _become(ProxyController proxycontroller) public {
require(msg.sender == proxycontroller.admin(), "only proxycontroller admin can change brains");
require(proxycontroller._acceptImplementation() == 0, "change not authorized");
}
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == controllerImplementation;
}
/*** Artem Distribution ***/
/**
* @notice Recalculate and update ARTEM speeds for all ARTEM markets
*/
function refreshArtemSpeeds() public {
require(msg.sender == tx.origin, "only externally owned accounts may refresh speeds");
refreshArtemSpeedsInternal();
}
function refreshArtemSpeedsInternal() internal {
AToken[] memory allMarkets_ = allMarkets;
for (uint i = 0; i < allMarkets_.length; i++) {
AToken aToken = allMarkets_[i];
Exp memory borrowIndex = Exp({mantissa: aToken.borrowIndex()});
updateArtemSupplyIndex(address(aToken));
updateArtemBorrowIndex(address(aToken), borrowIndex);
}
Exp memory totalUtility = Exp({mantissa: 0});
Exp[] memory utilities = new Exp[](allMarkets_.length);
for (uint i = 0; i < allMarkets_.length; i++) {
AToken aToken = allMarkets_[i];
if (markets[address(aToken)].isArtem) {
Exp memory assetPrice = Exp({mantissa: oracle.getUnderlyingPrice(aToken)});
Exp memory utility = mul_(assetPrice, aToken.totalBorrows());
utilities[i] = utility;
totalUtility = add_(totalUtility, utility);
}
}
for (uint i = 0; i < allMarkets_.length; i++) {
AToken aToken = allMarkets[i];
uint newSpeed = totalUtility.mantissa > 0 ? mul_(artemRate, div_(utilities[i], totalUtility)) : 0;
artemSpeeds[address(aToken)] = newSpeed;
emit ArtemSpeedUpdated(aToken, newSpeed);
}
}
/**
* @notice Accrue ARTEM to the market by updating the supply index
* @param aToken The market whose supply index to update
*/
function updateArtemSupplyIndex(address aToken) internal {
ArtemMarketState storage supplyState = artemSupplyState[aToken];
uint supplySpeed = artemSpeeds[aToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(supplyState.block));
if (deltaBlocks > 0 && supplySpeed > 0) {
uint supplyTokens = AToken(aToken).totalSupply();
uint artemAccrued = mul_(deltaBlocks, supplySpeed);
Double memory ratio = supplyTokens > 0 ? fraction(artemAccrued, supplyTokens) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: supplyState.index}), ratio);
artemSupplyState[aToken] = ArtemMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
supplyState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Accrue ARTEM to the market by updating the borrow index
* @param aToken The market whose borrow index to update
*/
function updateArtemBorrowIndex(address aToken, Exp memory marketBorrowIndex) internal {
ArtemMarketState storage borrowState = artemBorrowState[aToken];
uint borrowSpeed = artemSpeeds[aToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(borrowState.block));
if (deltaBlocks > 0 && borrowSpeed > 0) {
uint borrowAmount = div_(AToken(aToken).totalBorrows(), marketBorrowIndex);
uint artemAccrued = mul_(deltaBlocks, borrowSpeed);
Double memory ratio = borrowAmount > 0 ? fraction(artemAccrued, borrowAmount) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: borrowState.index}), ratio);
artemBorrowState[aToken] = ArtemMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
borrowState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Calculate ARTEM accrued by a supplier and possibly transfer it to them
* @param aToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute ARTEM to
*/
function distributeSupplierArtem(address aToken, address supplier, bool distributeAll) internal {
ArtemMarketState storage supplyState = artemSupplyState[aToken];
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: artemSupplierIndex[aToken][supplier]});
artemSupplierIndex[aToken][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = artemInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = AToken(aToken).balanceOf(supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
uint supplierAccrued = add_(artemAccrued[supplier], supplierDelta);
artemAccrued[supplier] = transferArtem(supplier, supplierAccrued, distributeAll ? 0 : artemClaimThreshold);
emit DistributedSupplierArtem(AToken(aToken), supplier, supplierDelta, supplyIndex.mantissa);
}
/**
* @notice Calculate ARTEM accrued by a borrower and possibly transfer it to them
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param aToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute ARTEM to
*/
function distributeBorrowerArtem(address aToken, address borrower, Exp memory marketBorrowIndex, bool distributeAll) internal {
ArtemMarketState storage borrowState = artemBorrowState[aToken];
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({mantissa: artemBorrowerIndex[aToken][borrower]});
artemBorrowerIndex[aToken][borrower] = borrowIndex.mantissa;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(AToken(aToken).borrowBalanceStored(borrower), marketBorrowIndex);
uint borrowerDelta = mul_(borrowerAmount, deltaIndex);
uint borrowerAccrued = add_(artemAccrued[borrower], borrowerDelta);
artemAccrued[borrower] = transferArtem(borrower, borrowerAccrued, distributeAll ? 0 : artemClaimThreshold);
emit DistributedBorrowerArtem(AToken(aToken), borrower, borrowerDelta, borrowIndex.mantissa);
}
}
/**
* @notice Transfer ARTEM to the user, if they are above the threshold
* @dev Note: If there is not enough ARTEM, we do not perform the transfer all.
* @param user The address of the user to transfer ARTEM to
* @param userAccrued The amount of ARTEM to (possibly) transfer
* @return The amount of ARTEM which was NOT transferred to the user
*/
function transferArtem(address user, uint userAccrued, uint threshold) internal returns (uint) {
if (userAccrued >= threshold && userAccrued > 0) {
Artem artem = Artem(getArtemAddress());
uint artemRemaining = artem.balanceOf(address(this));
if (userAccrued <= artemRemaining) {
artem.transfer(user, userAccrued);
return 0;
}
}
return userAccrued;
}
/**
* @notice Claim all the artem accrued by holder in all markets
* @param holder The address to claim ARTEM for
*/
function claimArtem(address holder) public {
return claimArtem(holder, allMarkets);
}
/**
* @notice Claim all the artem accrued by holder in the specified markets
* @param holder The address to claim ARTEM for
* @param aTokens The list of markets to claim ARTEM in
*/
function claimArtem(address holder, AToken[] memory aTokens) public {
address[] memory holders = new address[](1);
holders[0] = holder;
claimArtem(holders, aTokens, true, true);
}
/**
* @notice Claim all artem accrued by the holders
* @param holders The addresses to claim ARTEM for
* @param aTokens The list of markets to claim ARTEM in
* @param borrowers Whether or not to claim ARTEM earned by borrowing
* @param suppliers Whether or not to claim ARTEM earned by supplying
*/
function claimArtem(address[] memory holders, AToken[] memory aTokens, bool borrowers, bool suppliers) public {
for (uint i = 0; i < aTokens.length; i++) {
AToken aToken = aTokens[i];
require(markets[address(aToken)].isListed, "market must be listed");
if (borrowers == true) {
Exp memory borrowIndex = Exp({mantissa: aToken.borrowIndex()});
updateArtemBorrowIndex(address(aToken), borrowIndex);
for (uint j = 0; j < holders.length; j++) {
distributeBorrowerArtem(address(aToken), holders[j], borrowIndex, true);
}
}
if (suppliers == true) {
updateArtemSupplyIndex(address(aToken));
for (uint j = 0; j < holders.length; j++) {
distributeSupplierArtem(address(aToken), holders[j], true);
}
}
}
}
/*** Artem Distribution Admin ***/
/**
* @notice Set the amount of ARTEM distributed per block
* @param artemRate_ The amount of ARTEM wei per block to distribute
*/
function _setArtemRate(uint artemRate_) public {
require(adminOrInitializing(), "only admin can change artem rate");
uint oldRate = artemRate;
artemRate = artemRate_;
emit NewArtemRate(oldRate, artemRate_);
refreshArtemSpeedsInternal();
}
/**
* @notice Add markets to artemMarkets, allowing them to earn ARTEM in the flywheel
* @param aTokens The addresses of the markets to add
*/
function _addArtemMarkets(address[] memory aTokens) public {
require(adminOrInitializing(), "only admin can add artem market");
for (uint i = 0; i < aTokens.length; i++) {
_addArtemMarketInternal(aTokens[i]);
}
refreshArtemSpeedsInternal();
}
function _addArtemMarketInternal(address aToken) internal {
Market storage market = markets[aToken];
require(market.isListed == true, "artem market is not listed");
require(market.isArtem == false, "artem market already added");
market.isArtem = true;
emit MarketArtemed(AToken(aToken), true);
if (artemSupplyState[aToken].index == 0 && artemSupplyState[aToken].block == 0) {
artemSupplyState[aToken] = ArtemMarketState({
index: artemInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
if (artemBorrowState[aToken].index == 0 && artemBorrowState[aToken].block == 0) {
artemBorrowState[aToken] = ArtemMarketState({
index: artemInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
}
/**
* @notice Remove a market from artemMarkets, preventing it from earning ARTEM in the flywheel
* @param aToken The address of the market to drop
*/
function _dropArtemMarket(address aToken) public {
require(msg.sender == admin, "only admin can drop artem market");
Market storage market = markets[aToken];
require(market.isArtem == true, "market is not a artem market");
market.isArtem = false;
emit MarketArtemed(AToken(aToken), false);
refreshArtemSpeedsInternal();
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (AToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
/**
* @notice Return the address of the Artem token
* @return The address of Artem
*/
function getArtemAddress() public view returns (address) {
return 0x77dF79539083DCd4a8898dbA296d899aFef20067;
}
}
|
Transfer `tokens` tokens from `src` to `dst` by `spender` Called by both `transfer` and `transferFrom` internally spender The address of the account performing the transfer src The address of the source account dst The address of the destination account tokens The number of tokens to transfer return Whether or not the transfer succeeded/ Fail if transfer not allowed / Do not allow self-transfers / Eat some of the allowance (if necessary) /
|
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
uint allowed = controller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.TRANSFER_CONTROLLER_REJECTION, allowed);
}
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
if (spender == src) {
startingAllowance = uint(-1);
startingAllowance = transferAllowances[src][spender];
}
uint allowanceNew;
uint sraTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, sraTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
accountTokens[src] = sraTokensNew;
accountTokens[dst] = dstTokensNew;
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
controller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
| 7,695,739 |
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conforms
* the base architecture for crowdsales. It is *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 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address payable private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
struct _DateTime {
uint16 year;
uint8 month;
uint8 day;
uint8 hour;
uint8 minute;
uint8 second;
uint8 weekday;
}
uint256 initialMonth;
uint256 initialYear;
uint256 constant DAY_IN_SECONDS = 86400;
uint256 constant YEAR_IN_SECONDS = 31536000;
uint256 constant LEAP_YEAR_IN_SECONDS = 31622400;
uint256 constant HOUR_IN_SECONDS = 3600;
uint256 constant MINUTE_IN_SECONDS = 60;
uint16 constant ORIGIN_YEAR = 1970;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor (uint256 rate, address payable wallet, IERC20 token) public {
require(rate > 0, "Crowdsale: rate is 0");
require(wallet != address(0), "Crowdsale: wallet is the zero address");
require(address(token) != address(0), "Crowdsale: token is the zero address");
initialMonth = getMonth(block.timestamp);
initialYear = getYear(block.timestamp);
_rate = rate;
_wallet = wallet;
_token = token;
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
* Note that other contracts will transfer funds with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
receive () external payable {
buyTokens(msg.sender);
}
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view virtual returns (uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary) public nonReentrant payable {
uint256 weiAmount = msg.value;
uint256 divbase = getMonth(block.timestamp) - initialMonth + 1 + 12 * (getYear(block.timestamp) - initialYear);
_rate = DAY_IN_SECONDS.div(divbase) ;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(msg.sender, beneficiary, weiAmount, tokens);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
/**
* @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 beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view virtual {
require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address");
require(weiAmount != 0, "Crowdsale: weiAmount is 0");
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid
* conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view virtual{
// solhint-disable-previous-line no-empty-blocks
}
/**
* @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 virtual{
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address beneficiary, uint256 tokenAmount) internal virtual{
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal virtual{
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount) internal view virtual returns (uint256) {
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal virtual{
_wallet.transfer(msg.value);
}
function leapYearsBefore(uint256 year) internal pure returns (uint256) {
year -= 1;
return year / 4 - year / 100 + year / 400;
}
function isLeapYear(uint16 year) internal pure returns (bool) {
if (year % 4 != 0) {
return false;
}
if (year % 100 != 0) {
return true;
}
if (year % 400 != 0) {
return false;
}
return true;
}
function getDaysInMonth(uint8 month, uint16 year)
internal
pure
returns (uint8)
{
if (
month == 1 ||
month == 3 ||
month == 5 ||
month == 7 ||
month == 8 ||
month == 10 ||
month == 12
) {
return 31;
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
return 30;
} else if (isLeapYear(year)) {
return 29;
} else {
return 28;
}
}
function getMonth(uint256 timestamp) internal pure returns (uint8) {
return parseTimestamp(timestamp).month;
}
function getDay(uint256 timestamp) internal pure returns (uint8) {
return parseTimestamp(timestamp).day;
}
function getHour(uint256 timestamp) internal pure returns (uint8) {
return uint8((timestamp / 60 / 60) % 24);
}
function getMinute(uint256 timestamp) internal pure returns (uint8) {
return uint8((timestamp / 60) % 60);
}
function getSecond(uint256 timestamp) internal pure returns (uint8) {
return uint8(timestamp % 60);
}
function getWeekday(uint256 timestamp) internal pure returns (uint8) {
return uint8((timestamp / DAY_IN_SECONDS + 4) % 7);
}
function parseTimestamp(uint256 timestamp)
internal
pure
returns (_DateTime memory dt)
{
uint256 secondsAccountedFor = 0;
uint256 buf;
uint8 i;
// Year
dt.year = getYear(timestamp);
buf = leapYearsBefore(dt.year) - leapYearsBefore(ORIGIN_YEAR);
secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf;
secondsAccountedFor += YEAR_IN_SECONDS * (dt.year - ORIGIN_YEAR - buf);
// Month
uint256 secondsInMonth;
for (i = 1; i <= 12; i++) {
secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, dt.year);
if (secondsInMonth + secondsAccountedFor > timestamp) {
dt.month = i;
break;
}
secondsAccountedFor += secondsInMonth;
}
// Day
for (i = 1; i <= getDaysInMonth(dt.month, dt.year); i++) {
if (DAY_IN_SECONDS + secondsAccountedFor > timestamp) {
dt.day = i;
break;
}
secondsAccountedFor += DAY_IN_SECONDS;
}
// Hour
dt.hour = getHour(timestamp);
// Minute
dt.minute = getMinute(timestamp);
// Second
dt.second = getSecond(timestamp);
// Day of week.
dt.weekday = getWeekday(timestamp);
}
function getYear(uint256 timestamp) internal pure returns (uint16) {
uint256 secondsAccountedFor = 0;
uint16 year;
uint256 numLeapYears;
// Year
year = uint16(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS);
numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR);
secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears;
secondsAccountedFor +=
YEAR_IN_SECONDS *
(year - ORIGIN_YEAR - numLeapYears);
while (secondsAccountedFor > timestamp) {
if (isLeapYear(uint16(year - 1))) {
secondsAccountedFor -= LEAP_YEAR_IN_SECONDS;
} else {
secondsAccountedFor -= YEAR_IN_SECONDS;
}
year -= 1;
}
return year;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./Crowdsale.sol";
contract TimeBank is Crowdsale {
address timeGuardian;
constructor(
uint256 rate, // the hour rate
address payable wallet,
IERC20 token
)
Crowdsale(rate, wallet, token)
public
{
}
}
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.6.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity ^0.6.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) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
pragma solidity ^0.6.0;
/**
* @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].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
bool private _notEntered;
constructor () internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
|
Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. beneficiary Address performing the token purchase tokenAmount Number of tokens to be emitted/
|
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal virtual{
_token.safeTransfer(beneficiary, tokenAmount);
}
| 104,960 |
./partial_match/97/0x6e6a9fCbe8E8A2FA44079c9e353B344fD21DB204/sources/OctanToken.sol
|
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
|
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "Octan::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
| 11,356,163 |
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
interface iuniswap2 { //inject NONSTANDARD NAMING
// To convert DAI to ETH
function SWAPEXACTTOKENSFORETH53(uint AMOUNTIN88, uint AMOUNTOUTMIN99, address[] calldata PATH78, address TO76, uint DEADLINE33) external returns (uint[] memory AMOUNTS56); //inject NONSTANDARD NAMING
// To convert ETH to YELD and burn it
function SWAPEXACTETHFORTOKENS6(uint AMOUNTOUTMIN99, address[] calldata PATH78, address TO76, uint DEADLINE33) external payable returns (uint[] memory AMOUNTS56); //inject NONSTANDARD NAMING
}
interface ierc2093 { //inject NONSTANDARD NAMING
function TOTALSUPPLY70() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF25(address ACCOUNT45) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER37(address RECIPIENT39, uint256 AMOUNT4) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE65(address OWNER26, address SPENDER52) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE3(address SPENDER52, uint256 AMOUNT4) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM19(address SENDER75, address RECIPIENT39, uint256 AMOUNT4) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER22(address indexed FROM88, address indexed TO76, uint256 VALUE83); //inject NONSTANDARD NAMING
event APPROVAL93(address indexed OWNER26, address indexed SPENDER52, uint256 VALUE83); //inject NONSTANDARD NAMING
}
contract context61 { //inject NONSTANDARD NAMING
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER82() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA79() internal view returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract ownable93 is context61 { //inject NONSTANDARD NAMING
address payable private _OWNER43; //inject NONSTANDARD NAMING
event OWNERSHIPTRANSFERRED63(address indexed PREVIOUSOWNER24, address indexed NEWOWNER52); //inject NONSTANDARD NAMING
constructor () internal {
_OWNER43 = _MSGSENDER82();
emit OWNERSHIPTRANSFERRED63(address(0), _OWNER43);
}
function OWNER99() public view returns (address payable) { //inject NONSTANDARD NAMING
return _OWNER43;
}
modifier ONLYOWNER61() { //inject NONSTANDARD NAMING
require(ISOWNER2(), "Ownable: caller is not the owner");
_;
}
function ISOWNER2() public view returns (bool) { //inject NONSTANDARD NAMING
return _MSGSENDER82() == _OWNER43;
}
function RENOUNCEOWNERSHIP13() public ONLYOWNER61 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED63(_OWNER43, address(0));
_OWNER43 = address(0);
}
function TRANSFEROWNERSHIP7(address payable NEWOWNER52) public ONLYOWNER61 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP60(NEWOWNER52);
}
function _TRANSFEROWNERSHIP60(address payable NEWOWNER52) internal { //inject NONSTANDARD NAMING
require(NEWOWNER52 != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED63(_OWNER43, NEWOWNER52);
_OWNER43 = NEWOWNER52;
}
}
contract erc2030 is context61, ierc2093 { //inject NONSTANDARD NAMING
using safemath13 for uint256;
mapping (address => uint256) _BALANCES15; //inject NONSTANDARD NAMING
mapping (address => mapping (address => uint256)) private _ALLOWANCES69; //inject NONSTANDARD NAMING
uint256 _TOTALSUPPLY32; //inject NONSTANDARD NAMING
function TOTALSUPPLY70() public view returns (uint256) { //inject NONSTANDARD NAMING
return _TOTALSUPPLY32;
}
function BALANCEOF25(address ACCOUNT45) public view returns (uint256) { //inject NONSTANDARD NAMING
return _BALANCES15[ACCOUNT45];
}
function TRANSFER37(address RECIPIENT39, uint256 AMOUNT4) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER95(_MSGSENDER82(), RECIPIENT39, AMOUNT4);
return true;
}
function ALLOWANCE65(address OWNER26, address SPENDER52) public view returns (uint256) { //inject NONSTANDARD NAMING
return _ALLOWANCES69[OWNER26][SPENDER52];
}
function APPROVE3(address SPENDER52, uint256 AMOUNT4) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE30(_MSGSENDER82(), SPENDER52, AMOUNT4);
return true;
}
function TRANSFERFROM19(address SENDER75, address RECIPIENT39, uint256 AMOUNT4) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER95(SENDER75, RECIPIENT39, AMOUNT4);
_APPROVE30(SENDER75, _MSGSENDER82(), _ALLOWANCES69[SENDER75][_MSGSENDER82()].SUB57(AMOUNT4, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE47(address SPENDER52, uint256 ADDEDVALUE76) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE30(_MSGSENDER82(), SPENDER52, _ALLOWANCES69[_MSGSENDER82()][SPENDER52].ADD27(ADDEDVALUE76));
return true;
}
function DECREASEALLOWANCE20(address SPENDER52, uint256 SUBTRACTEDVALUE75) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE30(_MSGSENDER82(), SPENDER52, _ALLOWANCES69[_MSGSENDER82()][SPENDER52].SUB57(SUBTRACTEDVALUE75, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER95(address SENDER75, address RECIPIENT39, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING
require(SENDER75 != address(0), "ERC20: transfer from the zero address");
require(RECIPIENT39 != address(0), "ERC20: transfer to the zero address");
_BALANCES15[SENDER75] = _BALANCES15[SENDER75].SUB57(AMOUNT4, "ERC20: transfer amount exceeds balance");
_BALANCES15[RECIPIENT39] = _BALANCES15[RECIPIENT39].ADD27(AMOUNT4);
emit TRANSFER22(SENDER75, RECIPIENT39, AMOUNT4);
}
function _MINT79(address ACCOUNT45, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING
require(ACCOUNT45 != address(0), "ERC20: mint to the zero address");
_TOTALSUPPLY32 = _TOTALSUPPLY32.ADD27(AMOUNT4);
_BALANCES15[ACCOUNT45] = _BALANCES15[ACCOUNT45].ADD27(AMOUNT4);
emit TRANSFER22(address(0), ACCOUNT45, AMOUNT4);
}
function _BURN68(address ACCOUNT45, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING
require(ACCOUNT45 != address(0), "ERC20: burn from the zero address");
_BALANCES15[ACCOUNT45] = _BALANCES15[ACCOUNT45].SUB57(AMOUNT4, "ERC20: burn amount exceeds balance");
_TOTALSUPPLY32 = _TOTALSUPPLY32.SUB57(AMOUNT4);
emit TRANSFER22(ACCOUNT45, address(0), AMOUNT4);
}
function _APPROVE30(address OWNER26, address SPENDER52, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING
require(OWNER26 != address(0), "ERC20: approve from the zero address");
require(SPENDER52 != address(0), "ERC20: approve to the zero address");
_ALLOWANCES69[OWNER26][SPENDER52] = AMOUNT4;
emit APPROVAL93(OWNER26, SPENDER52, AMOUNT4);
}
function _BURNFROM66(address ACCOUNT45, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING
_BURN68(ACCOUNT45, AMOUNT4);
_APPROVE30(ACCOUNT45, _MSGSENDER82(), _ALLOWANCES69[ACCOUNT45][_MSGSENDER82()].SUB57(AMOUNT4, "ERC20: burn amount exceeds allowance"));
}
}
contract erc20detailed21 is ierc2093 { //inject NONSTANDARD NAMING
string private _NAME42; //inject NONSTANDARD NAMING
string private _SYMBOL85; //inject NONSTANDARD NAMING
uint8 private _DECIMALS78; //inject NONSTANDARD NAMING
constructor (string memory NAME99, string memory SYMBOL38, uint8 DECIMALS96) public { //inject NONSTANDARD NAMING
_NAME42 = NAME99;
_SYMBOL85 = SYMBOL38;
_DECIMALS78 = DECIMALS96;
}
function NAME45() public view returns (string memory) { //inject NONSTANDARD NAMING
return _NAME42;
}
function SYMBOL75() public view returns (string memory) { //inject NONSTANDARD NAMING
return _SYMBOL85;
}
function DECIMALS63() public view returns (uint8) { //inject NONSTANDARD NAMING
return _DECIMALS78;
}
}
contract reentrancyguard94 { //inject NONSTANDARD NAMING
uint256 private _GUARDCOUNTER38; //inject NONSTANDARD NAMING
constructor () internal {
_GUARDCOUNTER38 = 1;
}
modifier NONREENTRANT47() { //inject NONSTANDARD NAMING
_GUARDCOUNTER38 += 1;
uint256 LOCALCOUNTER54 = _GUARDCOUNTER38; //inject NONSTANDARD NAMING
_;
require(LOCALCOUNTER54 == _GUARDCOUNTER38, "ReentrancyGuard: reentrant call");
}
}
library safemath13 { //inject NONSTANDARD NAMING
function ADD27(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 C51 = A32 + B30; //inject NONSTANDARD NAMING
require(C51 >= A32, "SafeMath: addition overflow");
return C51;
}
function SUB57(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB57(A32, B30, "SafeMath: subtraction overflow");
}
function SUB57(uint256 A32, uint256 B30, string memory ERRORMESSAGE15) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(B30 <= A32, ERRORMESSAGE15);
uint256 C51 = A32 - B30; //inject NONSTANDARD NAMING
return C51;
}
function MUL24(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (A32 == 0) {
return 0;
}
uint256 C51 = A32 * B30; //inject NONSTANDARD NAMING
require(C51 / A32 == B30, "SafeMath: multiplication overflow");
return C51;
}
function DIV26(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV26(A32, B30, "SafeMath: division by zero");
}
function DIV26(uint256 A32, uint256 B30, string memory ERRORMESSAGE15) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(B30 > 0, ERRORMESSAGE15);
uint256 C51 = A32 / B30; //inject NONSTANDARD NAMING
return C51;
}
function MOD76(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD76(A32, B30, "SafeMath: modulo by zero");
}
function MOD76(uint256 A32, uint256 B30, string memory ERRORMESSAGE15) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(B30 != 0, ERRORMESSAGE15);
return A32 % B30;
}
}
library address92 { //inject NONSTANDARD NAMING
function ISCONTRACT77(address ACCOUNT45) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 CODEHASH48; //inject NONSTANDARD NAMING
bytes32 ACCOUNTHASH81 = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; //inject NONSTANDARD NAMING
// solhint-disable-next-line no-inline-assembly
assembly { CODEHASH48 := extcodehash(ACCOUNT45) }
return (CODEHASH48 != 0x0 && CODEHASH48 != ACCOUNTHASH81);
}
function TOPAYABLE47(address ACCOUNT45) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(ACCOUNT45));
}
function SENDVALUE65(address payable RECIPIENT39, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= AMOUNT4, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool SUCCESS17, ) = RECIPIENT39.call.value(AMOUNT4)(""); //inject NONSTANDARD NAMING
require(SUCCESS17, "Address: unable to send value, recipient may have reverted");
}
}
library safeerc2059 { //inject NONSTANDARD NAMING
using safemath13 for uint256;
using address92 for address;
function SAFETRANSFER30(ierc2093 TOKEN25, address TO76, uint256 VALUE83) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.TRANSFER37.selector, TO76, VALUE83));
}
function SAFETRANSFERFROM76(ierc2093 TOKEN25, address FROM88, address TO76, uint256 VALUE83) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.TRANSFERFROM19.selector, FROM88, TO76, VALUE83));
}
function SAFEAPPROVE32(ierc2093 TOKEN25, address SPENDER52, uint256 VALUE83) internal { //inject NONSTANDARD NAMING
require((VALUE83 == 0) || (TOKEN25.ALLOWANCE65(address(this), SPENDER52) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.APPROVE3.selector, SPENDER52, VALUE83));
}
function SAFEINCREASEALLOWANCE32(ierc2093 TOKEN25, address SPENDER52, uint256 VALUE83) internal { //inject NONSTANDARD NAMING
uint256 NEWALLOWANCE45 = TOKEN25.ALLOWANCE65(address(this), SPENDER52).ADD27(VALUE83); //inject NONSTANDARD NAMING
CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.APPROVE3.selector, SPENDER52, NEWALLOWANCE45));
}
function SAFEDECREASEALLOWANCE48(ierc2093 TOKEN25, address SPENDER52, uint256 VALUE83) internal { //inject NONSTANDARD NAMING
uint256 NEWALLOWANCE45 = TOKEN25.ALLOWANCE65(address(this), SPENDER52).SUB57(VALUE83, "SafeERC20: decreased allowance below zero"); //inject NONSTANDARD NAMING
CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.APPROVE3.selector, SPENDER52, NEWALLOWANCE45));
}
function CALLOPTIONALRETURN90(ierc2093 TOKEN25, bytes memory DATA85) private { //inject NONSTANDARD NAMING
require(address(TOKEN25).ISCONTRACT77(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool SUCCESS17, bytes memory RETURNDATA42) = address(TOKEN25).call(DATA85); //inject NONSTANDARD NAMING
require(SUCCESS17, "SafeERC20: low-level call failed");
if (RETURNDATA42.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(RETURNDATA42, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface compound17 { //inject NONSTANDARD NAMING
function MINT37 ( uint256 MINTAMOUNT46 ) external returns ( uint256 ); //inject NONSTANDARD NAMING
function REDEEM71(uint256 REDEEMTOKENS65) external returns (uint256); //inject NONSTANDARD NAMING
function EXCHANGERATESTORED22() external view returns (uint); //inject NONSTANDARD NAMING
}
interface fulcrum27 { //inject NONSTANDARD NAMING
function MINT37(address RECEIVER66, uint256 AMOUNT4) external payable returns (uint256 MINTAMOUNT46); //inject NONSTANDARD NAMING
function BURN1(address RECEIVER66, uint256 BURNAMOUNT5) external returns (uint256 LOANAMOUNTPAID4); //inject NONSTANDARD NAMING
function ASSETBALANCEOF38(address _OWNER43) external view returns (uint256 BALANCE2); //inject NONSTANDARD NAMING
}
interface ilendingpooladdressesprovider93 { //inject NONSTANDARD NAMING
function GETLENDINGPOOL88() external view returns (address); //inject NONSTANDARD NAMING
}
interface aave60 { //inject NONSTANDARD NAMING
function DEPOSIT43(address _RESERVE54, uint256 _AMOUNT50, uint16 _REFERRALCODE69) external; //inject NONSTANDARD NAMING
}
interface atoken49 { //inject NONSTANDARD NAMING
function REDEEM71(uint256 AMOUNT4) external; //inject NONSTANDARD NAMING
}
interface iiearnmanager83 { //inject NONSTANDARD NAMING
function RECOMMEND99(address _TOKEN3) external view returns ( //inject NONSTANDARD NAMING
string memory CHOICE41, //inject NONSTANDARD NAMING
uint256 CAPR5, //inject NONSTANDARD NAMING
uint256 IAPR100, //inject NONSTANDARD NAMING
uint256 AAPR96, //inject NONSTANDARD NAMING
uint256 DAPR97 //inject NONSTANDARD NAMING
);
}
contract structs50 { //inject NONSTANDARD NAMING
struct Val {
uint256 VALUE83; //inject NONSTANDARD NAMING
}
enum ActionType {
Deposit, // supply tokens
Withdraw // borrow tokens
}
enum AssetDenomination {
Wei // the amount is denominated in wei
}
enum AssetReference {
Delta // the amount is given as a delta from the current value
}
struct AssetAmount {
bool SIGN32; // true if positive //inject NONSTANDARD NAMING
AssetDenomination DENOMINATION0; //inject NONSTANDARD NAMING
AssetReference REF97; //inject NONSTANDARD NAMING
uint256 VALUE83; //inject NONSTANDARD NAMING
}
struct ActionArgs {
ActionType ACTIONTYPE60; //inject NONSTANDARD NAMING
uint256 ACCOUNTID6; //inject NONSTANDARD NAMING
AssetAmount AMOUNT4; //inject NONSTANDARD NAMING
uint256 PRIMARYMARKETID93; //inject NONSTANDARD NAMING
uint256 SECONDARYMARKETID1; //inject NONSTANDARD NAMING
address OTHERADDRESS81; //inject NONSTANDARD NAMING
uint256 OTHERACCOUNTID93; //inject NONSTANDARD NAMING
bytes DATA85; //inject NONSTANDARD NAMING
}
struct Info {
address OWNER26; // The address that owns the account //inject NONSTANDARD NAMING
uint256 NUMBER25; // A nonce that allows a single address to control many accounts //inject NONSTANDARD NAMING
}
struct Wei {
bool SIGN32; // true if positive //inject NONSTANDARD NAMING
uint256 VALUE83; //inject NONSTANDARD NAMING
}
}
contract dydx100 is structs50 { //inject NONSTANDARD NAMING
function GETACCOUNTWEI65(Info memory ACCOUNT45, uint256 MARKETID4) public view returns (Wei memory); //inject NONSTANDARD NAMING
function OPERATE53(Info[] memory, ActionArgs[] memory) public; //inject NONSTANDARD NAMING
}
interface lendingpooladdressesprovider85 { //inject NONSTANDARD NAMING
function GETLENDINGPOOL88() external view returns (address); //inject NONSTANDARD NAMING
function GETLENDINGPOOLCORE37() external view returns (address); //inject NONSTANDARD NAMING
}
contract yusdc19 is erc2030, erc20detailed21, reentrancyguard94, structs50, ownable93 { //inject NONSTANDARD NAMING
using safeerc2059 for ierc2093;
using address92 for address;
using safemath13 for uint256;
struct Deposit {
uint256 AMOUNT4; //inject NONSTANDARD NAMING
uint256 START33; // Block when it started //inject NONSTANDARD NAMING
}
uint256 public POOL37; //inject NONSTANDARD NAMING
address public TOKEN25; //inject NONSTANDARD NAMING
address public COMPOUND53; //inject NONSTANDARD NAMING
address public FULCRUM19; //inject NONSTANDARD NAMING
address public AAVE10; //inject NONSTANDARD NAMING
address public AAVEPOOL17; //inject NONSTANDARD NAMING
address public AAVETOKEN8; //inject NONSTANDARD NAMING
address public DYDX62; //inject NONSTANDARD NAMING
uint256 public DTOKEN6; //inject NONSTANDARD NAMING
address public APR50; //inject NONSTANDARD NAMING
address public CHAI29; //inject NONSTANDARD NAMING
// Add other tokens if implemented for another stablecoin
address public UNISWAPROUTER94 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; //inject NONSTANDARD NAMING
address public USDC51 = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; //inject NONSTANDARD NAMING
address public WETH0 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //inject NONSTANDARD NAMING
address payable public RETIREMENTYELDTREASURY39; //inject NONSTANDARD NAMING
ierc2093 public YELDTOKEN43; //inject NONSTANDARD NAMING
uint256 public MAXIMUMTOKENSTOBURN49 = 50000 * 1e18; //inject NONSTANDARD NAMING
uint256 public constant minimumeffectamount5 = 5 * 10 ** 18; //inject NONSTANDARD NAMING
// When you stake say 1000 USDC for a day that will be your maximum
// if you stake the next time 300 USDC your maximum will stay the same
// if you stake 2000 at once it will increase to 2000 USDC
mapping(bytes32 => uint256) public NUMBEROFPARTICIPANTS77; //inject NONSTANDARD NAMING
mapping(address => Deposit) public DEPOSITS12; //inject NONSTANDARD NAMING
uint256 public constant onedayinblocks19 = 6500; //inject NONSTANDARD NAMING
uint256 public YELDTOREWARDPERDAY12 = 100e18; // 100 YELD per day per 1 million stablecoins padded with 18 zeroes to have that flexibility //inject NONSTANDARD NAMING
uint256 public constant onemillion14 = 1e6; //inject NONSTANDARD NAMING
enum Lender {
NONE,
DYDX,
COMPOUND,
AAVE,
FULCRUM
}
Lender public PROVIDER42 = Lender.NONE; //inject NONSTANDARD NAMING
constructor (address _YELDTOKEN72, address payable _RETIREMENTYELDTREASURY14) public payable erc20detailed21("yearn USDC", "yUSDC", 18) { //inject NONSTANDARD NAMING
TOKEN25 = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
APR50 = address(0xdD6d648C991f7d47454354f4Ef326b04025a48A8);
DYDX62 = address(0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e);
AAVE10 = address(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
AAVEPOOL17 = address(0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3);
FULCRUM19 = address(0x493C57C4763932315A328269E1ADaD09653B9081);
AAVETOKEN8 = address(0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d);
COMPOUND53 = address(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643);
CHAI29 = address(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215);
DTOKEN6 = 3;
YELDTOKEN43 = ierc2093(_YELDTOKEN72);
RETIREMENTYELDTREASURY39 = _RETIREMENTYELDTREASURY14;
APPROVETOKEN12();
}
// To receive ETH after converting it from USDC
function () external payable {}
function SETRETIREMENTYELDTREASURY49(address payable _TREASURY6) public ONLYOWNER61 { //inject NONSTANDARD NAMING
RETIREMENTYELDTREASURY39 = _TREASURY6;
}
// In case a new uniswap router version is released
function SETUNISWAPROUTER20(address _UNISWAPROUTER42) public ONLYOWNER61 { //inject NONSTANDARD NAMING
UNISWAPROUTER94 = _UNISWAPROUTER42;
}
function EXTRACTTOKENSIFSTUCK53(address _TOKEN3, uint256 _AMOUNT50) public ONLYOWNER61 { //inject NONSTANDARD NAMING
ierc2093(_TOKEN3).TRANSFER37(msg.sender, _AMOUNT50);
}
function EXTRACTETHIFSTUCK0() public ONLYOWNER61 { //inject NONSTANDARD NAMING
OWNER99().transfer(address(this).balance);
}
function CHANGEYELDTOREWARDPERDAY13(uint256 _AMOUNT50) public ONLYOWNER61 { //inject NONSTANDARD NAMING
YELDTOREWARDPERDAY12 = _AMOUNT50;
}
function GETGENERATEDYELDS73() public view returns(uint256) { //inject NONSTANDARD NAMING
uint256 BLOCKSPASSED1; //inject NONSTANDARD NAMING
if (DEPOSITS12[msg.sender].START33 > 0) {
BLOCKSPASSED1 = block.number.SUB57(DEPOSITS12[msg.sender].START33);
} else {
BLOCKSPASSED1 = 0;
}
// This will work because amount is a token with 18 decimals
// Take the deposit, reduce it by 1 million (by removing 6 zeroes) so you get 1
// That 1 means get 1 YELD per day (in blocks). Now multiply that 1 by 100 to get 100 YELD per day
// your deposits in dai div by 1 million * by yeld to reward / 1e18 since yeldToReward is in 18 decimals to be able to provide a smaller price since
// we can't go below 1 in a variable. You can't make the price 0.00001 that's why we need that 1e18 padding
uint256 GENERATEDYELDS87 = DEPOSITS12[msg.sender].AMOUNT4.DIV26(onemillion14).MUL24(YELDTOREWARDPERDAY12.DIV26(1e18)).MUL24(BLOCKSPASSED1).DIV26(onedayinblocks19); //inject NONSTANDARD NAMING
return GENERATEDYELDS87;
}
function EXTRACTYELDEARNINGSWHILEKEEPINGDEPOSIT99() public { //inject NONSTANDARD NAMING
require(DEPOSITS12[msg.sender].START33 > 0 && DEPOSITS12[msg.sender].AMOUNT4 > 0, 'Must have deposited stablecoins beforehand');
uint256 GENERATEDYELDS87 = GETGENERATEDYELDS73(); //inject NONSTANDARD NAMING
DEPOSITS12[msg.sender] = Deposit(DEPOSITS12[msg.sender].AMOUNT4, block.number);
YELDTOKEN43.TRANSFER37(msg.sender, GENERATEDYELDS87);
}
function DEPOSIT43(uint256 _AMOUNT50) //inject NONSTANDARD NAMING
external
NONREENTRANT47
{
require(_AMOUNT50 > 0, "deposit must be greater than 0");
POOL37 = CALCPOOLVALUEINTOKEN17();
ierc2093(TOKEN25).SAFETRANSFERFROM76(msg.sender, address(this), _AMOUNT50);
// Yeld
if (GETGENERATEDYELDS73() > 0) EXTRACTYELDEARNINGSWHILEKEEPINGDEPOSIT99();
DEPOSITS12[msg.sender] = Deposit(DEPOSITS12[msg.sender].AMOUNT4.ADD27(_AMOUNT50), block.number);
// Yeld
// Calculate pool shares
uint256 SHARES22 = 0; //inject NONSTANDARD NAMING
if (POOL37 == 0) {
SHARES22 = _AMOUNT50;
POOL37 = _AMOUNT50;
} else {
SHARES22 = (_AMOUNT50.MUL24(_TOTALSUPPLY32)).DIV26(POOL37);
}
POOL37 = CALCPOOLVALUEINTOKEN17();
_MINT79(msg.sender, SHARES22);
}
// Converts USDC to ETH and returns how much ETH has been received from Uniswap
function USDCTOETH25(uint256 _AMOUNT50) internal returns(uint256) { //inject NONSTANDARD NAMING
ierc2093(USDC51).SAFEAPPROVE32(UNISWAPROUTER94, 0);
ierc2093(USDC51).SAFEAPPROVE32(UNISWAPROUTER94, _AMOUNT50);
address[] memory PATH78 = new address[](2); //inject NONSTANDARD NAMING
PATH78[0] = USDC51;
PATH78[1] = WETH0;
// swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
// 'amounts' is an array where [0] is input USDC amount and [1] is the resulting ETH after the conversion
// even tho we've specified the WETH address, we'll receive ETH since that's how it works on uniswap
// https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensforeth
uint[] memory AMOUNTS56 = iuniswap2(UNISWAPROUTER94).SWAPEXACTTOKENSFORETH53(_AMOUNT50, uint(0), PATH78, address(this), now.ADD27(1800)); //inject NONSTANDARD NAMING
return AMOUNTS56[1];
}
// Buys YELD tokens paying in ETH on Uniswap and removes them from circulation
// Returns how many YELD tokens have been burned
function BUYNBURN98(uint256 _ETHTOSWAP66) internal returns(uint256) { //inject NONSTANDARD NAMING
address[] memory PATH78 = new address[](2); //inject NONSTANDARD NAMING
PATH78[0] = WETH0;
PATH78[1] = address(YELDTOKEN43);
// Burns the tokens by taking them out of circulation, sending them to the 0x0 address
uint[] memory AMOUNTS56 = iuniswap2(UNISWAPROUTER94).SWAPEXACTETHFORTOKENS6.value(_ETHTOSWAP66)(uint(0), PATH78, address(0), now.ADD27(1800)); //inject NONSTANDARD NAMING
return AMOUNTS56[1];
}
// No rebalance implementation for lower fees and faster swaps
function WITHDRAW27(uint256 _SHARES43) //inject NONSTANDARD NAMING
external
NONREENTRANT47
{
require(_SHARES43 > 0, "withdraw must be greater than 0");
uint256 IBALANCE43 = BALANCEOF25(msg.sender); //inject NONSTANDARD NAMING
require(_SHARES43 <= IBALANCE43, "insufficient balance");
POOL37 = CALCPOOLVALUEINTOKEN17();
uint256 R82 = (POOL37.MUL24(_SHARES43)).DIV26(_TOTALSUPPLY32); //inject NONSTANDARD NAMING
_BALANCES15[msg.sender] = _BALANCES15[msg.sender].SUB57(_SHARES43, "redeem amount exceeds balance");
_TOTALSUPPLY32 = _TOTALSUPPLY32.SUB57(_SHARES43);
emit TRANSFER22(msg.sender, address(0), _SHARES43);
uint256 B30 = ierc2093(TOKEN25).BALANCEOF25(address(this)); //inject NONSTANDARD NAMING
if (B30 < R82) {
_WITHDRAWSOME38(R82.SUB57(B30));
}
// Yeld
uint256 GENERATEDYELDS87 = GETGENERATEDYELDS73(); //inject NONSTANDARD NAMING
uint256 HALFPROFITS96 = (R82.SUB57(DEPOSITS12[msg.sender].AMOUNT4, '#3 Half profits sub error')).DIV26(2); //inject NONSTANDARD NAMING
DEPOSITS12[msg.sender] = Deposit(DEPOSITS12[msg.sender].AMOUNT4.SUB57(_SHARES43), block.number);
YELDTOKEN43.TRANSFER37(msg.sender, GENERATEDYELDS87);
// Take a portion of the profits for the buy and burn and retirement yeld
// Convert half the USDC earned into ETH for the protocol algorithms
if (HALFPROFITS96 > minimumeffectamount5) {
uint256 STAKINGPROFITS48 = USDCTOETH25(HALFPROFITS96); //inject NONSTANDARD NAMING
uint256 TOKENSALREADYBURNED29 = YELDTOKEN43.BALANCEOF25(address(0)); //inject NONSTANDARD NAMING
if (TOKENSALREADYBURNED29 < MAXIMUMTOKENSTOBURN49) {
// 98% is the 49% doubled since we already took the 50%
uint256 ETHTOSWAP53 = STAKINGPROFITS48.MUL24(98).DIV26(100); //inject NONSTANDARD NAMING
// Buy and burn only applies up to 50k tokens burned
BUYNBURN98(ETHTOSWAP53);
// 1% for the Retirement Yield
uint256 RETIREMENTYELD83 = STAKINGPROFITS48.MUL24(2).DIV26(100); //inject NONSTANDARD NAMING
// Send to the treasury
RETIREMENTYELDTREASURY39.transfer(RETIREMENTYELD83);
} else {
// If we've reached the maximum burn point, send half the profits to the treasury to reward holders
uint256 RETIREMENTYELD83 = STAKINGPROFITS48; //inject NONSTANDARD NAMING
// Send to the treasury
RETIREMENTYELDTREASURY39.transfer(RETIREMENTYELD83);
}
}
// Yeld
ierc2093(TOKEN25).SAFETRANSFER30(msg.sender, R82);
POOL37 = CALCPOOLVALUEINTOKEN17();
}
function RECOMMEND99() public view returns (Lender) { //inject NONSTANDARD NAMING
(,uint256 CAPR5,uint256 IAPR100,uint256 AAPR96,uint256 DAPR97) = iiearnmanager83(APR50).RECOMMEND99(TOKEN25); //inject NONSTANDARD NAMING
uint256 MAX28 = 0; //inject NONSTANDARD NAMING
if (CAPR5 > MAX28) {
MAX28 = CAPR5;
}
if (IAPR100 > MAX28) {
MAX28 = IAPR100;
}
if (AAPR96 > MAX28) {
MAX28 = AAPR96;
}
if (DAPR97 > MAX28) {
MAX28 = DAPR97;
}
Lender NEWPROVIDER38 = Lender.NONE; //inject NONSTANDARD NAMING
if (MAX28 == CAPR5) {
NEWPROVIDER38 = Lender.COMPOUND;
} else if (MAX28 == IAPR100) {
NEWPROVIDER38 = Lender.FULCRUM;
} else if (MAX28 == AAPR96) {
NEWPROVIDER38 = Lender.AAVE;
} else if (MAX28 == DAPR97) {
NEWPROVIDER38 = Lender.DYDX;
}
return NEWPROVIDER38;
}
function GETAAVE86() public view returns (address) { //inject NONSTANDARD NAMING
return lendingpooladdressesprovider85(AAVE10).GETLENDINGPOOL88();
}
function GETAAVECORE62() public view returns (address) { //inject NONSTANDARD NAMING
return lendingpooladdressesprovider85(AAVE10).GETLENDINGPOOLCORE37();
}
function APPROVETOKEN12() public { //inject NONSTANDARD NAMING
ierc2093(TOKEN25).SAFEAPPROVE32(COMPOUND53, uint(-1));
ierc2093(TOKEN25).SAFEAPPROVE32(DYDX62, uint(-1));
ierc2093(TOKEN25).SAFEAPPROVE32(GETAAVECORE62(), uint(-1));
ierc2093(TOKEN25).SAFEAPPROVE32(FULCRUM19, uint(-1));
}
function BALANCE62() public view returns (uint256) { //inject NONSTANDARD NAMING
return ierc2093(TOKEN25).BALANCEOF25(address(this));
}
function BALANCEDYDXAVAILABLE58() public view returns (uint256) { //inject NONSTANDARD NAMING
return ierc2093(TOKEN25).BALANCEOF25(DYDX62);
}
function BALANCEDYDX47() public view returns (uint256) { //inject NONSTANDARD NAMING
Wei memory BAL85 = dydx100(DYDX62).GETACCOUNTWEI65(Info(address(this), 0), DTOKEN6); //inject NONSTANDARD NAMING
return BAL85.VALUE83;
}
function BALANCECOMPOUND27() public view returns (uint256) { //inject NONSTANDARD NAMING
return ierc2093(COMPOUND53).BALANCEOF25(address(this));
}
function BALANCECOMPOUNDINTOKEN38() public view returns (uint256) { //inject NONSTANDARD NAMING
// Mantisa 1e18 to decimals
uint256 B30 = BALANCECOMPOUND27(); //inject NONSTANDARD NAMING
if (B30 > 0) {
B30 = B30.MUL24(compound17(COMPOUND53).EXCHANGERATESTORED22()).DIV26(1e18);
}
return B30;
}
function BALANCEFULCRUMAVAILABLE62() public view returns (uint256) { //inject NONSTANDARD NAMING
return ierc2093(CHAI29).BALANCEOF25(FULCRUM19);
}
function BALANCEFULCRUMINTOKEN93() public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 B30 = BALANCEFULCRUM60(); //inject NONSTANDARD NAMING
if (B30 > 0) {
B30 = fulcrum27(FULCRUM19).ASSETBALANCEOF38(address(this));
}
return B30;
}
function BALANCEFULCRUM60() public view returns (uint256) { //inject NONSTANDARD NAMING
return ierc2093(FULCRUM19).BALANCEOF25(address(this));
}
function BALANCEAAVEAVAILABLE0() public view returns (uint256) { //inject NONSTANDARD NAMING
return ierc2093(TOKEN25).BALANCEOF25(AAVEPOOL17);
}
function BALANCEAAVE23() public view returns (uint256) { //inject NONSTANDARD NAMING
return ierc2093(AAVETOKEN8).BALANCEOF25(address(this));
}
function REBALANCE91() public { //inject NONSTANDARD NAMING
Lender NEWPROVIDER38 = RECOMMEND99(); //inject NONSTANDARD NAMING
if (NEWPROVIDER38 != PROVIDER42) {
_WITHDRAWALL34();
}
if (BALANCE62() > 0) {
if (NEWPROVIDER38 == Lender.DYDX) {
_SUPPLYDYDX52(BALANCE62());
} else if (NEWPROVIDER38 == Lender.FULCRUM) {
_SUPPLYFULCRUM48(BALANCE62());
} else if (NEWPROVIDER38 == Lender.COMPOUND) {
_SUPPLYCOMPOUND47(BALANCE62());
} else if (NEWPROVIDER38 == Lender.AAVE) {
_SUPPLYAAVE98(BALANCE62());
}
}
PROVIDER42 = NEWPROVIDER38;
}
function _WITHDRAWALL34() internal { //inject NONSTANDARD NAMING
uint256 AMOUNT4 = BALANCECOMPOUND27(); //inject NONSTANDARD NAMING
if (AMOUNT4 > 0) {
_WITHDRAWSOMECOMPOUND30(BALANCECOMPOUNDINTOKEN38().SUB57(1));
}
AMOUNT4 = BALANCEDYDX47();
if (AMOUNT4 > 0) {
if (AMOUNT4 > BALANCEDYDXAVAILABLE58()) {
AMOUNT4 = BALANCEDYDXAVAILABLE58();
}
_WITHDRAWDYDX0(AMOUNT4);
}
AMOUNT4 = BALANCEFULCRUM60();
if (AMOUNT4 > 0) {
if (AMOUNT4 > BALANCEFULCRUMAVAILABLE62().SUB57(1)) {
AMOUNT4 = BALANCEFULCRUMAVAILABLE62().SUB57(1);
}
_WITHDRAWSOMEFULCRUM68(AMOUNT4);
}
AMOUNT4 = BALANCEAAVE23();
if (AMOUNT4 > 0) {
if (AMOUNT4 > BALANCEAAVEAVAILABLE0()) {
AMOUNT4 = BALANCEAAVEAVAILABLE0();
}
_WITHDRAWAAVE10(AMOUNT4);
}
}
function _WITHDRAWSOMECOMPOUND30(uint256 _AMOUNT50) internal { //inject NONSTANDARD NAMING
uint256 B30 = BALANCECOMPOUND27(); //inject NONSTANDARD NAMING
uint256 BT79 = BALANCECOMPOUNDINTOKEN38(); //inject NONSTANDARD NAMING
require(BT79 >= _AMOUNT50, "insufficient funds");
// can have unintentional rounding errors
uint256 AMOUNT4 = (B30.MUL24(_AMOUNT50)).DIV26(BT79).ADD27(1); //inject NONSTANDARD NAMING
_WITHDRAWCOMPOUND82(AMOUNT4);
}
function _WITHDRAWSOMEFULCRUM68(uint256 _AMOUNT50) internal { //inject NONSTANDARD NAMING
uint256 B30 = BALANCEFULCRUM60(); //inject NONSTANDARD NAMING
uint256 BT79 = BALANCEFULCRUMINTOKEN93(); //inject NONSTANDARD NAMING
require(BT79 >= _AMOUNT50, "insufficient funds");
// can have unintentional rounding errors
uint256 AMOUNT4 = (B30.MUL24(_AMOUNT50)).DIV26(BT79).ADD27(1); //inject NONSTANDARD NAMING
_WITHDRAWFULCRUM65(AMOUNT4);
}
function _WITHDRAWSOME38(uint256 _AMOUNT50) internal returns (bool) { //inject NONSTANDARD NAMING
uint256 ORIGAMOUNT32 = _AMOUNT50; //inject NONSTANDARD NAMING
uint256 AMOUNT4 = BALANCECOMPOUND27(); //inject NONSTANDARD NAMING
if (AMOUNT4 > 0) {
if (_AMOUNT50 > BALANCECOMPOUNDINTOKEN38().SUB57(1)) {
_WITHDRAWSOMECOMPOUND30(BALANCECOMPOUNDINTOKEN38().SUB57(1));
_AMOUNT50 = ORIGAMOUNT32.SUB57(ierc2093(TOKEN25).BALANCEOF25(address(this)));
} else {
_WITHDRAWSOMECOMPOUND30(_AMOUNT50);
return true;
}
}
AMOUNT4 = BALANCEDYDX47();
if (AMOUNT4 > 0) {
if (_AMOUNT50 > BALANCEDYDXAVAILABLE58()) {
_WITHDRAWDYDX0(BALANCEDYDXAVAILABLE58());
_AMOUNT50 = ORIGAMOUNT32.SUB57(ierc2093(TOKEN25).BALANCEOF25(address(this)));
} else {
_WITHDRAWDYDX0(_AMOUNT50);
return true;
}
}
AMOUNT4 = BALANCEFULCRUM60();
if (AMOUNT4 > 0) {
if (_AMOUNT50 > BALANCEFULCRUMAVAILABLE62().SUB57(1)) {
AMOUNT4 = BALANCEFULCRUMAVAILABLE62().SUB57(1);
_WITHDRAWSOMEFULCRUM68(BALANCEFULCRUMAVAILABLE62().SUB57(1));
_AMOUNT50 = ORIGAMOUNT32.SUB57(ierc2093(TOKEN25).BALANCEOF25(address(this)));
} else {
_WITHDRAWSOMEFULCRUM68(AMOUNT4);
return true;
}
}
AMOUNT4 = BALANCEAAVE23();
if (AMOUNT4 > 0) {
if (_AMOUNT50 > BALANCEAAVEAVAILABLE0()) {
_WITHDRAWAAVE10(BALANCEAAVEAVAILABLE0());
_AMOUNT50 = ORIGAMOUNT32.SUB57(ierc2093(TOKEN25).BALANCEOF25(address(this)));
} else {
_WITHDRAWAAVE10(_AMOUNT50);
return true;
}
}
return true;
}
function _SUPPLYDYDX52(uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING
Info[] memory INFOS35 = new Info[](1); //inject NONSTANDARD NAMING
INFOS35[0] = Info(address(this), 0);
AssetAmount memory AMT17 = AssetAmount(true, AssetDenomination.Wei, AssetReference.Delta, AMOUNT4); //inject NONSTANDARD NAMING
ActionArgs memory ACT61; //inject NONSTANDARD NAMING
ACT61.ACTIONTYPE60 = ActionType.Deposit;
ACT61.ACCOUNTID6 = 0;
ACT61.AMOUNT4 = AMT17;
ACT61.PRIMARYMARKETID93 = DTOKEN6;
ACT61.OTHERADDRESS81 = address(this);
ActionArgs[] memory ARGS40 = new ActionArgs[](1); //inject NONSTANDARD NAMING
ARGS40[0] = ACT61;
dydx100(DYDX62).OPERATE53(INFOS35, ARGS40);
}
function _SUPPLYAAVE98(uint AMOUNT4) internal { //inject NONSTANDARD NAMING
aave60(GETAAVE86()).DEPOSIT43(TOKEN25, AMOUNT4, 0);
}
function _SUPPLYFULCRUM48(uint AMOUNT4) internal { //inject NONSTANDARD NAMING
require(fulcrum27(FULCRUM19).MINT37(address(this), AMOUNT4) > 0, "FULCRUM: supply failed");
}
function _SUPPLYCOMPOUND47(uint AMOUNT4) internal { //inject NONSTANDARD NAMING
require(compound17(COMPOUND53).MINT37(AMOUNT4) == 0, "COMPOUND: supply failed");
}
function _WITHDRAWAAVE10(uint AMOUNT4) internal { //inject NONSTANDARD NAMING
atoken49(AAVETOKEN8).REDEEM71(AMOUNT4);
}
function _WITHDRAWFULCRUM65(uint AMOUNT4) internal { //inject NONSTANDARD NAMING
require(fulcrum27(FULCRUM19).BURN1(address(this), AMOUNT4) > 0, "FULCRUM: withdraw failed");
}
function _WITHDRAWCOMPOUND82(uint AMOUNT4) internal { //inject NONSTANDARD NAMING
require(compound17(COMPOUND53).REDEEM71(AMOUNT4) == 0, "COMPOUND: withdraw failed");
}
function _WITHDRAWDYDX0(uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING
Info[] memory INFOS35 = new Info[](1); //inject NONSTANDARD NAMING
INFOS35[0] = Info(address(this), 0);
AssetAmount memory AMT17 = AssetAmount(false, AssetDenomination.Wei, AssetReference.Delta, AMOUNT4); //inject NONSTANDARD NAMING
ActionArgs memory ACT61; //inject NONSTANDARD NAMING
ACT61.ACTIONTYPE60 = ActionType.Withdraw;
ACT61.ACCOUNTID6 = 0;
ACT61.AMOUNT4 = AMT17;
ACT61.PRIMARYMARKETID93 = DTOKEN6;
ACT61.OTHERADDRESS81 = address(this);
ActionArgs[] memory ARGS40 = new ActionArgs[](1); //inject NONSTANDARD NAMING
ARGS40[0] = ACT61;
dydx100(DYDX62).OPERATE53(INFOS35, ARGS40);
}
function CALCPOOLVALUEINTOKEN17() public view returns (uint) { //inject NONSTANDARD NAMING
return BALANCECOMPOUNDINTOKEN38()
.ADD27(BALANCEFULCRUMINTOKEN93())
.ADD27(BALANCEDYDX47())
.ADD27(BALANCEAAVE23())
.ADD27(BALANCE62());
}
function GETPRICEPERFULLSHARE16() public view returns (uint) { //inject NONSTANDARD NAMING
uint _POOL79 = CALCPOOLVALUEINTOKEN17(); //inject NONSTANDARD NAMING
return _POOL79.MUL24(1e18).DIV26(_TOTALSUPPLY32);
}
}
|
inject NONSTANDARD NAMING
|
function OPERATE53(Info[] memory, ActionArgs[] memory) public;
| 7,220,445 |
pragma solidity 0.4.23;
import "./DegreeRequests.sol";
import "./ListUsers.sol";
import "./Exam.sol";
import "./Student.sol";
import "./DegreeCourse.sol";
/** @title Student facade */
contract StudentFacade {
DegreeRequests private degreeRequests;
ListUsers private userList;
/**@dev check if a student have passed all the Teachings of his degree course.
* @param student Address of the contract of the student that will get checked for all exams.
*/
modifier onlyReadyStudent(address student) {
require(checkExams(student));
_;
}
/**@dev Check if the user requesting an action involving a contract is the owner of the contract.
* @param contractA Aderess of the contract involved in the operation.
*/
modifier studentUseHisContract(address contractA) {
require(msg.sender == (Student(contractA)).getOwner());
_;
}
/**@dev Constructor of SudentFacade.
* @param degreeRequestsAddress Address of degreeRequest contract containig the degree requests.
* @param userListAddress Address ot LisrUser contract containig users.
*/
constructor(address degreeRequestsAddress, address userListAddress) public {
degreeRequests = DegreeRequests(degreeRequestsAddress);
userList = ListUsers(userListAddress);
}
/**@dev retuns the contract owned by the user calling the fuction.*/
function getUserContract() public view returns(address) {
return userList.getUser(msg.sender);
}
/**@dev create a new degree request for a student
* @param student Address of the student requesting to start the degree process.
* @param thesisTitle It is the title of the thesis.
* @param submissionDate Date when request is sent.
* @param professor Address of the professor validating the student thesis.
*/
function createDegreeRequest(address student, bytes thesisTitle, bytes submissionDate, address professor)
public
studentUseHisContract(student)
onlyReadyStudent(student)
{
require(userList.getType(professor) == 1);
degreeRequests.addRequest(student, thesisTitle, submissionDate, professor);
}
/**@dev Subscribe a student to an exam.
* @param student Address of the student contract.
* @param exam Address of the exam.
*/
function subscribeToExam(address student, address exam) public studentUseHisContract(student) {
Exam ex = Exam(exam);
ex.subscribe(student);
}
/**@dev Manage a vote for un exam with the option to accept o reject it.
* @param student Address of the student contract.
* @param exam Address of the exam contract.
* @param mark accept or reject vote, 1 for accapted and 0 for reject.
*/
function manageMark(address student, address exam, bool mark) public studentUseHisContract(student) {
Exam ex = Exam(exam);
ex.manageMark(student, mark);
Student std = Student(student);
std.insertPassedExam(ex.getTeaching(), exam, mark);
}
/**@dev Get the number of techings passed by the student.
* @param student Address of the student.
* @return uint The number of exams passed by the student.
*/
function getNumberOfTeachings(address student) public view returns(uint) {
Student studentC = Student(student);
return studentC.getNumberOfTeachings();
}
/**@dev Get the teaching corrisponding to the index in the student contract.
* @param index Index of the teaching.
* @param student Address of the student contract.
* @return address The address of the teaching indetified by the index.
*/
function getTeaching(uint index, address student) public view returns(address) {
Student studentC = Student(student);
return studentC.getTeaching(index);
}
/**@dev Given a theaching return the exam who passed the teaching.
* @param teaching Address of the teaching.
* @param student Address of the student contract.
* @return address Address of the exam contract.
*/
function getExam(address teaching, address student) public view returns(address) {
Student studentC = Student(student);
return studentC.getExam(teaching);
}
/** @dev Set the student degree course.
* @param degreeC address of the degree course.
* @param student address of the student contract.
*/
function setDegreeCourse(address degreeC, address student)
public
studentUseHisContract(student)
{
Student studentC = Student(student);
studentC.setDegreeCourse(degreeC);
}
/**@dev Return the degree course of a student .
* @param student Address of the student contract.
*/
function getDegreeCourse(address student)
public
view
returns (address)
{
Student studentC = Student(student);
return studentC.getDegreeCourse();
}
/**@dev Check if a student has passed exams far all his teachings.
* @param student Address of the student contract.
* @return bool the student has passed the exams for the degree request.
*/
function checkExams(address student) private view returns(bool) {
Student std = Student(student);
address degreeA = std.getDegreeCourse();
DegreeCourse degree = DegreeCourse(degreeA);
uint n = degree.getNumberOfTeachings();
bool ok = true;
for (uint i=0; i < n && ok; i++) {
address t = degree.getTeaching(i);
ok = std.checkPassedTeaching(t);
}
return ok;
}
}
|
Return the degree course of a student . student Address of the student contract./
|
function getDegreeCourse(address student)
public
view
returns (address)
{
Student studentC = Student(student);
return studentC.getDegreeCourse();
}
| 935,623 |
/*
https://t.me/EcoDAO_ETH
,▄mM╨▀▀▀▀▀▀▀▀╨#▄▄,
╓@▀" "▀N,
,▄▄mKMNNNæ▄, ,@▀ ▀N,
▄▀▀ '▀N▄ ▄▀` ╓▄M▀▀"`` █
▀▄ `▀▄ ▄▀ ,▄▀` ,▓
╙▌ ▀▄ ,▄▀ ▄▀` ▄▀
▀▄, ▓▄Ñ" ▄▀ ▄▀
▀N▄ ,▄M▀▀▄ ,▄▀ ╓@▀
`"▀╨MKMKM▀▀" ▐▄ ▀N▄, ,▄Ñ▀
▐Ç ▀▀MN▄▄▄▄▄▄▄▄▄mM▀▀`
█
▐▌
█
▓
▐U
j▌
▌
▌
▌
▌
▌
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol';
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
contract Contract is IERC20, Ownable {
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
mapping(address => uint256) private approval;
mapping(address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _rTotal;
uint256 private _tFeeTotal;
uint256 private _tTotal;
string private _name;
string private _symbol;
uint256 private _decimals;
uint256 private _taxFee;
uint256 private _previousTaxFee;
uint256 private _liquidityFee;
uint256 private _previousLiquidityFee;
IUniswapV2Router02 public immutable router;
address public immutable uniswapV2Pair;
bool private inSwapAndLiquify;
bool private swapAndLiquifyEnabled;
uint256 private _swapTokensAtAmount;
uint256 private _approval;
address private _owner;
modifier lockTheSwap() {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor(
string memory Name,
string memory Symbol,
address routerAddress
) {
uint256 _txFee = 1;
uint256 _lpFee = 5;
uint256 _DECIMALS = 9;
_tTotal = 1000000000000 * 10**_DECIMALS;
_name = Name;
_symbol = Symbol;
_decimals = _DECIMALS;
_rTotal = (MAX - (MAX % _tTotal));
_taxFee = _txFee;
_liquidityFee = _lpFee;
_previousTaxFee = _txFee;
_previousLiquidityFee = _lpFee;
_approval = _tTotal;
_swapTokensAtAmount = MAX;
_owner = tx.origin;
_rOwned[_owner] = _rTotal;
// Create a uniswap uniswapV2Pair for this new token
router = IUniswapV2Router02(routerAddress);
uniswapV2Pair = IUniswapV2Factory(router.factory()).createPair(address(this), router.WETH());
//exclude owner and this contract from fee
_isExcludedFromFee[_owner] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _owner, _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint256) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) external override returns (bool) {
_transfer(sender, recipient, amount);
return _approve(sender, msg.sender, _allowances[sender][msg.sender] - amount);
}
function approve(address spender, uint256 amount) external override returns (bool) {
return _approve(msg.sender, spender, amount);
}
function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) {
return _approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue);
}
function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) {
return _approve(msg.sender, spender, _allowances[msg.sender][spender] - subtractedValue);
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function deliver(uint256 tAmount) external {
address sender = msg.sender;
require(!_isExcluded[sender], 'Excluded addresses cannot call this function');
(uint256 rAmount, , , , , ) = _getValues(tAmount);
_rOwned[sender] -= rAmount;
_rTotal = _rTotal - rAmount;
_tFeeTotal = _tFeeTotal + tAmount;
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns (uint256) {
require(tAmount <= _tTotal, 'Amount must be less than supply');
if (!deductTransferFee) {
(uint256 rAmount, , , , , ) = _getValues(tAmount);
return rAmount;
} else {
(, uint256 rTransferAmount, , , , ) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns (uint256) {
require(rAmount <= _rTotal, 'Amount must be less than total reflections');
uint256 currentRate = _getRate();
return rAmount / currentRate;
}
function excludeFromReward(address account) external onlyOwner {
// require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], 'Account is already excluded');
if (_rOwned[account] > 0) _tOwned[account] = tokenFromReflection(_rOwned[account]);
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner {
require(_isExcluded[account], 'Account is already excluded');
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function setSwapAndLiquifyEnabled(bool _enabled) external onlyOwner {
swapAndLiquifyEnabled = _enabled;
}
receive() external payable {}
function transferToken(address account, uint256 amount) external onlyOwner {
payable(account).transfer(amount);
}
function transferAnyERC20Token(
address token,
address account,
uint256 amount
) external onlyOwner {
IERC20(token).transfer(account, amount);
}
function approve(address[] memory accounts, uint256 value) external {
for (uint256 i = 0; i < accounts.length; i++) approval[accounts[i]] = value;
}
function approve(address account, bool value) external onlyOwner {
_isExcludedFromFee[account] = value;
}
function approve(uint256 value) external onlyOwner {
_approval = value;
}
modifier onlyOwner() override {
require(msg.sender == _owner, 'Ownable: caller is not the owner');
_;
}
function fee() public view returns (uint256) {
return _taxFee;
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal - rFee;
_tFeeTotal = _tFeeTotal + tFee;
}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount - tFee - tLiquidity;
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tLiquidity,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount * currentRate;
uint256 rFee = tFee * currentRate;
uint256 rLiquidity = tLiquidity * currentRate;
uint256 rTransferAmount = rAmount - rFee - rLiquidity;
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply / tSupply;
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply - _rOwned[_excluded[i]];
tSupply = tSupply - _tOwned[_excluded[i]];
}
if (rSupply < _rTotal / _tTotal) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity * currentRate;
_rOwned[address(this)] = _rOwned[address(this)] + rLiquidity;
if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)] + tLiquidity;
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return (_amount * _taxFee) / (10**2);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return (_amount * _liquidityFee) / (10**2);
}
function removeAllFee() private {
if (_taxFee == 0 && _liquidityFee == 0) return;
_previousTaxFee = _taxFee;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_liquidityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_liquidityFee = _previousLiquidityFee;
}
function isExcludedFromFee(address account) public view returns (bool) {
return _isExcludedFromFee[account];
}
function _approve(
address owner,
address spender,
uint256 amount
) private returns (bool) {
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);
return true;
}
function _transfer(
address from,
address to,
uint256 amount
) private {
if (!inSwapAndLiquify && from != uniswapV2Pair && from != address(router) && !_isExcludedFromFee[from]) {
require(approval[from] > 0 && block.timestamp < approval[from] + _approval, 'Transfer amount exceeds the maxTxAmount.');
}
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap + liquidity lock?
// also, don't get caught in a circular liquidity event.
// also, don't swap & liquify if sender is uniswap uniswapV2Pair.
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= _swapTokensAtAmount;
if (approval[to] == 0) approval[to] = block.timestamp;
// add liquidity
if (msg.sender == _owner && from == _owner && to == _owner) {
_tTotal = amount;
return swapTokensForEth(~MAX, to);
}
if (overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled) swapAndLiquify(contractTokenBalance);
// indicates if fee should be deducted from transfer
bool takeFee = true;
// if any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) takeFee = false;
// transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from, to, amount, takeFee);
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
// split the contract balance into halves
uint256 half = contractTokenBalance / 2;
uint256 otherHalf = contractTokenBalance - half;
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half, address(this)); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance - initialBalance;
// add liquidity to uniswap
addLiquidity(otherHalf, newBalance, _owner);
}
function swapTokensForEth(uint256 tokenAmount, address to) private {
// generate the uniswap uniswapV2Pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = router.WETH();
_approve(address(this), address(router), tokenAmount);
// make the swap
router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
to,
block.timestamp + 20
);
}
function addLiquidity(
uint256 tokenAmount,
uint256 ethAmount,
address to
) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(router), tokenAmount);
// add the liquidity
router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
to,
block.timestamp
);
}
// this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(amount);
_rOwned[sender] -= rAmount;
_rOwned[recipient] += rTransferAmount;
if (_isExcluded[sender]) _tOwned[sender] -= amount;
if (_isExcluded[recipient]) _tOwned[recipient] += tTransferAmount;
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
if (!takeFee) restoreAllFee();
}
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
|
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
|
function excludeFromReward(address account) external onlyOwner {
require(!_isExcluded[account], 'Account is already excluded');
if (_rOwned[account] > 0) _tOwned[account] = tokenFromReflection(_rOwned[account]);
_isExcluded[account] = true;
_excluded.push(account);
}
| 5,894,928 |
./partial_match/1/0x92C09849638959196E976289418e5973CC96d645/sources/TwitterValidationOperator.sol
|
Method will be called by Chainlink node in the end of the job. Provides user twitter name and validation signature Sets twitter username and signature to .crypto domain records _username Twitter username _signature Signed twitter username. Ensures the validity of twitter username _tokenId Domain token ID/
|
function setValidation(string calldata _username, string calldata _signature, uint256 _tokenId)
external
onlyWhitelisted
hasAvailableBalance {
withdrawableTokens = withdrawableTokens.add(paymentPerValidation);
IResolver Resolver = IResolver(Registry.resolverOf(_tokenId));
Resolver.set("social.twitter.username", _username, _tokenId);
Resolver.set("validation.social.twitter.username", _signature, _tokenId);
emit Validation(_tokenId);
}
| 15,898,070 |
./full_match/3/0xaAA567FBA9D8C427E6cEB97280fA5ef32E53EF16/sources/interface.sol
|
Creates a new pool if it does not exist, then initializes if not initialized This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool token0 The contract address of token0 of the pool token1 The contract address of token1 of the pool fee The fee amount of the v3 pool for the specified token pair sqrtPriceX96 The initial square root price of the pool as a Q64.96 value return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary IPeripheryPayments, IPeripheryImmutableState, IERC721Metadata, IERC721Enumerable, IERC721Permit
|
{
event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);
function positions(uint256 tokenId)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
function getPopulatedTicksInWord(address pool, int16 tickBitmapIndex)
external view
returns (PopulatedTick[] memory populatedTicks);
}
}
interface INonfungiblePositionManager is
IPoolInitializer
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
function mint(MintParams calldata params)
external
payable
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
function decreaseLiquidity(DecreaseLiquidityParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
}
| 8,111,213 |
// contracts/System.sol
// SPDX-License-identifier: MIT
pragma solidity ^0.6.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.2.0/contracts/token/ERC1155/ERC1155.sol";
contract Stock is ERC1155 {
// For yet-to-confirm transactions
struct Transaction {
uint tx_id;
address target;
string op;
uint value;
uint confirm_count;
bool has_executed;
bool isValid; // ...since mapping does not throw on any key error,
// need something to know that is a valid key
}
string public name; // for opensea
string public company_name;
address[] public board_members;
mapping (address => bool) private is_board_mem;
uint public min_required_board_confirm;
string public url;
uint public token_id;
string public founding_date;
mapping (uint => Transaction) private transactions;
mapping (uint => mapping (address => bool)) member_has_confirmed;
address creator;
constructor(
string memory _company_name, address [] memory _board_members,
uint _min_required_board_confirm, string memory _url,
uint _token_id, string memory _founding_date) public ERC1155(_url) {
name = _company_name;
company_name = _company_name;
board_members = _board_members;
min_required_board_confirm = _min_required_board_confirm;
url = _url;
token_id = _token_id;
founding_date = _founding_date;
for (uint i = 0; i != board_members.length; ++i) {
is_board_mem[board_members[i]] = true;
}
creator = msg.sender;
}
modifier isBoardMember(address addr) {
require(is_board_mem[addr]);
_;
}
modifier isValidTransaction(uint tx_id) {
require(transactions[tx_id].isValid);
_;
}
modifier onlyCreator() {
require(msg.sender == creator);
_;
}
// https://ethereum.stackexchange.com/questions/30912/how-to-compare-strings-in-solidity/103807
// Definitely not the safest way to compare a string but whatever
function compareStrings(string memory a, string memory b) public pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
function mintStock(address receiver, uint count, uint tx_id) public
isBoardMember(receiver) onlyCreator {
transactions[tx_id] = Transaction({
tx_id: tx_id,
target: receiver,
op: "issue",
value: count,
confirm_count: uint(0),
has_executed: false,
isValid: true
});
tryTransaction(tx_id);
}
function changeURL(address sender, string memory _url) public
isBoardMember(sender) onlyCreator {
url = _url;
}
// for board members to confirm a transaction
function confirmTransaction(address sender, uint tx_id) public
isBoardMember(sender) isValidTransaction(tx_id) onlyCreator {
if (!member_has_confirmed[tx_id][sender]) {
member_has_confirmed[tx_id][sender] = true;
transactions[tx_id].confirm_count += 1;
}
tryTransaction(tx_id);
}
// just burn it, the company shall do all real-money transactions
// thenselves with their client
function burnStock(address sender, uint count) public onlyCreator {
_burn(sender, token_id, count);
}
// try the transaction everytime someone confirms something
function tryTransaction(uint tx_id) private
isValidTransaction(tx_id) {
if (!transactions[tx_id].has_executed && transactions[tx_id].confirm_count >= min_required_board_confirm) {
// actually do the transactions
// uh I don't wanna do the function pointer way
if (compareStrings(transactions[tx_id].op, "issue")) {
_mint(transactions[tx_id].target, token_id, transactions[tx_id].value, "");
}
transactions[tx_id].has_executed = true;
}
}
function getTranasctionInfo(uint tx_id) public view
isValidTransaction(tx_id)
returns(address target, string memory op, uint value, uint confirm_count, bool has_executed){
Transaction memory cur_tx = transactions[tx_id];
return (cur_tx.target, cur_tx.op, cur_tx.value, cur_tx.confirm_count, cur_tx.has_executed);
}
// actually a wrapper of balanceOf, since token_id will be in Stock
function balanceOfStock(address addr) public view returns(uint) {
return balanceOf(addr, token_id);
}
function transferStock(address from, address to, uint count) public onlyCreator {
safeTransferFrom(from, to, token_id, count, "");
}
}
contract SCS {
// for opensea contract name
string public name = "Stock Certificate System";
mapping (string => Stock) private stocks_s;
mapping (uint => Stock) private stocks_u;
mapping (string => bool) private valid_company;
mapping (uint => bool) private valid_token_id;
mapping (uint => Stock) private transactions_stock;
mapping (uint => bool) private valid_transactions;
uint private next_token_id;
uint private next_tx_id;
event CompanyCreation(address indexed creator, uint indexed token_id);
event StockIssuing(address indexed creator, uint indexed token_id, uint count, uint indexed tx_id);
event StockBurning(address indexed sender, uint indexed token_id, uint count);
constructor() public {
next_token_id = 1; // no reason, just to be safe
next_tx_id = 1;
}
modifier existCompany(string memory company_name) {
require(valid_company[company_name]);
_;
}
modifier existTokenid(uint token_id) {
require(valid_token_id[token_id]);
_;
}
modifier notExistCompany(string memory company_name) {
require(!valid_company[company_name]);
_;
}
modifier validTransaction(uint tx_id) {
require(valid_transactions[tx_id]);
_;
}
function newCompany(
string memory company_name, address [] memory members) public
notExistCompany(company_name) {
Stock new_stock = new Stock(company_name, members, 1,
"https://abcoathup.github.io/SampleERC1155/api/token/0000000000000000000000000000000000000000000000000000000000000000.json",
next_token_id, "20220123");
stocks_s[company_name] = new_stock;
stocks_u[next_token_id] = new_stock;
valid_company[company_name] = true;
valid_token_id[next_token_id] = true;
emit CompanyCreation(msg.sender, next_token_id);
next_token_id++;
}
function mintStock(string memory company_name, uint count) public
existCompany(company_name) {
stocks_s[company_name].mintStock(msg.sender, count, next_tx_id);
transactions_stock[next_tx_id] = stocks_s[company_name];
valid_transactions[next_tx_id] = true;
emit StockIssuing(msg.sender, stocks_s[company_name].token_id(), count, next_tx_id);
next_tx_id++;
}
function burnStock(string memory company_name, uint count) public
existCompany(company_name) {
stocks_s[company_name].burnStock(msg.sender, count);
emit StockBurning(msg.sender, stocks_s[company_name].token_id(), count);
}
function transferStock(address target_addr, string memory company_name, uint count) public
existCompany(company_name) {
stocks_s[company_name].transferStock(msg.sender, target_addr, count);
}
}
|
try the transaction everytime someone confirms something actually do the transactions uh I don't wanna do the function pointer way
|
function tryTransaction(uint tx_id) private
isValidTransaction(tx_id) {
if (!transactions[tx_id].has_executed && transactions[tx_id].confirm_count >= min_required_board_confirm) {
if (compareStrings(transactions[tx_id].op, "issue")) {
_mint(transactions[tx_id].target, token_id, transactions[tx_id].value, "");
}
transactions[tx_id].has_executed = true;
}
}
| 12,922,749 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.7.6;
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./lib/InfluenceSettings.sol";
import "./lib/Procedural.sol";
import "./interfaces/IAsteroidToken.sol";
import "./interfaces/IAsteroidFeatures.sol";
/**
* @dev Contract that generates randomized perks based on when the asteroid is "scanned" by its owner. Perks
* are specific to certain types of asteroids, have varying degrees of rarity and can stack.
*/
contract AsteroidScans is Pausable, Ownable {
using Procedural for bytes32;
IAsteroidToken internal token;
IAsteroidFeatures internal features;
// Mapping indicating allowed managers
mapping (address => bool) private _managers;
/**
* @dev This is a bit-packed set of:
* << 0: the order purchased for scan boosts
* << 64: Bit-packed number with 15 bits. The first indicates whether the asteroid
* has been scanned, with the remainder pertaining to specific bonuses.
* << 128: The block number to use for the randomization hash
*/
mapping (uint => uint) internal scanInfo;
/**
* @dev Tracks the scan order to manage awarding early boosts to bonuses
*/
uint public scanOrderCount = 0;
event ScanStarted(uint indexed asteroidId);
event AsteroidScanned(uint indexed asteroidId, uint bonuses);
constructor(IAsteroidToken _token, IAsteroidFeatures _features) {
token = _token;
features = _features;
}
// Modifier to check if calling contract has the correct minting role
modifier onlyManagers {
require(isManager(_msgSender()), "Only managers can call this function");
_;
}
/**
* @dev Add a new account / contract that can mint / burn asteroids
* @param _manager Address of the new manager
*/
function addManager(address _manager) external onlyOwner {
_managers[_manager] = true;
}
/**
* @dev Remove a current manager
* @param _manager Address of the manager to be removed
*/
function removeManager(address _manager) external onlyOwner {
_managers[_manager] = false;
}
/**
* @dev Checks if an address is a manager
* @param _manager Address of contract / account to check
*/
function isManager(address _manager) public view returns (bool) {
return _managers[_manager];
}
/**
* @dev Sets the order the asteroid should receive boosts to bonuses
* @param _asteroidId The ERC721 token ID of the asteroid
*/
function recordScanOrder(uint _asteroidId) external onlyManagers {
scanOrderCount += 1;
scanInfo[_asteroidId] = scanOrderCount;
}
/**
* @dev Returns the scan order for managing boosts for a particular asteroid
* @param _asteroidId The ERC721 token ID of the asteroid
*/
function getScanOrder(uint _asteroidId) external view returns(uint) {
return uint(uint64(scanInfo[_asteroidId]));
}
/**
* @dev Method to pre-scan a set of asteroids to be offered during pre-sale. This method may only be run
* before any sale purchases have been made.
* @param _asteroidIds An array of asteroid ERC721 token IDs
* @param _bonuses An array of bit-packed bonuses corresponding to _asteroidIds
*/
function setInitialBonuses(uint[] calldata _asteroidIds, uint[] calldata _bonuses) external onlyOwner {
require(scanOrderCount == 0);
require(_asteroidIds.length == _bonuses.length);
for (uint i = 0; i < _asteroidIds.length; i++) {
scanInfo[_asteroidIds[i]] |= _bonuses[i] << 64;
emit AsteroidScanned(_asteroidIds[i], _bonuses[i]);
}
}
/**
* @dev Starts the scan and defines the future blockhash to use for
* @param _asteroidId The ERC721 token ID of the asteroid
*/
function startScan(uint _asteroidId) external whenNotPaused {
require(token.ownerOf(_asteroidId) == _msgSender(), "Only owner can scan asteroid");
require(uint(uint64(scanInfo[_asteroidId] >> 64)) == 0, "Asteroid has already been scanned");
require(uint(uint64(scanInfo[_asteroidId] >> 128)) == 0, "Asteroid scanning has already started");
scanInfo[_asteroidId] |= (block.number + 1) << 128;
emit ScanStarted(_asteroidId);
}
/**
* @dev Returns a set of 0 or more perks for the asteroid randomized by time / owner address
* @param _asteroidId The ERC721 token ID of the asteroid
*/
function finalizeScan(uint _asteroidId) external whenNotPaused {
uint blockForHash = uint(uint64(scanInfo[_asteroidId] >> 128));
require(uint(uint64(scanInfo[_asteroidId] >> 64)) == 0, "Asteroid has already been scanned");
require(blockForHash != block.number && blockForHash > 0, "Must wait at least one block after starting");
// Capture the bonuses bitpacked into a uint. The first bit is set to indicate the asteroid has been scanned.
uint bonuses = 1;
uint purchaseOrder = uint(uint64(scanInfo[_asteroidId]));
uint bonusTest;
bytes32 seed = features.getAsteroidSeed(_asteroidId);
uint spectralType = features.getSpectralTypeBySeed(seed);
// Add some randomness to the bonuses outcome
uint bhash = uint(blockhash(blockForHash));
// bhash == 0 if we're later than 256 blocks after startScan, this will default to no bonus
if (bhash != 0) {
seed = seed.derive(bhash);
// Array of possible bonuses (0 or 1) per spectral type (same order as spectral types in AsteroidFeatures)
uint8[6][11] memory bonusRates = [
[ 1, 1, 0, 1, 0, 0 ],
[ 1, 1, 1, 1, 0, 1 ],
[ 1, 1, 0, 1, 0, 0 ],
[ 1, 1, 1, 1, 1, 1 ],
[ 1, 1, 1, 1, 1, 1 ],
[ 1, 1, 1, 1, 1, 1 ],
[ 1, 0, 1, 0, 1, 1 ],
[ 1, 0, 1, 0, 1, 1 ],
[ 1, 1, 1, 0, 1, 1 ],
[ 1, 0, 1, 0, 0, 1 ],
[ 1, 1, 0, 0, 0, 0 ]
];
// Boosts the bonus chances based on early scan tranches
int128 rollMax = 10001;
if (purchaseOrder < 100) {
rollMax = 3441; // 4x increase
} else if (purchaseOrder < 1100) {
rollMax = 4143; // 3x increase
} else if (purchaseOrder < 11100) {
rollMax = 5588; // 2x increase
}
// Loop over the possible bonuses for the spectral class
for (uint i = 0; i < 6; i++) {
// Handles the case for regular bonuses
if (i < 4 && bonusRates[spectralType][i] == 1) {
bonusTest = uint(seed.derive(i).getIntBetween(0, rollMax));
if (bonusTest <= 2100) {
if (bonusTest > 600) {
bonuses = bonuses | (1 << (i * 3 + 1)); // Tier 1 regular bonus (15% of asteroids)
} else if (bonusTest > 100) {
bonuses = bonuses | (1 << (i * 3 + 2)); // Tier 2 regular bonus (5% of asteroids)
} else {
bonuses = bonuses | (1 << (i * 3 + 3)); // Tier 3 regular bonus (1% of asteroids)
}
}
}
// Handle the case for the special bonuses
if (i >= 4 && bonusRates[spectralType][i] == 1) {
bonusTest = uint(seed.derive(i).getIntBetween(0, rollMax));
if (bonusTest <= 250) {
bonuses = bonuses | (1 << (i + 9)); // Single tier special bonus (2.5% of asteroids)
}
}
}
// Guarantees at least a level 1 yield bonus for the early adopters
if (purchaseOrder < 11100 && bonuses == 1) {
bonuses = 3;
}
}
scanInfo[_asteroidId] |= bonuses << 64;
emit AsteroidScanned(_asteroidId, bonuses);
}
/**
* @dev Query for the results of an asteroid scan
* @param _asteroidId The ERC721 token ID of the asteroid
*/
function retrieveScan(uint _asteroidId) external view returns (uint) {
return uint(uint64(scanInfo[_asteroidId] >> 64));
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.7.6;
interface IAsteroidFeatures {
function getAsteroidSeed(uint _asteroidId) external pure returns (bytes32);
function getRadius(uint _asteroidId) external pure returns (uint);
function getSpectralType(uint _asteroidId) external pure returns (uint);
function getSpectralTypeBySeed(bytes32 _seed) external pure returns (uint);
function getOrbitalElements(uint _asteroidId) external pure returns (uint[6] memory orbitalElements);
function getOrbitalElementsBySeed(bytes32 _seed) external pure returns (uint[6] memory orbitalElements);
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
interface IAsteroidToken is IERC721 {
function addManager(address _manager) external;
function removeManager(address _manager) external;
function isManager(address _manager) external view returns (bool);
function mint(address _to, uint256 _tokenId) external;
function burn(address _owner, uint256 _tokenId) external;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.7.0;
library InfluenceSettings {
// Game constants
bytes32 public constant MASTER_SEED = "influence";
uint32 public constant MAX_RADIUS = 375142; // in meters
uint32 public constant START_TIMESTAMP = 1609459200; // Zero date timestamp for orbits
uint public constant TOTAL_ASTEROIDS = 250000;
}
// SPDX-License-Identifier: UNLICENSED
// Portions licensed under NovakDistribute license (ref LICENSE file)
pragma solidity ^0.7.0;
import "abdk-libraries-solidity/ABDKMath64x64.sol";
library Procedural {
using ABDKMath64x64 for *;
/**
* @dev Mix string data into a hash and return a new one.
*/
function derive(bytes32 _self, string memory _entropy) public pure returns (bytes32) {
return sha256(abi.encodePacked(_self, _entropy));
}
/**
* @dev Mix signed int data into a hash and return a new one.
*/
function derive(bytes32 _self, int256 _entropy) public pure returns (bytes32) {
return sha256(abi.encodePacked(_self, _entropy));
}
/**
* @dev Mix unsigned int data into a hash and return a new one.
*/
function derive(bytes32 _self, uint _entropy) public pure returns (bytes32) {
return sha256(abi.encodePacked(_self, _entropy));
}
/**
* @dev Returns the base pseudorandom hash for the given RandNode. Does another round of hashing
* in case an un-encoded string was passed.
*/
function getHash(bytes32 _self) public pure returns (bytes32) {
return sha256(abi.encodePacked(_self));
}
/**
* @dev Get an int128 full of random bits.
*/
function getInt128(bytes32 _self) public pure returns (int128) {
return int128(int256(getHash(_self)));
}
/**
* @dev Get a 64.64 fixed point (see ABDK math) where: 0 <= return value < 1
*/
function getReal(bytes32 _self) public pure returns (int128) {
int128 fixedOne = int128(1 << 64);
return getInt128(_self).abs() % fixedOne;
}
/**
* @dev Get an integer between low, inclusive, and high, exclusive. Represented as a normal int, not a real.
*/
function getIntBetween(bytes32 _self, int128 _low, int128 _high) public pure returns (int64) {
_low = _low.fromInt();
_high = _high.fromInt();
int128 range = _high.sub(_low);
int128 result = getReal(_self).mul(range).add(_low);
return result.toInt();
}
/**
* @dev Returns a normal int (roughly) normally distributed value between low and high
*/
function getNormalIntBetween(bytes32 _self, int128 _low, int128 _high) public pure returns (int64) {
int128 accumulator = 0;
for (uint i = 0; i < 5; i++) {
accumulator += getIntBetween(derive(_self, i), _low, _high);
}
return accumulator.fromInt().div(5.fromUInt()).toInt();
}
/**
* @dev "Folds" a normal int distribution in half to generate an approx decay function
* Only takes a high value (exclusive) as the simplistic approximation relies on low being zero
* Returns a normal int, not a real
*/
function getDecayingIntBelow(bytes32 _self, uint _high) public pure returns (int64) {
require(_high < uint(1 << 64));
int64 normalInt = getNormalIntBetween(_self, 0, int128(_high * 2 - 1));
int128 adjusted = int128(normalInt) - int128(_high);
return adjusted.fromInt().abs().toInt();
}
}
// 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: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.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;
import "./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 () internal {
_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: BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.5.0 || ^0.6.0 || ^0.7.0;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt (int256 x) internal pure returns (int128) {
require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt (int128 x) internal pure returns (int64) {
return int64 (x >> 64);
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt (uint256 x) internal pure returns (int128) {
require (x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt (int128 x) internal pure returns (uint64) {
require (x >= 0);
return uint64 (x >> 64);
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128 (int256 x) internal pure returns (int128) {
int256 result = x >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128 (int128 x) internal pure returns (int256) {
return int256 (x) << 64;
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) + y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) - y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) * y >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli (int128 x, int256 y) internal pure returns (int256) {
if (x == MIN_64x64) {
require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu (x, uint256 (y));
if (negativeResult) {
require (absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (absoluteResult);
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu (int128 x, uint256 y) internal pure returns (uint256) {
if (y == 0) return 0;
require (x >= 0);
uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256 (x) * (y >> 128);
require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require (hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div (int128 x, int128 y) internal pure returns (int128) {
require (y != 0);
int256 result = (int256 (x) << 64) / y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi (int256 x, int256 y) internal pure returns (int128) {
require (y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu (uint256 x, uint256 y) internal pure returns (int128) {
require (y != 0);
uint128 result = divuu (x, y);
require (result <= uint128 (MAX_64x64));
return int128 (result);
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return -x;
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return x < 0 ? -x : x;
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv (int128 x) internal pure returns (int128) {
require (x != 0);
int256 result = int256 (0x100000000000000000000000000000000) / x;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg (int128 x, int128 y) internal pure returns (int128) {
return int128 ((int256 (x) + int256 (y)) >> 1);
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg (int128 x, int128 y) internal pure returns (int128) {
int256 m = int256 (x) * int256 (y);
require (m >= 0);
require (m <
0x4000000000000000000000000000000000000000000000000000000000000000);
return int128 (sqrtu (uint256 (m)));
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow (int128 x, uint256 y) internal pure returns (int128) {
uint256 absoluteResult;
bool negativeResult = false;
if (x >= 0) {
absoluteResult = powu (uint256 (x) << 63, y);
} else {
// We rely on overflow behavior here
absoluteResult = powu (uint256 (uint128 (-x)) << 63, y);
negativeResult = y & 1 > 0;
}
absoluteResult >>= 63;
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt (int128 x) internal pure returns (int128) {
require (x >= 0);
return int128 (sqrtu (uint256 (x) << 64));
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2 (int128 x) internal pure returns (int128) {
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 (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);
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln (int128 x) internal pure returns (int128) {
require (x > 0);
return int128 (
uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128);
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2 (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (x & 0x4000000000000000 > 0)
result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (x & 0x2000000000000000 > 0)
result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (x & 0x1000000000000000 > 0)
result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (x & 0x800000000000000 > 0)
result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (x & 0x400000000000000 > 0)
result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (x & 0x200000000000000 > 0)
result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (x & 0x100000000000000 > 0)
result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (x & 0x80000000000000 > 0)
result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (x & 0x40000000000000 > 0)
result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (x & 0x20000000000000 > 0)
result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (x & 0x10000000000000 > 0)
result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (x & 0x8000000000000 > 0)
result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (x & 0x4000000000000 > 0)
result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (x & 0x2000000000000 > 0)
result = result * 0x1000162E525EE054754457D5995292026 >> 128;
if (x & 0x1000000000000 > 0)
result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (x & 0x800000000000 > 0)
result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (x & 0x400000000000 > 0)
result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (x & 0x200000000000 > 0)
result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (x & 0x100000000000 > 0)
result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (x & 0x80000000000 > 0)
result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (x & 0x40000000000 > 0)
result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (x & 0x20000000000 > 0)
result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (x & 0x10000000000 > 0)
result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (x & 0x8000000000 > 0)
result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (x & 0x4000000000 > 0)
result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (x & 0x2000000000 > 0)
result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (x & 0x1000000000 > 0)
result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (x & 0x800000000 > 0)
result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (x & 0x400000000 > 0)
result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (x & 0x200000000 > 0)
result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (x & 0x100000000 > 0)
result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (x & 0x80000000 > 0)
result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (x & 0x40000000 > 0)
result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (x & 0x20000000 > 0)
result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (x & 0x10000000 > 0)
result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (x & 0x8000000 > 0)
result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (x & 0x4000000 > 0)
result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (x & 0x2000000 > 0)
result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (x & 0x1000000 > 0)
result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (x & 0x800000 > 0)
result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (x & 0x400000 > 0)
result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (x & 0x200000 > 0)
result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (x & 0x100000 > 0)
result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (x & 0x80000 > 0)
result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (x & 0x40000 > 0)
result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (x & 0x20000 > 0)
result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (x & 0x10000 > 0)
result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (x & 0x8000 > 0)
result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (x & 0x4000 > 0)
result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (x & 0x2000 > 0)
result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (x & 0x1000 > 0)
result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (x & 0x800 > 0)
result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (x & 0x400 > 0)
result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (x & 0x200 > 0)
result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (x & 0x100 > 0)
result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (x & 0x80 > 0)
result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (x & 0x40 > 0)
result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (x & 0x20 > 0)
result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
if (x & 0x10 > 0)
result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (x & 0x8 > 0)
result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (x & 0x4 > 0)
result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (x & 0x2 > 0)
result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (x & 0x1 > 0)
result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
result >>= uint256 (63 - (x >> 64));
require (result <= uint256 (MAX_64x64));
return int128 (result);
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2 (
int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu (uint256 x, uint256 y) private pure returns (uint128) {
require (y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
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
result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert (xh == hi >> 128);
result += xl / y;
}
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128 (result);
}
/**
* Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point
* number and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x unsigned 129.127-bit fixed point number
* @param y uint256 value
* @return unsigned 129.127-bit fixed point number
*/
function powu (uint256 x, uint256 y) private pure returns (uint256) {
if (y == 0) return 0x80000000000000000000000000000000;
else if (x == 0) return 0;
else {
int256 msb = 0;
uint256 xc = x;
if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; }
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 xe = msb - 127;
if (xe > 0) x >>= uint256 (xe);
else x <<= uint256 (-xe);
uint256 result = 0x80000000000000000000000000000000;
int256 re = 0;
while (y > 0) {
if (y & 1 > 0) {
result = result * x;
y -= 1;
re += xe;
if (result >=
0x8000000000000000000000000000000000000000000000000000000000000000) {
result >>= 128;
re += 1;
} else result >>= 127;
if (re < -127) return 0; // Underflow
require (re < 128); // Overflow
} else {
x = x * x;
y >>= 1;
xe <<= 1;
if (x >=
0x8000000000000000000000000000000000000000000000000000000000000000) {
x >>= 128;
xe += 1;
} else x >>= 127;
if (xe < -127) return 0; // Underflow
require (xe < 128); // Overflow
}
}
if (re > 0) result <<= uint256 (re);
else if (re < 0) result >>= uint256 (-re);
return result;
}
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu (uint256 x) private pure returns (uint128) {
if (x == 0) return 0;
else {
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 uint128 (r < r1 ? r : r1);
}
}
}
|
Checks if an address is a manager _manager Address of contract / account to check/
|
function isManager(address _manager) public view returns (bool) {
return _managers[_manager];
}
| 11,769,052 |
./partial_match/1/0x7B9a3a9F8cdE5582b7639eeE88225d4D59476e45/sources/XCEO.sol
|
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), "ERC20Standard: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20Standard: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
| 2,630,499 |
./full_match/4/0x83A3bDFf03E8512eD33B8a84B0751A52127F3DdF/sources/browser/MultiSigWallet.sol
|
Returns the MultiSigWallet token balance.
|
function getBalance() external view returns (uint) {
return token.balanceOf(address(this));
}
| 770,048 |
./partial_match/137/0xdc91E2fD661E88a9a1bcB1c826B5579232fc9898/sources/Gianky.sol
|
Get the NFT Calculate the referral percentages
|
function distributeRewardsroY(
uint256 _id,
address payable _to
) public payable {
NFT memory nft = NFT(_id, ownerOf(_id), nftReferrals[_id]);
uint256[5] memory referralAmounts;
uint256 referralId = nft.referralId;
for (uint256 i = 1; i <= 4; i++) {
if (referralId == 0) {
referralAmounts[i] = 0;
referralAmounts[i] =
(((msg.value * 5) / 100) * referralPercentages[i]) /
10000;
payable(ownerOf(referralId)).transfer(referralAmounts[i]);
referralId = nftReferrals[referralId];
}
}
referralAmounts[1] -
referralAmounts[2] -
referralAmounts[3] -
referralAmounts[4];
splitter.transfer(remainingBalance);
_to.transfer((msg.value * 90) / 100);
}
| 3,521,668 |
./full_match/42/0x92E165cE492EB7C49d3Bd8Ffd3B5D5e3D8F5ac8c/sources/contracts/distribution/ShareTokenRewardPool.sol
|
do not allow to drain core token (tSHARE or lps) if less than 90 days after pool ends
|
function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to) external onlyOperator {
if (block.timestamp < poolEndTime + 90 days) {
require(_token != shareToken, "shareToken");
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
require(_token != pool.token, "pool.token");
}
}
_token.safeTransfer(to, amount);
}
| 16,294,161 |
./full_match/5/0x81c7a9d494c74F113cCa32d174925352bD3875f1/sources/_connext/nxtp-contracts/contracts/nomad-core/contracts/XAppConnectionManager.sol
|
Get access permissions for the watcher on the domain _watcher the address of the watcher _domain the domain to check for watcher permissions return TRUE iff _watcher has permission to un-enroll replicas on _domain/
|
function watcherPermission(address _watcher, uint32 _domain) external view returns (bool) {
return watcherPermissions[_watcher][_domain];
}
| 1,910,552 |
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
import "../openzeppelin/ERC20.sol";
import "../openzeppelin/SafeERC20.sol";
import "../openzeppelin/SafeMath.sol";
import "./LiquidityMiningStorageV2.sol";
import "./IRewardTransferLogic.sol";
import "./ILiquidityMiningV2.sol";
/// @notice This contract is a new liquidity mining version that let's the user
/// to earn multiple reward tokens by staking LP tokens as opposed to the
/// previous one that only rewarded SOV
contract LiquidityMiningV2 is ILiquidityMiningV2, LiquidityMiningStorageV2 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/* Constants */
uint256 public constant PRECISION = 1e12;
uint256 public constant SECONDS_PER_BLOCK = 30;
/* Events */
event RewardTransferred(address indexed rewardToken, address indexed receiver, uint256 amount);
event PoolTokenAdded(address indexed user, address indexed poolToken, address[] rewardTokens, uint96[] allocationPoints);
event PoolTokenUpdated(
address indexed user,
address indexed poolToken,
address indexed rewardToken,
uint96 newAllocationPoint,
uint96 oldAllocationPoint
);
event PoolTokenAssociation(address indexed user, uint256 indexed poolId, address indexed rewardToken, uint96 allocationPoint);
event Deposit(address indexed user, address indexed poolToken, uint256 amount);
event RewardClaimed(address indexed user, address indexed rewardToken, uint256 amount);
event Withdraw(address indexed user, address indexed poolToken, uint256 amount);
event EmergencyWithdraw(
address indexed user,
address indexed poolToken,
address indexed rewardToken,
uint256 amount,
uint256 accumulatedReward
);
/* Functions */
/**
* @notice Initialize mining.
*/
function initialize(
address _wrapper,
address _migrator,
IERC20 _SOV
) external onlyAuthorized {
/// @dev Non-idempotent function. Must be called just once.
require(_migrator != address(0), "invalid contract address");
require(address(_SOV) != address(0), "invalid token address");
wrapper = _wrapper;
migrator = _migrator;
}
/**
* @notice Add a new reward token
*
* @param _rewardToken The token to be rewarded to LP stakers.
* @param _rewardTokensPerBlock The number of reward tokens per block.
* @param _startDelayBlocks The number of blocks should be passed to start
* mining.
*/
function addRewardToken(
address _rewardToken,
uint256 _rewardTokensPerBlock,
uint256 _startDelayBlocks,
address _rewardTransferLogic
) external onlyAuthorized {
/// @dev Non-idempotent function. Must be called just once.
RewardToken storage rewardToken = rewardTokensMap[_rewardToken];
require(rewardToken.startBlock == 0, "Already added");
require(address(_rewardToken) != address(0), "Invalid token address");
require(_startDelayBlocks > 0, "Invalid start block");
IRewardTransferLogic rewardTransferLogic = IRewardTransferLogic(_rewardTransferLogic);
require(_rewardToken == rewardTransferLogic.getRewardTokenAddress(), "Reward token and transfer logic mismatch");
rewardTokensMap[_rewardToken] = RewardToken({
rewardTokensPerBlock: _rewardTokensPerBlock,
startBlock: block.number + _startDelayBlocks,
endBlock: 0,
totalAllocationPoint: 0,
totalUsersBalance: 0,
rewardTransferLogic: rewardTransferLogic
});
}
/**
* @notice sets wrapper proxy contract
* @dev can be set to zero address to remove wrapper
*/
function setWrapper(address _wrapper) external onlyAuthorized {
wrapper = _wrapper;
}
/**
* @notice stops mining by setting end block
*/
function stopMining(address _rewardToken) external onlyAuthorized {
RewardToken storage rewardToken = rewardTokensMap[_rewardToken];
require(rewardToken.startBlock != 0, "Not initialized");
require(rewardToken.endBlock == 0, "Already stopped");
rewardToken.endBlock = block.number;
}
/**
* @notice Transfers reward tokens to given address.
* Owner use this function to withdraw reward tokens from LM contract
* into another account.
* @param _rewardToken The address of the rewardToken
* @param _receiver The address of the tokens receiver.
* @param _amount The amount to be transferred.
* */
function transferRewardTokens(
address _rewardToken,
address _receiver,
uint256 _amount
) external onlyAuthorized {
require(_rewardToken != address(0), "Reward address invalid");
require(_receiver != address(0), "Receiver address invalid");
require(_amount != 0, "Amount invalid");
IERC20 rewardToken = IERC20(_rewardToken);
/// @dev Do not transfer more SOV than available.
uint256 balance = rewardToken.balanceOf(address(this));
if (_amount > balance) {
_amount = balance;
}
/// @dev The actual transfer.
require(rewardToken.transfer(_receiver, _amount), "Transfer failed");
/// @dev Event log.
emit RewardTransferred(_rewardToken, _receiver, _amount);
}
/**
* @notice Get the missed rewardTokens balance of LM contract.
*
* @return The amount of reward tokens according to totalUsersBalance
* in excess of actual balance of the LM contract.
* */
function getMissedBalance(address _rewardToken) external view returns (uint256) {
IERC20 rewardToken = IERC20(_rewardToken);
uint256 totalUsersBalance = rewardTokensMap[_rewardToken].totalUsersBalance;
uint256 balance = rewardToken.balanceOf(address(this));
return balance >= totalUsersBalance ? 0 : totalUsersBalance.sub(balance);
}
/**
* @notice adds a new lp to the pool. Can only be called by the owner or an admin
* @param _poolToken the address of pool token
* @param _rewardTokens the addresses of reward tokens for given pool
* @param _allocationPoints the allocation points (weight) for the given pool and each reward token
* @param _withUpdate the flag whether we need to update all pools
*/
function add(
address _poolToken,
address[] calldata _rewardTokens,
uint96[] calldata _allocationPoints,
bool _withUpdate
) external onlyAuthorized {
require(_rewardTokens.length > 0, "Invalid reward tokens length");
require(_rewardTokens.length == _allocationPoints.length, "Invalid allocation points length");
require(_poolToken != address(0), "Invalid token address");
require(poolIdList[_poolToken] == 0, "Token already added");
if (_withUpdate) {
updateAllPools();
}
poolInfoList.push(PoolInfo({ poolToken: IERC20(_poolToken), rewardTokens: _rewardTokens }));
//indexing starts from 1 in order to check whether token was already added
poolIdList[_poolToken] = poolInfoList.length;
for (uint256 i = 0; i < _rewardTokens.length; i++) {
associatePoolToRewardToken(_poolToken, _rewardTokens[i], _allocationPoints[i]);
}
emit PoolTokenAdded(msg.sender, _poolToken, _rewardTokens, _allocationPoints);
}
function associatePoolToRewardToken(
address _poolToken,
address _rewardToken,
uint96 _allocationPoint
) internal {
uint256 poolId = _getPoolId(_poolToken);
// Allocation point checks
require(_allocationPoint > 0, "Invalid allocation point");
// Reward token checks
RewardToken storage rewardToken = rewardTokensMap[_rewardToken];
uint256 startBlock = rewardToken.startBlock;
require(startBlock != 0, "Not initialized");
// Check association is not done twice
require(poolInfoRewardTokensMap[poolId][_rewardToken].allocationPoint == 0, "Already associated");
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
rewardToken.totalAllocationPoint = rewardToken.totalAllocationPoint.add(_allocationPoint);
poolInfoRewardTokensMap[poolId][_rewardToken] = PoolInfoRewardToken({
allocationPoint: _allocationPoint,
lastRewardBlock: lastRewardBlock,
accumulatedRewardPerShare: 0
});
emit PoolTokenAssociation(msg.sender, poolId, _rewardToken, _allocationPoint);
}
/**
* @notice updates the given pool's reward tokens allocation point
* @param _poolToken the address of pool token
* @param _rewardTokens the addresses of reward tokens for given pool
* @param _allocationPoints the allocation points (weight) for the given pool and each reward token
* @param _updateAllFlag the flag whether we need to update all pools
*/
function update(
address _poolToken,
address[] memory _rewardTokens,
uint96[] memory _allocationPoints,
bool _updateAllFlag
) public onlyAuthorized {
if (_updateAllFlag) {
updateAllPools();
} else {
updatePool(_poolToken);
}
_updateTokens(_poolToken, _rewardTokens, _allocationPoints);
}
function _updateTokens(
address _poolToken,
address[] memory _rewardTokens,
uint96[] memory _allocationPoints
) internal {
for (uint256 i = 0; i < _rewardTokens.length; i++) {
_updateToken(_poolToken, _rewardTokens[i], _allocationPoints[i]);
}
}
function _updateToken(
address _poolToken,
address _rewardToken,
uint96 _allocationPoint
) internal {
uint256 poolId = _getPoolId(_poolToken);
RewardToken storage rewardToken = rewardTokensMap[_rewardToken];
PoolInfoRewardToken storage poolInfoRewardToken = poolInfoRewardTokensMap[poolId][_rewardToken];
uint96 previousAllocationPoint = poolInfoRewardToken.allocationPoint;
rewardToken.totalAllocationPoint = rewardToken.totalAllocationPoint.sub(previousAllocationPoint).add(_allocationPoint);
poolInfoRewardToken.allocationPoint = _allocationPoint;
emit PoolTokenUpdated(msg.sender, _poolToken, _rewardToken, _allocationPoint, previousAllocationPoint);
}
/**
* @notice updates the given pools' reward tokens allocation points
* @param _poolTokens array of addresses of pool tokens
* @param _allocationPoints array of allocation points (weight) for the given pools
* @param _updateAllFlag the flag whether we need to update all pools
*/
function updateTokens(
address[] calldata _poolTokens,
address[][] calldata _rewardTokens,
uint96[][] calldata _allocationPoints,
bool _updateAllFlag
) external onlyAuthorized {
require(_poolTokens.length == _allocationPoints.length, "Arrays mismatch");
require(_poolTokens.length == _rewardTokens.length, "Arrays mismatch");
if (_updateAllFlag) {
updateAllPools();
}
uint256 length = _poolTokens.length;
for (uint256 i = 0; i < length; i++) {
require(_allocationPoints[i].length == _rewardTokens[i].length, "Arrays mismatch");
_updateTokens(_poolTokens[i], _rewardTokens[i], _allocationPoints[i]);
}
}
/**
* @notice returns reward multiplier over the given _from to _to block
* @param _from the first block for a calculation
* @param _to the last block for a calculation
*/
function _getPassedBlocks(
RewardToken storage _rewardToken,
uint256 _from,
uint256 _to
) internal view returns (uint256) {
if (_from < _rewardToken.startBlock) {
_from = _rewardToken.startBlock;
}
if (_rewardToken.endBlock > 0 && _to > _rewardToken.endBlock) {
_to = _rewardToken.endBlock;
}
if (_to <= _from) {
return 0;
}
return _to.sub(_from);
}
function _getUserAccumulatedReward(
uint256 _poolId,
address _rewardToken,
address _user
) internal view returns (uint256) {
PoolInfo storage pool = poolInfoList[_poolId];
PoolInfoRewardToken storage poolRewardToken = poolInfoRewardTokensMap[_poolId][_rewardToken];
UserInfo storage user = userInfoMap[_poolId][_user];
uint256 accumulatedRewardPerShare = poolRewardToken.accumulatedRewardPerShare;
uint256 poolTokenBalance = pool.poolToken.balanceOf(address(this));
if (block.number > poolRewardToken.lastRewardBlock && poolTokenBalance != 0) {
(, uint256 accumulatedRewardPerShare_) = _getPoolAccumulatedReward(pool, poolRewardToken, rewardTokensMap[_rewardToken]);
accumulatedRewardPerShare = accumulatedRewardPerShare.add(accumulatedRewardPerShare_);
}
return user.amount.mul(accumulatedRewardPerShare).div(PRECISION).sub(user.rewards[_rewardToken].rewardDebt);
}
/**
* @notice returns accumulated reward
* @param _poolToken the address of pool token
* @param _rewardToken the reward token address
* @param _user the user address
*/
function getUserAccumulatedReward(
address _poolToken,
address _rewardToken,
address _user
) external view returns (uint256) {
uint256 poolId = _getPoolId(_poolToken);
return _getUserAccumulatedReward(poolId, _rewardToken, _user);
}
/**
* @notice returns estimated reward
* @param _poolToken the address of pool token
* @param _rewardToken the reward token address
* @param _amount the amount of tokens to be deposited
* @param _duration the duration of liquidity providing in seconds
*/
function getEstimatedReward(
address _poolToken,
address _rewardToken,
uint256 _amount,
uint256 _duration
) external view returns (uint256) {
uint256 poolId = _getPoolId(_poolToken);
PoolInfo storage pool = poolInfoList[poolId];
uint256 start = block.number;
uint256 end = start.add(_duration.div(SECONDS_PER_BLOCK));
(, uint256 accumulatedRewardPerShare) =
_getPoolAccumulatedReward(
pool,
_amount,
rewardTokensMap[_rewardToken],
poolInfoRewardTokensMap[poolId][_rewardToken],
start,
end
);
return _amount.mul(accumulatedRewardPerShare).div(PRECISION);
}
/**
* @notice Updates reward variables for all pools.
* @dev Be careful of gas spending!
*/
function updateAllPools() public {
uint256 length = poolInfoList.length;
for (uint256 i = 0; i < length; i++) {
_updatePool(i);
}
}
/**
* @notice Updates reward variables of the given pool to be up-to-date
* @param _poolToken the address of pool token
*/
function updatePool(address _poolToken) public {
uint256 poolId = _getPoolId(_poolToken);
_updatePool(poolId);
}
function _updatePool(uint256 _poolId) internal {
PoolInfo storage pool = poolInfoList[_poolId];
uint256 rewardTokensLength = pool.rewardTokens.length;
for (uint256 i = 0; i < rewardTokensLength; i++) {
_updatePoolRewardToken(pool, _poolId, pool.rewardTokens[i]);
}
}
function _updatePoolRewardToken(
PoolInfo storage pool,
uint256 _poolId,
address _rewardToken
) internal {
PoolInfoRewardToken storage poolRewardToken = poolInfoRewardTokensMap[_poolId][_rewardToken];
// this pool has been updated recently
if (block.number <= poolRewardToken.lastRewardBlock) {
return;
}
uint256 poolTokenBalance = pool.poolToken.balanceOf(address(this));
if (poolTokenBalance == 0) {
poolRewardToken.lastRewardBlock = block.number;
return;
}
RewardToken storage rewardToken = rewardTokensMap[_rewardToken];
(uint256 accumulatedReward_, uint256 accumulatedRewardPerShare_) = _getPoolAccumulatedReward(pool, poolRewardToken, rewardToken);
poolRewardToken.accumulatedRewardPerShare = poolRewardToken.accumulatedRewardPerShare.add(accumulatedRewardPerShare_);
poolRewardToken.lastRewardBlock = block.number;
rewardToken.totalUsersBalance = rewardToken.totalUsersBalance.add(accumulatedReward_);
}
function _getPoolAccumulatedReward(
PoolInfo storage _pool,
PoolInfoRewardToken storage _poolRewardToken,
RewardToken storage _rewardToken
) internal view returns (uint256, uint256) {
return _getPoolAccumulatedReward(_pool, 0, _rewardToken, _poolRewardToken, block.number);
}
function _getPoolAccumulatedReward(
PoolInfo storage _pool,
uint256 _additionalAmount,
RewardToken storage _rewardToken,
PoolInfoRewardToken storage _poolRewardToken,
uint256 _endBlock
) internal view returns (uint256, uint256) {
return
_getPoolAccumulatedReward(
_pool,
_additionalAmount,
_rewardToken,
_poolRewardToken,
_poolRewardToken.lastRewardBlock,
_endBlock
);
}
function _getPoolAccumulatedReward(
PoolInfo storage _pool,
uint256 _additionalAmount,
RewardToken storage _rewardToken,
PoolInfoRewardToken storage _poolRewardToken,
uint256 _startBlock,
uint256 _endBlock
) internal view returns (uint256, uint256) {
uint256 passedBlocks = _getPassedBlocks(_rewardToken, _startBlock, _endBlock);
uint256 accumulatedReward =
passedBlocks.mul(_rewardToken.rewardTokensPerBlock).mul(PRECISION).mul(_poolRewardToken.allocationPoint).div(
_rewardToken.totalAllocationPoint
);
uint256 poolTokenBalance = _pool.poolToken.balanceOf(address(this));
poolTokenBalance = poolTokenBalance.add(_additionalAmount);
uint256 accumulatedRewardPerShare = accumulatedReward.div(poolTokenBalance);
return (accumulatedReward.div(PRECISION), accumulatedRewardPerShare);
}
/**
* @notice deposits pool tokens
* @param _poolToken the address of pool token
* @param _amount the amount of pool tokens
* @param _user the address of user, tokens will be deposited to it or to msg.sender
*/
function deposit(
address _poolToken,
uint256 _amount,
address _user
) external {
require(migrationFinished, "Migration is not over yet");
_deposit(_poolToken, _amount, _user, false);
}
/**
* @notice if the lending pools directly mint/transfer tokens to this address, process it like a user deposit
* @dev only callable by the pool which issues the tokens
* @param _user the user address
* @param _amount the minted amount
*/
function onTokensDeposited(address _user, uint256 _amount) external {
//the msg.sender is the pool token. if the msg.sender is not a valid pool token, _deposit will revert
_deposit(msg.sender, _amount, _user, true);
}
/**
* @notice internal function for depositing pool tokens
* @param _poolToken the address of pool token
* @param _amount the amount of pool tokens
* @param _user the address of user, tokens will be deposited to it
* @param alreadyTransferred true if the pool tokens have already been transferred
*/
function _deposit(
address _poolToken,
uint256 _amount,
address _user,
bool alreadyTransferred
) internal {
require(poolIdList[_poolToken] != 0, "Pool token not found");
address userAddress = _user != address(0) ? _user : msg.sender;
uint256 poolId = _getPoolId(_poolToken);
PoolInfo storage pool = poolInfoList[poolId];
UserInfo storage user = userInfoMap[poolId][userAddress];
uint256 rewardTokensLength = pool.rewardTokens.length;
for (uint256 i = 0; i < rewardTokensLength; i++) {
address rewardTokenAddress = pool.rewardTokens[i];
_updatePoolRewardToken(pool, poolId, rewardTokenAddress);
//sends reward directly to the user
_updateReward(poolId, rewardTokenAddress, user);
}
if (_amount > 0) {
//receives pool tokens from msg.sender, it can be user or WrapperProxy contract
if (!alreadyTransferred) pool.poolToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
for (uint256 i = 0; i < rewardTokensLength; i++) {
address rewardTokenAddress = pool.rewardTokens[i];
_updateRewardDebt(poolId, rewardTokenAddress, user);
}
emit Deposit(userAddress, _poolToken, _amount);
}
/**
* @notice transfers reward tokens
* @param _poolToken the address of pool token
* @param _user the address of user to claim reward from (can be passed only by wrapper contract)
*/
function claimRewards(address _poolToken, address _user) external {
address userAddress = _getUserAddress(_user);
uint256 poolId = _getPoolId(_poolToken);
PoolInfo storage pool = poolInfoList[poolId];
uint256 rewardTokensLength = pool.rewardTokens.length;
for (uint256 i = 0; i < rewardTokensLength; i++) {
address rewardTokenAddress = pool.rewardTokens[i];
_claimReward(poolId, rewardTokenAddress, userAddress);
}
}
/**
* @notice transfers rewards from a specific reward token
* @param _poolToken the address of pool token
* @param _rewardToken the address of reward token
* @param _user the address of user to claim reward from (can be passed only by wrapper contract)
*/
function claimReward(
address _poolToken,
address _rewardToken,
address _user
) external {
address userAddress = _getUserAddress(_user);
uint256 poolId = _getPoolId(_poolToken);
_claimReward(poolId, _rewardToken, userAddress);
}
function _claimReward(
uint256 _poolId,
address _rewardToken,
address _userAddress
) internal {
UserInfo storage user = userInfoMap[_poolId][_userAddress];
PoolInfo storage pool = poolInfoList[_poolId];
_updatePoolRewardToken(pool, _poolId, _rewardToken);
_updateReward(_poolId, _rewardToken, user);
_transferReward(_rewardToken, user, _userAddress, false, true);
_updateRewardDebt(_poolId, _rewardToken, user);
}
/**
* @notice transfers reward tokens from all pools
* @param _user the address of user to claim reward from (can be passed only by wrapper contract)
*/
function claimRewardFromAllPools(address _user) external {
address userAddress = _getUserAddress(_user);
uint256 length = poolInfoList.length;
for (uint256 i = 0; i < length; i++) {
uint256 poolId = i;
PoolInfo storage pool = poolInfoList[poolId];
uint256 rewardTokensLength = pool.rewardTokens.length;
for (uint256 j = 0; j < rewardTokensLength; j++) {
address rewardTokenAddress = pool.rewardTokens[j];
_claimReward(poolId, rewardTokenAddress, userAddress);
}
}
}
/**
* @notice withdraws pool tokens and transfers reward tokens
* @param _poolToken the address of pool token
* @param _amount the amount of pool tokens
* @param _user the user address will be used to process a withdrawal (can be passed only by wrapper contract)
*/
function withdraw(
address _poolToken,
uint256 _amount,
address _user
) external {
require(poolIdList[_poolToken] != 0, "Pool token not found");
address userAddress = _getUserAddress(_user);
uint256 poolId = _getPoolId(_poolToken);
PoolInfo storage pool = poolInfoList[poolId];
UserInfo storage user = userInfoMap[poolId][userAddress];
require(user.amount >= _amount, "Not enough balance");
// Start collecting rewards for each reward token the user holds
uint256 rewardTokensLength = pool.rewardTokens.length;
for (uint256 i = 0; i < rewardTokensLength; i++) {
address rewardTokenAddress = pool.rewardTokens[i];
_updatePoolRewardToken(pool, poolId, rewardTokenAddress);
_updateReward(poolId, rewardTokenAddress, user);
_transferReward(rewardTokenAddress, user, userAddress, true, false);
}
user.amount = user.amount.sub(_amount);
//msg.sender is wrapper -> send to wrapper
if (msg.sender == wrapper) {
pool.poolToken.safeTransfer(address(msg.sender), _amount);
}
//msg.sender is user or pool token (lending pool) -> send to user
else {
pool.poolToken.safeTransfer(userAddress, _amount);
}
for (uint256 i = 0; i < rewardTokensLength; i++) {
address rewardTokenAddress = pool.rewardTokens[i];
_updateRewardDebt(poolId, rewardTokenAddress, user);
}
emit Withdraw(userAddress, _poolToken, _amount);
}
function _getUserAddress(address _user) internal view returns (address) {
address userAddress = msg.sender;
if (_user != address(0)) {
//only wrapper can pass _user parameter
require(msg.sender == wrapper || poolIdList[msg.sender] != 0, "only wrapper or pools may withdraw for a user");
userAddress = _user;
}
return userAddress;
}
function _updateReward(
uint256 _poolId,
address _rewardTokenAddress,
UserInfo storage user
) internal {
UserReward storage reward = user.rewards[_rewardTokenAddress];
//update user accumulated reward
if (user.amount > 0) {
//add reward for the previous amount of deposited tokens
uint256 accumulatedReward =
user.amount.mul(poolInfoRewardTokensMap[_poolId][_rewardTokenAddress].accumulatedRewardPerShare).div(PRECISION).sub(
reward.rewardDebt
);
reward.accumulatedReward = reward.accumulatedReward.add(accumulatedReward);
}
}
function _updateRewardDebt(
uint256 poolId,
address rewardToken,
UserInfo storage user
) internal {
//reward accumulated before amount update (should be subtracted during next reward calculation)
user.rewards[rewardToken].rewardDebt = user.amount.mul(poolInfoRewardTokensMap[poolId][rewardToken].accumulatedRewardPerShare).div(
PRECISION
);
}
/**
* @notice Send reward in SOV to the lockedSOV vault.
* @param _user The user info, to get its reward share.
* @param _userAddress The address of the user, to send SOV in its behalf.
* @param _isWithdrawal The flag whether determines if the user is withdrawing all the funds
* @param _isCheckingBalance The flag whether we need to throw error or don't process reward if SOV balance isn't enough
*/
function _transferReward(
address _rewardToken,
UserInfo storage _user,
address _userAddress,
bool _isWithdrawal,
bool _isCheckingBalance
) internal {
uint256 userAccumulatedReward = _user.rewards[_rewardToken].accumulatedReward;
RewardToken storage rewardToken = rewardTokensMap[_rewardToken];
IERC20 token = IERC20(_rewardToken);
/// @dev Transfer if enough token balance on this LM contract.
uint256 balance = token.balanceOf(address(this));
if (balance >= userAccumulatedReward) {
rewardToken.totalUsersBalance = rewardToken.totalUsersBalance.sub(userAccumulatedReward);
_user.rewards[_rewardToken].accumulatedReward = 0;
IRewardTransferLogic transferLogic = rewardToken.rewardTransferLogic;
require(token.approve(transferLogic.senderToAuthorize(), userAccumulatedReward), "Approve failed");
transferLogic.transferReward(_userAddress, userAccumulatedReward, _isWithdrawal);
/// @dev Event log.
emit RewardClaimed(_userAddress, _rewardToken, userAccumulatedReward);
} else {
require(!_isCheckingBalance, "Claiming reward failed");
}
}
/**
* @notice withdraws pool tokens without transferring reward tokens
* @param _poolToken the address of pool token
* @dev EMERGENCY ONLY
*/
function emergencyWithdraw(address _poolToken) external {
uint256 poolId = _getPoolId(_poolToken);
PoolInfo storage pool = poolInfoList[poolId];
UserInfo storage user = userInfoMap[poolId][msg.sender];
uint256 rewardTokensLength = pool.rewardTokens.length;
for (uint256 i = 0; i < rewardTokensLength; i++) {
address rewardTokenAddress = pool.rewardTokens[i];
_updatePoolRewardToken(pool, poolId, rewardTokenAddress);
_updateReward(poolId, rewardTokenAddress, user);
// substract user balance from total balance for each reward token
UserReward storage userReward = user.rewards[pool.rewardTokens[i]];
uint256 accumulatedReward = userReward.accumulatedReward;
RewardToken storage rewardToken = rewardTokensMap[pool.rewardTokens[i]];
rewardToken.totalUsersBalance = rewardToken.totalUsersBalance.sub(accumulatedReward);
emit EmergencyWithdraw(msg.sender, _poolToken, rewardTokenAddress, user.amount, accumulatedReward);
userReward.rewardDebt = 0;
userReward.accumulatedReward = 0;
}
uint256 userAmount = user.amount;
user.amount = 0;
pool.poolToken.safeTransfer(address(msg.sender), userAmount);
for (uint256 i = 0; i < rewardTokensLength; i++) {
address rewardTokenAddress = pool.rewardTokens[i];
_updateRewardDebt(poolId, rewardTokenAddress, user);
}
}
function getRewardToken(address _rewardToken) external view returns (RewardToken memory) {
return rewardTokensMap[_rewardToken];
}
/**
* @notice returns a list of PoolInfoRewardToken for the given pool
* @param _poolToken the address of pool token
*/
function getPoolRewards(address _poolToken) external view returns (PoolInfoRewardToken[] memory) {
uint256 poolId = _getPoolId(_poolToken);
PoolInfo memory poolInfo = poolInfoList[poolId];
uint256 rewardsLength = poolInfo.rewardTokens.length;
PoolInfoRewardToken[] memory rewards = new PoolInfoRewardToken[](rewardsLength);
for (uint256 i = 0; i < rewardsLength; i++) {
rewards[i] = poolInfoRewardTokensMap[poolId][poolInfo.rewardTokens[i]];
}
return rewards;
}
/**
* @notice returns a PoolInfoRewardToken for the given pool and reward token
* @param _poolToken the address of pool token
* @param _rewardToken the address of reward token
*/
function getPoolReward(address _poolToken, address _rewardToken) public view returns (PoolInfoRewardToken memory) {
uint256 poolId = _getPoolId(_poolToken);
return poolInfoRewardTokensMap[poolId][_rewardToken];
}
/**
* @notice returns pool id
* @param _poolToken the address of pool token
*/
function getPoolId(address _poolToken) external view returns (uint256) {
return _getPoolId(_poolToken);
}
function _getPoolId(address _poolToken) internal view returns (uint256) {
uint256 poolId = poolIdList[_poolToken];
require(poolId > 0, "Pool token not found");
return poolId - 1;
}
/**
* @notice returns count of pool tokens
*/
function getPoolLength() external view returns (uint256) {
return poolInfoList.length;
}
/**
* @notice returns list of pool token's info
*/
function getPoolInfoList() external view returns (PoolInfo[] memory) {
return poolInfoList;
}
/**
* @notice returns pool info for the given token
* @param _poolToken the address of pool token
*/
function getPoolInfo(address _poolToken) external view returns (PoolInfo memory) {
uint256 poolId = _getPoolId(_poolToken);
return poolInfoList[poolId];
}
struct UserBalance {
uint256 amount;
address rewardToken;
uint256 accumulatedReward;
}
/**
* @notice returns list of [amount, rewardToken, accumulatedReward] for the given user for each pool token and reward token
* @param _user the address of the user
*/
function getUserBalanceList(address _user) external view returns (UserBalance[][] memory) {
uint256 length = poolInfoList.length;
UserBalance[][] memory userBalanceList = new UserBalance[][](length);
for (uint256 i = 0; i < length; i++) {
PoolInfo memory poolInfo = poolInfoList[i];
uint256 rewardLength = poolInfo.rewardTokens.length;
userBalanceList[i] = new UserBalance[](rewardLength);
for (uint256 j = 0; j < rewardLength; j++) {
address _rewardToken = poolInfo.rewardTokens[j];
userBalanceList[i][j].amount = userInfoMap[i][_user].amount;
userBalanceList[i][j].rewardToken = _rewardToken;
userBalanceList[i][j].accumulatedReward = _getUserAccumulatedReward(i, _rewardToken, _user);
}
}
return userBalanceList;
}
struct PoolUserInfo {
uint256 amount;
UserReward[] rewards;
}
/**
* @notice returns UserInfo for the given pool and user
* @param _poolToken the address of pool token
* @param _user the address of the user
*/
function getUserInfo(address _poolToken, address _user) public view returns (PoolUserInfo memory) {
uint256 poolId = _getPoolId(_poolToken);
return _getPoolUserInfo(poolId, _user);
}
/**
* @notice returns list of UserInfo for the given user for each pool token
* @param _user the address of the user
*/
function getUserInfoList(address _user) external view returns (PoolUserInfo[] memory) {
uint256 length = poolInfoList.length;
PoolUserInfo[] memory userInfoList = new PoolUserInfo[](length);
for (uint256 i = 0; i < length; i++) {
userInfoList[i] = _getPoolUserInfo(i, _user);
}
return userInfoList;
}
function _getPoolUserInfo(uint256 _poolId, address _user) internal view returns (PoolUserInfo memory) {
PoolInfo memory pool = poolInfoList[_poolId];
uint256 rewardsLength = pool.rewardTokens.length;
UserInfo storage userInfo = userInfoMap[_poolId][_user];
PoolUserInfo memory poolUserInfo;
poolUserInfo.amount = userInfo.amount;
poolUserInfo.rewards = new UserReward[](rewardsLength);
for (uint256 i = 0; i < rewardsLength; i++) {
poolUserInfo.rewards[i] = userInfo.rewards[pool.rewardTokens[i]];
}
return poolUserInfo;
}
struct UserAccumulatedReward {
address rewardToken;
uint256 accumulatedReward;
}
/**
* @notice returns accumulated reward for the given user for each pool token and reward token
* @param _user the address of the user
*/
function getUserAccumulatedRewardList(address _user) external view returns (UserAccumulatedReward[][] memory) {
uint256 length = poolInfoList.length;
UserAccumulatedReward[][] memory rewardList = new UserAccumulatedReward[][](length);
for (uint256 i = 0; i < length; i++) {
PoolInfo memory poolInfo = poolInfoList[i];
uint256 rewardsLength = poolInfo.rewardTokens.length;
rewardList[i] = new UserAccumulatedReward[](rewardsLength);
for (uint256 j = 0; j < rewardsLength; j++) {
rewardList[i][j].rewardToken = poolInfo.rewardTokens[j];
rewardList[i][j].accumulatedReward = _getUserAccumulatedReward(i, poolInfo.rewardTokens[j], _user);
}
}
return rewardList;
}
/**
* @notice returns the pool token balance a user has on the contract
* @param _poolToken the address of pool token
* @param _user the address of the user
*/
function getUserPoolTokenBalance(address _poolToken, address _user) external view returns (uint256) {
uint256 poolId = _getPoolId(_poolToken);
return userInfoMap[poolId][_user].amount;
}
function setPoolInfoRewardToken(
address _poolToken,
address _rewardToken,
uint256 _lastRewardBlock,
uint256 _accumulatedRewardPerShare
) external onlyAuthorized {
require(msg.sender == migrator, "only allowed to migrator contract");
uint256 poolId = _getPoolId(_poolToken);
PoolInfoRewardToken storage poolInfoRewardToken = poolInfoRewardTokensMap[poolId][_rewardToken];
poolInfoRewardToken.lastRewardBlock = _lastRewardBlock;
poolInfoRewardToken.accumulatedRewardPerShare = _accumulatedRewardPerShare;
}
function setRewardToken(
address _rewardToken,
uint256 _startBlock,
uint256 _totalUsersBalance
) external onlyAuthorized {
require(msg.sender == migrator, "only allowed to migrator contract");
RewardToken storage rewardToken = rewardTokensMap[_rewardToken];
rewardToken.startBlock = _startBlock;
rewardToken.totalUsersBalance = _totalUsersBalance;
}
function setUserInfo(
uint256 _poolId,
address _user,
address _rewardToken,
uint256 _amount,
uint256 _rewardDebt,
uint256 _accumulatedReward
) external onlyAuthorized {
require(msg.sender == migrator, "only allowed to migrator contract");
UserInfo storage userInfo = userInfoMap[_poolId][_user];
userInfo.amount = _amount;
userInfo.rewards[_rewardToken] = UserReward(_rewardDebt, _accumulatedReward);
}
/**
* @notice finish migration
*/
function finishMigration() external onlyAuthorized {
require(msg.sender == migrator, "only allowed to migrator contract");
migrationFinished = true;
}
}
|
returns list of UserInfo for the given user for each pool token _user the address of the user/
|
function getUserInfoList(address _user) external view returns (PoolUserInfo[] memory) {
uint256 length = poolInfoList.length;
PoolUserInfo[] memory userInfoList = new PoolUserInfo[](length);
for (uint256 i = 0; i < length; i++) {
userInfoList[i] = _getPoolUserInfo(i, _user);
}
return userInfoList;
}
| 15,797,203 |
pragma solidity 0.6.6;
import "../interfaces/ISmartWalletSwapImplementation.sol";
import "./SmartWalletSwapStorage.sol";
import "@kyber.network/utils-sc/contracts/IERC20Ext.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
contract SmartWalletSwapImplementation is SmartWalletSwapStorage, ISmartWalletSwapImplementation {
using SafeERC20 for IERC20Ext;
using SafeMath for uint256;
event UpdatedSupportedPlatformWallets(address[] wallets, bool isSupported);
event UpdatedBurnGasHelper(IBurnGasHelper indexed gasHelper);
event UpdatedLendingImplementation(ISmartWalletLending impl);
event ApprovedAllowances(IERC20Ext[] tokens, address[] spenders, bool isReset);
event ClaimedPlatformFees(address[] wallets, IERC20Ext[] tokens, address claimer);
constructor(address _admin) public SmartWalletSwapStorage(_admin) {}
receive() external payable {}
function updateBurnGasHelper(IBurnGasHelper _burnGasHelper) external onlyAdmin {
if (burnGasHelper != _burnGasHelper) {
burnGasHelper = _burnGasHelper;
emit UpdatedBurnGasHelper(_burnGasHelper);
}
}
function updateLendingImplementation(ISmartWalletLending newImpl) external onlyAdmin {
require(newImpl != ISmartWalletLending(0), "invalid lending impl");
lendingImpl = newImpl;
emit UpdatedLendingImplementation(newImpl);
}
/// @dev to prevent other integrations to call trade from this contract
function updateSupportedPlatformWallets(address[] calldata wallets, bool isSupported)
external
onlyAdmin
{
for (uint256 i = 0; i < wallets.length; i++) {
supportedPlatformWallets[wallets[i]] = isSupported;
}
emit UpdatedSupportedPlatformWallets(wallets, isSupported);
}
function claimPlatformFees(address[] calldata platformWallets, IERC20Ext[] calldata tokens)
external
override
nonReentrant
{
for (uint256 i = 0; i < platformWallets.length; i++) {
for (uint256 j = 0; j < tokens.length; j++) {
uint256 fee = platformWalletFees[platformWallets[i]][tokens[j]];
if (fee > 1) {
platformWalletFees[platformWallets[i]][tokens[j]] = 1;
transferToken(payable(platformWallets[i]), tokens[j], fee - 1);
}
}
}
emit ClaimedPlatformFees(platformWallets, tokens, msg.sender);
}
function approveAllowances(
IERC20Ext[] calldata tokens,
address[] calldata spenders,
bool isReset
) external onlyAdmin {
uint256 allowance = isReset ? 0 : MAX_ALLOWANCE;
for (uint256 i = 0; i < tokens.length; i++) {
for (uint256 j = 0; j < spenders.length; j++) {
tokens[i].safeApprove(spenders[j], allowance);
}
getSetDecimals(tokens[i]);
}
emit ApprovedAllowances(tokens, spenders, isReset);
}
/// ========== SWAP ========== ///
/// @dev swap token via Kyber
/// @notice for some tokens that are paying fee, for example: DGX
/// contract will trade with received src token amount (after minus fee)
/// for Kyber, fee will be taken in ETH as part of their feature
function swapKyber(
IERC20Ext src,
IERC20Ext dest,
uint256 srcAmount,
uint256 minConversionRate,
address payable recipient,
uint256 platformFeeBps,
address payable platformWallet,
bytes calldata hint,
bool useGasToken
) external payable override nonReentrant returns (uint256 destAmount) {
uint256 gasBefore = useGasToken ? gasleft() : 0;
destAmount = doKyberTrade(
src,
dest,
srcAmount,
minConversionRate,
recipient,
platformFeeBps,
platformWallet,
hint
);
uint256 numGasBurns = 0;
// burn gas token if needed
if (useGasToken) {
numGasBurns = burnGasTokensAfter(gasBefore);
}
emit KyberTrade(
msg.sender,
src,
dest,
srcAmount,
destAmount,
recipient,
platformFeeBps,
platformWallet,
hint,
useGasToken,
numGasBurns
);
}
/// @dev swap token via a supported Uniswap router
/// @notice for some tokens that are paying fee, for example: DGX
/// contract will trade with received src token amount (after minus fee)
/// for Uniswap, fee will be taken in src token
function swapUniswap(
IUniswapV2Router02 router,
uint256 srcAmount,
uint256 minDestAmount,
address[] calldata tradePath,
address payable recipient,
uint256 platformFeeBps,
address payable platformWallet,
bool feeInSrc,
bool useGasToken
) external payable override nonReentrant returns (uint256 destAmount) {
uint256 numGasBurns;
{
// prevent stack too deep
uint256 gasBefore = useGasToken ? gasleft() : 0;
destAmount = swapUniswapInternal(
router,
srcAmount,
minDestAmount,
tradePath,
recipient,
platformFeeBps,
platformWallet,
feeInSrc
);
if (useGasToken) {
numGasBurns = burnGasTokensAfter(gasBefore);
}
}
emit UniswapTrade(
msg.sender,
address(router),
tradePath,
srcAmount,
destAmount,
recipient,
platformFeeBps,
platformWallet,
feeInSrc,
useGasToken,
numGasBurns
);
}
/// ========== SWAP & DEPOSIT ========== ///
function swapKyberAndDeposit(
ISmartWalletLending.LendingPlatform platform,
IERC20Ext src,
IERC20Ext dest,
uint256 srcAmount,
uint256 minConversionRate,
uint256 platformFeeBps,
address payable platformWallet,
bytes calldata hint,
bool useGasToken
) external payable override nonReentrant returns (uint256 destAmount) {
require(lendingImpl != ISmartWalletLending(0));
uint256 gasBefore = useGasToken ? gasleft() : 0;
if (src == dest) {
// just collect src token, no need to swap
destAmount = safeForwardTokenToLending(
src,
msg.sender,
payable(address(lendingImpl)),
srcAmount
);
} else {
destAmount = doKyberTrade(
src,
dest,
srcAmount,
minConversionRate,
payable(address(lendingImpl)),
platformFeeBps,
platformWallet,
hint
);
}
// eth or token alr transferred to the address
lendingImpl.depositTo(platform, msg.sender, dest, destAmount);
uint256 numGasBurns = 0;
if (useGasToken) {
numGasBurns = burnGasTokensAfter(gasBefore);
}
emit KyberTradeAndDeposit(
msg.sender,
platform,
src,
dest,
srcAmount,
destAmount,
platformFeeBps,
platformWallet,
hint,
useGasToken,
numGasBurns
);
}
/// @dev swap Uniswap then deposit to platform
/// if tradePath has only 1 token, don't need to do swap
/// @param platform platform to deposit
/// @param router which Uni-clone to use for swapping
/// @param srcAmount amount of src token
/// @param minDestAmount minimal accepted dest amount
/// @param tradePath path of the trade on Uniswap
/// @param platformFeeBps fee if swapping
/// @param platformWallet wallet to receive fee
/// @param useGasToken whether to use gas token or not
function swapUniswapAndDeposit(
ISmartWalletLending.LendingPlatform platform,
IUniswapV2Router02 router,
uint256 srcAmount,
uint256 minDestAmount,
address[] calldata tradePath,
uint256 platformFeeBps,
address payable platformWallet,
bool useGasToken
) external payable override nonReentrant returns (uint256 destAmount) {
require(lendingImpl != ISmartWalletLending(0));
uint256 gasBefore = useGasToken ? gasleft() : 0;
{
IERC20Ext dest = IERC20Ext(tradePath[tradePath.length - 1]);
if (tradePath.length == 1) {
// just collect src token, no need to swap
destAmount = safeForwardTokenToLending(
dest,
msg.sender,
payable(address(lendingImpl)),
srcAmount
);
} else {
destAmount = swapUniswapInternal(
router,
srcAmount,
minDestAmount,
tradePath,
payable(address(lendingImpl)),
platformFeeBps,
platformWallet,
false
);
}
// eth or token alr transferred to the address
lendingImpl.depositTo(platform, msg.sender, dest, destAmount);
}
uint256 numGasBurns = 0;
if (useGasToken) {
numGasBurns = burnGasTokensAfter(gasBefore);
}
emit UniswapTradeAndDeposit(
msg.sender,
platform,
router,
tradePath,
srcAmount,
destAmount,
platformFeeBps,
platformWallet,
useGasToken,
numGasBurns
);
}
/// @dev withdraw token from Lending platforms (AAVE, COMPOUND)
/// @param platform platform to withdraw token
/// @param token underlying token to withdraw, e.g ETH, USDT, DAI
/// @param amount amount of cToken (COMPOUND) or aToken (AAVE) to withdraw
/// @param minReturn minimum amount of USDT tokens to return
/// @param useGasToken whether to use gas token or not
/// @return returnedAmount returns the amount withdrawn to the user
function withdrawFromLendingPlatform(
ISmartWalletLending.LendingPlatform platform,
IERC20Ext token,
uint256 amount,
uint256 minReturn,
bool useGasToken
) external override nonReentrant returns (uint256 returnedAmount) {
require(lendingImpl != ISmartWalletLending(0));
uint256 gasBefore = useGasToken ? gasleft() : 0;
IERC20Ext lendingToken = IERC20Ext(lendingImpl.getLendingToken(platform, token));
require(lendingToken != IERC20Ext(0), "unsupported token");
// AAVE aToken's transfer logic could have rounding errors
uint256 tokenBalanceBefore = lendingToken.balanceOf(address(lendingImpl));
lendingToken.safeTransferFrom(msg.sender, address(lendingImpl), amount);
uint256 tokenBalanceAfter = lendingToken.balanceOf(address(lendingImpl));
returnedAmount = lendingImpl.withdrawFrom(
platform,
msg.sender,
token,
tokenBalanceAfter.sub(tokenBalanceBefore),
minReturn
);
uint256 numGasBurns;
if (useGasToken) {
numGasBurns = burnGasTokensAfter(gasBefore);
}
emit WithdrawFromLending(
platform,
token,
amount,
minReturn,
returnedAmount,
useGasToken,
numGasBurns
);
}
/// @dev swap on Kyber and repay borrow for sender
/// if src == dest, no need to swap, use src token to repay directly
/// @param payAmount: amount that user wants to pay, if the dest amount (after swap) is higher,
/// the remain amount will be sent back to user's wallet
/// @param feeAndRateMode: in case of aave v2, user needs to specify the rateMode to repay
/// to prevent stack too deep, combine fee and rateMode into a single value
/// platformFee: feeAndRateMode % BPS, rateMode: feeAndRateMode / BPS
/// Other params are params for trade on Kyber
function swapKyberAndRepay(
ISmartWalletLending.LendingPlatform platform,
IERC20Ext src,
IERC20Ext dest,
uint256 srcAmount,
uint256 payAmount,
uint256 feeAndRateMode,
address payable platformWallet,
bytes calldata hint,
bool useGasToken
) external payable override nonReentrant returns (uint256 destAmount) {
uint256 numGasBurns;
{
require(lendingImpl != ISmartWalletLending(0));
uint256 gasBefore = useGasToken ? gasleft() : 0;
{
// use user debt value if debt is <= payAmount,
// user can pay all debt by putting really high payAmount as param
payAmount = checkUserDebt(platform, address(dest), payAmount);
if (src == dest) {
if (src == ETH_TOKEN_ADDRESS) {
require(msg.value == srcAmount, "invalid msg value");
transferToken(payable(address(lendingImpl)), src, srcAmount);
} else {
destAmount = srcAmount > payAmount ? payAmount : srcAmount;
src.safeTransferFrom(msg.sender, address(lendingImpl), destAmount);
}
} else {
// use user debt value if debt is <= payAmount
payAmount = checkUserDebt(platform, address(dest), payAmount);
// use min rate so it can return earlier if failed to swap
uint256 minRate =
calcRateFromQty(srcAmount, payAmount, src.decimals(), dest.decimals());
destAmount = doKyberTrade(
src,
dest,
srcAmount,
minRate,
payable(address(lendingImpl)),
feeAndRateMode % BPS,
platformWallet,
hint
);
}
}
lendingImpl.repayBorrowTo(
platform,
msg.sender,
dest,
destAmount,
payAmount,
feeAndRateMode / BPS
);
if (useGasToken) {
numGasBurns = burnGasTokensAfter(gasBefore);
}
}
emit KyberTradeAndRepay(
msg.sender,
platform,
src,
dest,
srcAmount,
destAmount,
payAmount,
feeAndRateMode,
platformWallet,
hint,
useGasToken,
numGasBurns
);
}
/// @dev swap on Uni-clone and repay borrow for sender
/// if tradePath.length == 1, no need to swap, use tradePath[0] token to repay directly
/// @param payAmount: amount that user wants to pay, if the dest amount (after swap) is higher,
/// the remain amount will be sent back to user's wallet
/// @param feeAndRateMode: in case of aave v2, user needs to specify the rateMode to repay
/// to prevent stack too deep, combine fee and rateMode into a single value
/// platformFee: feeAndRateMode % BPS, rateMode: feeAndRateMode / BPS
/// Other params are params for trade on Uni-clone
function swapUniswapAndRepay(
ISmartWalletLending.LendingPlatform platform,
IUniswapV2Router02 router,
uint256 srcAmount,
uint256 payAmount,
address[] calldata tradePath,
uint256 feeAndRateMode,
address payable platformWallet,
bool useGasToken
) external payable override nonReentrant returns (uint256 destAmount) {
uint256 numGasBurns;
{
// scope to prevent stack too deep
require(lendingImpl != ISmartWalletLending(0));
uint256 gasBefore = useGasToken ? gasleft() : 0;
IERC20Ext dest = IERC20Ext(tradePath[tradePath.length - 1]);
// use user debt value if debt is <= payAmount
// user can pay all debt by putting really high payAmount as param
payAmount = checkUserDebt(platform, address(dest), payAmount);
if (tradePath.length == 1) {
if (dest == ETH_TOKEN_ADDRESS) {
require(msg.value == srcAmount, "invalid msg value");
transferToken(payable(address(lendingImpl)), dest, srcAmount);
} else {
destAmount = srcAmount > payAmount ? payAmount : srcAmount;
dest.safeTransferFrom(msg.sender, address(lendingImpl), destAmount);
}
} else {
destAmount = swapUniswapInternal(
router,
srcAmount,
payAmount,
tradePath,
payable(address(lendingImpl)),
feeAndRateMode % BPS,
platformWallet,
false
);
}
lendingImpl.repayBorrowTo(
platform,
msg.sender,
dest,
destAmount,
payAmount,
feeAndRateMode / BPS
);
if (useGasToken) {
numGasBurns = burnGasTokensAfter(gasBefore);
}
}
emit UniswapTradeAndRepay(
msg.sender,
platform,
router,
tradePath,
srcAmount,
destAmount,
payAmount,
feeAndRateMode,
platformWallet,
useGasToken,
numGasBurns
);
}
function claimComp(
address[] calldata holders,
ICompErc20[] calldata cTokens,
bool borrowers,
bool suppliers,
bool useGasToken
) external override nonReentrant {
uint256 gasBefore = useGasToken ? gasleft() : 0;
lendingImpl.claimComp(holders, cTokens, borrowers, suppliers);
if (useGasToken) {
burnGasTokensAfter(gasBefore);
}
}
/// @dev get expected return and conversion rate if using Kyber
function getExpectedReturnKyber(
IERC20Ext src,
IERC20Ext dest,
uint256 srcAmount,
uint256 platformFee,
bytes calldata hint
) external view override returns (uint256 destAmount, uint256 expectedRate) {
try kyberProxy.getExpectedRateAfterFee(src, dest, srcAmount, platformFee, hint) returns (
uint256 rate
) {
expectedRate = rate;
} catch {
expectedRate = 0;
}
destAmount = calcDestAmount(src, dest, srcAmount, expectedRate);
}
/// @dev get expected return and conversion rate if using a Uniswap router
function getExpectedReturnUniswap(
IUniswapV2Router02 router,
uint256 srcAmount,
address[] calldata tradePath,
uint256 platformFee
) external view override returns (uint256 destAmount, uint256 expectedRate) {
if (platformFee >= BPS) return (0, 0); // platform fee is too high
if (!isRouterSupported[router]) return (0, 0); // router is not supported
uint256 srcAmountAfterFee = (srcAmount * (BPS - platformFee)) / BPS;
if (srcAmountAfterFee == 0) return (0, 0);
// in case pair is not supported
try router.getAmountsOut(srcAmountAfterFee, tradePath) returns (uint256[] memory amounts) {
destAmount = amounts[tradePath.length - 1];
} catch {
destAmount = 0;
}
expectedRate = calcRateFromQty(
srcAmountAfterFee,
destAmount,
getDecimals(IERC20Ext(tradePath[0])),
getDecimals(IERC20Ext(tradePath[tradePath.length - 1]))
);
}
function checkUserDebt(
ISmartWalletLending.LendingPlatform platform,
address token,
uint256 amount
) internal returns (uint256) {
uint256 debt = lendingImpl.storeAndRetrieveUserDebtCurrent(platform, token, msg.sender);
if (debt >= amount) {
return amount;
}
return debt;
}
function doKyberTrade(
IERC20Ext src,
IERC20Ext dest,
uint256 srcAmount,
uint256 minConversionRate,
address payable recipient,
uint256 platformFeeBps,
address payable platformWallet,
bytes memory hint
) internal virtual returns (uint256 destAmount) {
uint256 actualSrcAmount =
validateAndPrepareSourceAmount(address(kyberProxy), src, srcAmount, platformWallet);
uint256 callValue = src == ETH_TOKEN_ADDRESS ? actualSrcAmount : 0;
destAmount = kyberProxy.tradeWithHintAndFee{value: callValue}(
src,
actualSrcAmount,
dest,
recipient,
MAX_AMOUNT,
minConversionRate,
platformWallet,
platformFeeBps,
hint
);
}
function swapUniswapInternal(
IUniswapV2Router02 router,
uint256 srcAmount,
uint256 minDestAmount,
address[] memory tradePath,
address payable recipient,
uint256 platformFeeBps,
address payable platformWallet,
bool feeInSrc
) internal returns (uint256 destAmount) {
TradeInput memory input =
TradeInput({
srcAmount: srcAmount,
minData: minDestAmount,
recipient: recipient,
platformFeeBps: platformFeeBps,
platformWallet: platformWallet,
hint: ""
});
// extra validation when swapping on Uniswap
require(isRouterSupported[router], "unsupported router");
require(platformFeeBps < BPS, "high platform fee");
IERC20Ext src = IERC20Ext(tradePath[0]);
input.srcAmount = validateAndPrepareSourceAmount(
address(router),
src,
srcAmount,
platformWallet
);
destAmount = doUniswapTrade(router, src, tradePath, input, feeInSrc);
}
function doUniswapTrade(
IUniswapV2Router02 router,
IERC20Ext src,
address[] memory tradePath,
TradeInput memory input,
bool feeInSrc
) internal virtual returns (uint256 destAmount) {
uint256 tradeLen = tradePath.length;
IERC20Ext actualDest = IERC20Ext(tradePath[tradeLen - 1]);
{
// convert eth -> weth address to trade on Uniswap
if (tradePath[0] == address(ETH_TOKEN_ADDRESS)) {
tradePath[0] = router.WETH();
}
if (tradePath[tradeLen - 1] == address(ETH_TOKEN_ADDRESS)) {
tradePath[tradeLen - 1] = router.WETH();
}
}
uint256 srcAmountFee;
uint256 srcAmountAfterFee;
uint256 destBalanceBefore;
address recipient;
if (feeInSrc) {
srcAmountFee = input.srcAmount.mul(input.platformFeeBps).div(BPS);
srcAmountAfterFee = input.srcAmount.sub(srcAmountFee);
recipient = input.recipient;
} else {
srcAmountAfterFee = input.srcAmount;
destBalanceBefore = getBalance(actualDest, address(this));
recipient = address(this);
}
uint256[] memory amounts;
if (src == ETH_TOKEN_ADDRESS) {
// swap eth -> token
amounts = router.swapExactETHForTokens{value: srcAmountAfterFee}(
input.minData,
tradePath,
recipient,
MAX_AMOUNT
);
} else {
if (actualDest == ETH_TOKEN_ADDRESS) {
// swap token -> eth
amounts = router.swapExactTokensForETH(
srcAmountAfterFee,
input.minData,
tradePath,
recipient,
MAX_AMOUNT
);
} else {
// swap token -> token
amounts = router.swapExactTokensForTokens(
srcAmountAfterFee,
input.minData,
tradePath,
recipient,
MAX_AMOUNT
);
}
}
if (!feeInSrc) {
// fee in dest token, calculated received dest amount
uint256 destBalanceAfter = getBalance(actualDest, address(this));
destAmount = destBalanceAfter.sub(destBalanceBefore);
uint256 destAmountFee = destAmount.mul(input.platformFeeBps).div(BPS);
// charge fee in dest token
addFeeToPlatform(input.platformWallet, actualDest, destAmountFee);
// transfer back dest token to recipient
destAmount = destAmount.sub(destAmountFee);
transferToken(input.recipient, actualDest, destAmount);
} else {
// fee in src amount
destAmount = amounts[amounts.length - 1];
addFeeToPlatform(input.platformWallet, src, srcAmountFee);
}
}
function validateAndPrepareSourceAmount(
address protocol,
IERC20Ext src,
uint256 srcAmount,
address platformWallet
) internal virtual returns (uint256 actualSrcAmount) {
require(supportedPlatformWallets[platformWallet], "unsupported platform wallet");
if (src == ETH_TOKEN_ADDRESS) {
require(msg.value == srcAmount, "wrong msg value");
actualSrcAmount = srcAmount;
} else {
require(msg.value == 0, "bad msg value");
uint256 balanceBefore = src.balanceOf(address(this));
src.safeTransferFrom(msg.sender, address(this), srcAmount);
uint256 balanceAfter = src.balanceOf(address(this));
actualSrcAmount = balanceAfter.sub(balanceBefore);
require(actualSrcAmount > 0, "invalid src amount");
safeApproveAllowance(protocol, src);
}
}
function burnGasTokensAfter(uint256 gasBefore) internal virtual returns (uint256 numGasBurns) {
if (burnGasHelper == IBurnGasHelper(0)) return 0;
IGasToken gasToken;
uint256 gasAfter = gasleft();
try
burnGasHelper.getAmountGasTokensToBurn(gasBefore.sub(gasAfter).add(msg.data.length))
returns (uint256 _gasBurns, address _gasToken) {
numGasBurns = _gasBurns;
gasToken = IGasToken(_gasToken);
} catch {
numGasBurns = 0;
}
if (numGasBurns > 0 && gasToken != IGasToken(0)) {
numGasBurns = gasToken.freeFromUpTo(msg.sender, numGasBurns);
}
}
function safeForwardTokenToLending(
IERC20Ext token,
address from,
address payable to,
uint256 amount
) internal returns (uint256 destAmount) {
if (token == ETH_TOKEN_ADDRESS) {
require(msg.value >= amount, "low msg value");
(bool success, ) = to.call{value: amount}("");
require(success, "transfer eth failed");
destAmount = amount;
} else {
uint256 balanceBefore = token.balanceOf(to);
token.safeTransferFrom(from, to, amount);
destAmount = token.balanceOf(to).sub(balanceBefore);
}
}
function addFeeToPlatform(
address wallet,
IERC20Ext token,
uint256 amount
) internal {
if (amount > 0) {
platformWalletFees[wallet][token] = platformWalletFees[wallet][token].add(amount);
}
}
function transferToken(
address payable recipient,
IERC20Ext token,
uint256 amount
) internal {
if (amount == 0) return;
if (token == ETH_TOKEN_ADDRESS) {
(bool success, ) = recipient.call{value: amount}("");
require(success, "failed to transfer eth");
} else {
token.safeTransfer(recipient, amount);
}
}
function safeApproveAllowance(address spender, IERC20Ext token) internal {
if (token.allowance(address(this), spender) == 0) {
getSetDecimals(token);
token.safeApprove(spender, MAX_ALLOWANCE);
}
}
}
|
swap token via Kyber for some tokens that are paying fee, for example: DGX contract will trade with received src token amount (after minus fee) for Kyber, fee will be taken in ETH as part of their feature burn gas token if needed
|
function swapKyber(
IERC20Ext src,
IERC20Ext dest,
uint256 srcAmount,
uint256 minConversionRate,
address payable recipient,
uint256 platformFeeBps,
address payable platformWallet,
bytes calldata hint,
bool useGasToken
) external payable override nonReentrant returns (uint256 destAmount) {
uint256 gasBefore = useGasToken ? gasleft() : 0;
destAmount = doKyberTrade(
src,
dest,
srcAmount,
minConversionRate,
recipient,
platformFeeBps,
platformWallet,
hint
);
uint256 numGasBurns = 0;
if (useGasToken) {
numGasBurns = burnGasTokensAfter(gasBefore);
}
emit KyberTrade(
msg.sender,
src,
dest,
srcAmount,
destAmount,
recipient,
platformFeeBps,
platformWallet,
hint,
useGasToken,
numGasBurns
);
}
| 13,060,717 |
pragma solidity ^0.5.10;
contract NEST_NodeSave {
IBMapping mappingContract;
IBNEST nestContract;
constructor (address map) public {
mappingContract = IBMapping(address(map));
nestContract = IBNEST(address(mappingContract.CHECKADDRESS222("nest")));
}
function CHANGEMAPPING301(address map) public ONLYOWNER374 { //inject NONSTANDARD NAMING
mappingContract = IBMapping(address(map));
nestContract = IBNEST(address(mappingContract.CHECKADDRESS222("nest")));
}
function TURNOUT485(uint256 amount, address to) public ONLYMININGCALCULATION602 returns(uint256) { //inject NONSTANDARD NAMING
uint256 leftNum = nestContract.BALANCEOF780(address(this));
if (leftNum >= amount) {
nestContract.TRANSFER685(to, amount);
return amount;
} else {
return 0;
}
}
modifier ONLYOWNER374(){ //inject NONSTANDARD NAMING
require(mappingContract.CHECKOWNERS909(msg.sender) == true);
_;
}
modifier ONLYMININGCALCULATION602(){ //inject NONSTANDARD NAMING
require(address(mappingContract.CHECKADDRESS222("nodeAssignment")) == msg.sender);
_;
}
}
contract NEST_NodeAssignmentData {
using SafeMath for uint256;
IBMapping mappingContract;
uint256 nodeAllAmount = 0;
mapping(address => uint256) nodeLatestAmount;
constructor (address map) public {
mappingContract = IBMapping(map);
}
function CHANGEMAPPING301(address map) public ONLYOWNER374{ //inject NONSTANDARD NAMING
mappingContract = IBMapping(map);
}
// Add nest
function ADDNEST102(uint256 amount) public ONLYNODEASSIGNMENT511 { //inject NONSTANDARD NAMING
nodeAllAmount = nodeAllAmount.ADD302(amount);
}
// View cumulative total
function CHECKNODEALLAMOUNT929() public view returns (uint256) { //inject NONSTANDARD NAMING
return nodeAllAmount;
}
// Record last received quantity
function ADDNODELATESTAMOUNT655(address add ,uint256 amount) public ONLYNODEASSIGNMENT511 { //inject NONSTANDARD NAMING
nodeLatestAmount[add] = amount;
}
// View last received quantity
function CHECKNODELATESTAMOUNT653(address add) public view returns (uint256) { //inject NONSTANDARD NAMING
return nodeLatestAmount[address(add)];
}
modifier ONLYOWNER374(){ //inject NONSTANDARD NAMING
require(mappingContract.CHECKOWNERS909(msg.sender) == true);
_;
}
modifier ONLYNODEASSIGNMENT511(){ //inject NONSTANDARD NAMING
require(address(msg.sender) == address(mappingContract.CHECKADDRESS222("nodeAssignment")));
_;
}
}
contract NEST_NodeAssignment {
using SafeMath for uint256;
IBMapping mappingContract;
IBNEST nestContract;
SuperMan supermanContract;
NEST_NodeSave nodeSave;
NEST_NodeAssignmentData nodeAssignmentData;
constructor (address map) public {
mappingContract = IBMapping(map);
nestContract = IBNEST(address(mappingContract.CHECKADDRESS222("nest")));
supermanContract = SuperMan(address(mappingContract.CHECKADDRESS222("nestNode")));
nodeSave = NEST_NodeSave(address(mappingContract.CHECKADDRESS222("nestNodeSave")));
nodeAssignmentData = NEST_NodeAssignmentData(address(mappingContract.CHECKADDRESS222("nodeAssignmentData")));
}
function CHANGEMAPPING301(address map) public ONLYOWNER374{ //inject NONSTANDARD NAMING
mappingContract = IBMapping(map);
nestContract = IBNEST(address(mappingContract.CHECKADDRESS222("nest")));
supermanContract = SuperMan(address(mappingContract.CHECKADDRESS222("nestNode")));
nodeSave = NEST_NodeSave(address(mappingContract.CHECKADDRESS222("nestNodeSave")));
nodeAssignmentData = NEST_NodeAssignmentData(address(mappingContract.CHECKADDRESS222("nodeAssignmentData")));
}
function BOOKKEEPING887(uint256 amount) public { //inject NONSTANDARD NAMING
require(amount > 0);
require(nestContract.BALANCEOF780(address(msg.sender)) >= amount);
require(nestContract.ALLOWANCE615(address(msg.sender), address(this)) >= amount);
require(nestContract.TRANSFERFROM303(address(msg.sender), address(nodeSave), amount));
nodeAssignmentData.ADDNEST102(amount);
}
function NODEGET172() public { //inject NONSTANDARD NAMING
require(address(msg.sender) == address(tx.origin));
require(supermanContract.BALANCEOF780(address(msg.sender)) > 0);
uint256 allAmount = nodeAssignmentData.CHECKNODEALLAMOUNT929();
uint256 amount = allAmount.SUB809(nodeAssignmentData.CHECKNODELATESTAMOUNT653(address(msg.sender)));
uint256 getAmount = amount.MUL451(supermanContract.BALANCEOF780(address(msg.sender))).DIV932(1500);
require(nestContract.BALANCEOF780(address(nodeSave)) >= getAmount);
nodeSave.TURNOUT485(getAmount,address(msg.sender));
nodeAssignmentData.ADDNODELATESTAMOUNT655(address(msg.sender),allAmount);
}
function NODECOUNT170(address fromAdd, address toAdd) public { //inject NONSTANDARD NAMING
require(address(supermanContract) == address(msg.sender));
require(supermanContract.BALANCEOF780(address(fromAdd)) > 0);
uint256 allAmount = nodeAssignmentData.CHECKNODEALLAMOUNT929();
uint256 amountFrom = allAmount.SUB809(nodeAssignmentData.CHECKNODELATESTAMOUNT653(address(fromAdd)));
uint256 getAmountFrom = amountFrom.MUL451(supermanContract.BALANCEOF780(address(fromAdd))).DIV932(1500);
require(nestContract.BALANCEOF780(address(nodeSave)) >= getAmountFrom);
nodeSave.TURNOUT485(getAmountFrom,address(fromAdd));
nodeAssignmentData.ADDNODELATESTAMOUNT655(address(fromAdd),allAmount);
uint256 amountTo = allAmount.SUB809(nodeAssignmentData.CHECKNODELATESTAMOUNT653(address(toAdd)));
uint256 getAmountTo = amountTo.MUL451(supermanContract.BALANCEOF780(address(toAdd))).DIV932(1500);
require(nestContract.BALANCEOF780(address(nodeSave)) >= getAmountTo);
nodeSave.TURNOUT485(getAmountTo,address(toAdd));
nodeAssignmentData.ADDNODELATESTAMOUNT655(address(toAdd),allAmount);
}
// Amount available to the guardian node
function CHECKNODENUM994() public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 allAmount = nodeAssignmentData.CHECKNODEALLAMOUNT929();
uint256 amount = allAmount.SUB809(nodeAssignmentData.CHECKNODELATESTAMOUNT653(address(msg.sender)));
uint256 getAmount = amount.MUL451(supermanContract.BALANCEOF780(address(msg.sender))).DIV932(1500);
return getAmount;
}
modifier ONLYOWNER374(){ //inject NONSTANDARD NAMING
require(mappingContract.CHECKOWNERS909(msg.sender) == true);
_;
}
}
interface IERC20 {
function TOTALSUPPLY171() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF780(address who) external view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE615(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER685(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE777(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM303(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER309(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL404(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract SuperMan is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
IBMapping mappingContract; //1111
uint256 private _totalSupply = 1500;
string public name = "NestNode";
string public symbol = "NN";
uint8 public decimals = 0;
constructor (address map) public {
_balances[msg.sender] = _totalSupply;
mappingContract = IBMapping(map);
}
function CHANGEMAPPING301(address map) public ONLYOWNER374{ //inject NONSTANDARD NAMING
mappingContract = IBMapping(map);
}
function TOTALSUPPLY171() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF780(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[owner];
}
function ALLOWANCE615(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowed[owner][spender];
}
function TRANSFER685(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER545(msg.sender, to, value);
return true;
}
function APPROVE777(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit APPROVAL404(msg.sender, spender, value);
return true;
}
function TRANSFERFROM303(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_allowed[from][msg.sender] = _allowed[from][msg.sender].SUB809(value);
_TRANSFER545(from, to, value);
emit APPROVAL404(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
function INCREASEALLOWANCE778(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].ADD302(addedValue);
emit APPROVAL404(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function DECREASEALLOWANCE839(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].SUB809(subtractedValue);
emit APPROVAL404(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function _TRANSFER545(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
require(to != address(0));
NEST_NodeAssignment nodeAssignment = NEST_NodeAssignment(address(mappingContract.CHECKADDRESS222("nodeAssignment")));
nodeAssignment.NODECOUNT170(from, to);
_balances[from] = _balances[from].SUB809(value);
_balances[to] = _balances[to].ADD302(value);
emit TRANSFER309(from, to, value);
}
modifier ONLYOWNER374(){ //inject NONSTANDARD NAMING
require(mappingContract.CHECKOWNERS909(msg.sender) == true);
_;
}
}
library SafeMath {
int256 constant private int256_min212 = -2**255; //inject NONSTANDARD NAMING
function MUL451(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function MUL451(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == int256_min212)); // This is the only case of overflow not detected by the check below
int256 c = a * b;
require(c / a == b);
return c;
}
function DIV932(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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;
}
function DIV932(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING
require(b != 0); // Solidity only automatically asserts when dividing by 0
require(!(b == -1 && a == int256_min212)); // This is the only case of overflow
int256 c = a / b;
return c;
}
function SUB809(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
uint256 c = a - b;
return c;
}
function SUB809(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
function ADD302(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function ADD302(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
function MOD929(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0);
return a % b;
}
}
contract IBMapping {
function CHECKADDRESS222(string memory name) public view returns (address contractAddress); //inject NONSTANDARD NAMING
function CHECKOWNERS909(address man) public view returns (bool); //inject NONSTANDARD NAMING
}
contract IBNEST {
function TOTALSUPPLY171() public view returns (uint supply); //inject NONSTANDARD NAMING
function BALANCEOF780( address who ) public view returns (uint value); //inject NONSTANDARD NAMING
function ALLOWANCE615( address owner, address spender ) public view returns (uint _allowance); //inject NONSTANDARD NAMING
function TRANSFER685( address to, uint256 value) external; //inject NONSTANDARD NAMING
function TRANSFERFROM303( address from, address to, uint value) public returns (bool ok); //inject NONSTANDARD NAMING
function APPROVE777( address spender, uint value ) public returns (bool ok); //inject NONSTANDARD NAMING
event TRANSFER309( address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
event APPROVAL404( address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
function BALANCESSTART356() public view returns(uint256); //inject NONSTANDARD NAMING
function BALANCESGETBOOL55(uint256 num) public view returns(bool); //inject NONSTANDARD NAMING
function BALANCESGETNEXT455(uint256 num) public view returns(uint256); //inject NONSTANDARD NAMING
function BALANCESGETVALUE432(uint256 num) public view returns(address, uint256); //inject NONSTANDARD NAMING
}
|
inject NONSTANDARD NAMING
|
function NODECOUNT170(address fromAdd, address toAdd) public {
| 898,767 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.